11#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
12#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
15#define CATCH_VERSION_MAJOR 2
16#define CATCH_VERSION_MINOR 13
17#define CATCH_VERSION_PATCH 9
20#pragma clang system_header
22#pragma GCC system_header
30#pragma warning(disable : 161 1682)
32#pragma clang diagnostic push
33#pragma clang diagnostic ignored "-Wpadded"
34#pragma clang diagnostic ignored "-Wswitch-enum"
35#pragma clang diagnostic ignored "-Wcovered-switch-default"
41#pragma GCC diagnostic ignored "-Wparentheses"
43#pragma GCC diagnostic push
44#pragma GCC diagnostic ignored "-Wunused-variable"
45#pragma GCC diagnostic ignored "-Wpadded"
48#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
50#define CATCH_CONFIG_ALL_PARTS
55#if defined(CATCH_CONFIG_ALL_PARTS)
56#define CATCH_CONFIG_EXTERNAL_INTERFACES
57#if defined(CATCH_CONFIG_DISABLE_MATCHERS)
58#undef CATCH_CONFIG_DISABLE_MATCHERS
60#if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
61#define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
65#if !defined(CATCH_CONFIG_IMPL_ONLY)
71#include <TargetConditionals.h>
72#if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1)
73#define CATCH_PLATFORM_MAC
74#elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1)
75#define CATCH_PLATFORM_IPHONE
78#elif defined(linux) || defined(__linux) || defined(__linux__)
79#define CATCH_PLATFORM_LINUX
81#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || \
83#define CATCH_PLATFORM_WINDOWS
89#ifndef CLARA_CONFIG_MAIN
90#define CLARA_CONFIG_MAIN_NOT_DEFINED
91#define CLARA_CONFIG_MAIN
98unsigned int rngSeed();
127#if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
128#define CATCH_CPP14_OR_GREATER
131#if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
132#define CATCH_CPP17_OR_GREATER
139#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && \
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(...) \
166 (void)__builtin_constant_p(__VA_ARGS__)
170#define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
171 _Pragma("clang diagnostic ignored \"-Wexit-time-destructors\"") \
172 _Pragma("clang diagnostic ignored \"-Wglobal-constructors\"")
174#define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
175 _Pragma("clang diagnostic ignored \"-Wparentheses\"")
177#define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
178 _Pragma("clang diagnostic ignored \"-Wunused-variable\"")
180#define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
181 _Pragma("clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"")
183#define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
184 _Pragma("clang diagnostic ignored \"-Wunused-template\"")
190#if !defined(CATCH_PLATFORM_WINDOWS)
191#define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
196#if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
197#define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
201#define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
202#define CATCH_CONFIG_COLOUR_NONE
207#if defined(__ANDROID__)
208#define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
209#define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
214#if defined(__MINGW32__)
215#define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
220#if defined(__ORBIS__)
221#define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
236#if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) && \
237 !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
239#define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
250#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
251#define CATCH_CONFIG_COLOUR_NONE
253#define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
256#if !defined(__clang__)
261#if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
262#define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
267#define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma(warning(push))
268#define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma(warning(pop))
273#if defined(_REENTRANT) || defined(_MSC_VER)
276#define CATCH_INTERNAL_CONFIG_USE_ASYNC
281#if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
282#define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
288#define CATCH_INTERNAL_CONFIG_NO_WCHAR
293#if defined(__BORLANDC__)
294#define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
304#if (!defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L)
305#define CATCH_INTERNAL_CONFIG_COUNTER
313#if defined(UNDER_RTSS) || defined(RTX64_BUILD)
314#define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
315#define CATCH_INTERNAL_CONFIG_NO_ASYNC
316#define CATCH_CONFIG_COLOUR_NONE
319#if !defined(_GLIBCXX_USE_C99_MATH_TR1)
320#define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
324#if defined(__has_include)
326#if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
327#define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
331#if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
332#define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
336#if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
338#if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0)
339#define CATCH_INTERNAL_CONFIG_CPP17_BYTE
344#if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
345#if defined(__clang__) && (__clang_major__ < 8)
350#if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
351#define CATCH_CONFIG_NO_CPP17_VARIANT
353#define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
357#define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
362#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && \
363 !defined(CATCH_CONFIG_COUNTER)
364#define CATCH_CONFIG_COUNTER
366#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && \
367 !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
368#define CATCH_CONFIG_WINDOWS_SEH
372#if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && \
373 !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && \
374 !defined(CATCH_CONFIG_POSIX_SIGNALS)
375#define CATCH_CONFIG_POSIX_SIGNALS
379#if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && \
380 !defined(CATCH_CONFIG_WCHAR)
381#define CATCH_CONFIG_WCHAR
384#if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && \
385 !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
386#define CATCH_CONFIG_CPP11_TO_STRING
389#if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && \
390 !defined(CATCH_CONFIG_CPP17_OPTIONAL)
391#define CATCH_CONFIG_CPP17_OPTIONAL
394#if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && \
395 !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
396#define CATCH_CONFIG_CPP17_STRING_VIEW
399#if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && \
400 !defined(CATCH_CONFIG_CPP17_VARIANT)
401#define CATCH_CONFIG_CPP17_VARIANT
404#if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && \
405 !defined(CATCH_CONFIG_CPP17_BYTE)
406#define CATCH_CONFIG_CPP17_BYTE
409#if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
410#define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
413#if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && \
414 !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && \
415 !defined(CATCH_CONFIG_NEW_CAPTURE)
416#define CATCH_CONFIG_NEW_CAPTURE
419#if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
420#define CATCH_CONFIG_DISABLE_EXCEPTIONS
423#if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && \
424 !defined(CATCH_CONFIG_POLYFILL_ISNAN)
425#define CATCH_CONFIG_POLYFILL_ISNAN
428#if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && \
429 !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
430#define CATCH_CONFIG_USE_ASYNC
433#if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && \
434 !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
435#define CATCH_CONFIG_ANDROID_LOGWRITE
438#if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && \
439 !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
440#define CATCH_CONFIG_GLOBAL_NEXTAFTER
445#if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
446#define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
448#if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
449#define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
451#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
452#define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
454#if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
455#define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
457#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
458#define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
460#if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
461#define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
466#if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
467#define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
470#if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
471#undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
472#elif defined(__clang__) && (__clang_major__ < 5)
473#undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
476#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
477#define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
480#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
481#define CATCH_TRY if ((true))
482#define CATCH_CATCH_ALL if ((false))
483#define CATCH_CATCH_ANON(type) if ((false))
486#define CATCH_CATCH_ALL catch (...)
487#define CATCH_CATCH_ANON(type) catch (type)
490#if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && \
491 !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && \
492 !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
493#define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
497#define INTERNAL_CATCH_UNIQUE_NAME_LINE2(name, line) name##line
498#define INTERNAL_CATCH_UNIQUE_NAME_LINE(name, line) INTERNAL_CATCH_UNIQUE_NAME_LINE2(name, line)
499#ifdef CATCH_CONFIG_COUNTER
500#define INTERNAL_CATCH_UNIQUE_NAME(name) INTERNAL_CATCH_UNIQUE_NAME_LINE(name, __COUNTER__)
502#define INTERNAL_CATCH_UNIQUE_NAME(name) INTERNAL_CATCH_UNIQUE_NAME_LINE(name, __LINE__)
517 enum Choice { Yes, No };
521 NonCopyable(NonCopyable
const&) =
delete;
522 NonCopyable(NonCopyable&&) =
delete;
523 NonCopyable& operator=(NonCopyable
const&) =
delete;
524 NonCopyable& operator=(NonCopyable&&) =
delete;
528 virtual ~NonCopyable();
531struct SourceLineInfo {
533 SourceLineInfo() =
delete;
534 SourceLineInfo(
char const* _file, std::size_t _line) noexcept : file(_file), line(_line) {}
536 SourceLineInfo(SourceLineInfo
const& other) =
default;
537 SourceLineInfo& operator=(SourceLineInfo
const&) =
default;
538 SourceLineInfo(SourceLineInfo&&)
noexcept =
default;
539 SourceLineInfo& operator=(SourceLineInfo&&)
noexcept =
default;
541 bool empty()
const noexcept {
return file[0] ==
'\0'; }
542 bool operator==(SourceLineInfo
const& other)
const noexcept;
543 bool operator<(SourceLineInfo
const& other)
const noexcept;
549std::ostream& operator<<(std::ostream& os,
SourceLineInfo const& info);
561 std::string operator+()
const;
563template <
typename T> T
const& operator+(T
const& value,
StreamEndStop) {
568#define CATCH_INTERNAL_LINEINFO \
569 ::Catch::SourceLineInfo(__FILE__, static_cast<std::size_t>(__LINE__))
574struct RegistrarForTagAliases {
575 RegistrarForTagAliases(
char const* alias,
char const* tag,
SourceLineInfo const& lineInfo);
580#define CATCH_REGISTER_TAG_ALIAS(alias, spec) \
581 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
582 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
584 Catch::RegistrarForTagAliases \
585 INTERNAL_CATCH_UNIQUE_NAME(AutoRegisterTagAlias)(alias, spec, CATCH_INTERNAL_LINEINFO); \
587 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
601 virtual void invoke()
const = 0;
610 virtual std::vector<TestCase>
const& getAllTests()
const = 0;
611 virtual std::vector<TestCase>
const& getAllTestsSorted(
IConfig const& config)
const = 0;
615bool matchTest(
TestCase const& testCase, TestSpec
const& testSpec,
IConfig const& config);
616std::vector<TestCase> filterTests(std::vector<TestCase>
const& testCases, TestSpec
const& testSpec,
618std::vector<TestCase>
const& getAllTestCasesSorted(
IConfig const& config);
637 using size_type = std::size_t;
638 using const_iterator =
const char*;
641 static constexpr char const*
const s_empty =
"";
643 char const* m_start = s_empty;
644 size_type m_size = 0;
647 constexpr StringRef()
noexcept =
default;
649 StringRef(
char const* rawChars)
noexcept;
651 constexpr StringRef(
char const* rawChars, size_type size) noexcept
652 : m_start(rawChars), m_size(size) {}
654 StringRef(std::string
const& stdString) noexcept
655 : m_start(stdString.c_str()), m_size(stdString.size()) {}
657 explicit operator std::string()
const {
return std::string(m_start, m_size); }
660 auto operator==(StringRef
const& other)
const noexcept -> bool;
661 auto operator!=(StringRef
const& other)
const noexcept ->
bool {
return !(*
this == other); }
663 auto operator[](size_type index)
const noexcept ->
char {
664 assert(index < m_size);
665 return m_start[index];
669 constexpr auto empty()
const noexcept ->
bool {
return m_size == 0; }
670 constexpr auto size()
const noexcept -> size_type {
return m_size; }
674 auto c_str()
const ->
char const*;
680 auto substr(size_type start, size_type length)
const noexcept -> StringRef;
683 auto data()
const noexcept ->
char const*;
685 constexpr auto isNullTerminated()
const noexcept ->
bool {
return m_start[m_size] ==
'\0'; }
688 constexpr const_iterator begin()
const {
return m_start; }
689 constexpr const_iterator end()
const {
return m_start + m_size; }
692auto operator+=(std::string& lhs,
StringRef const& sr) -> std::string&;
693auto operator<<(std::ostream& os,
StringRef const& sr) -> std::ostream&;
695constexpr auto operator"" _sr(
char const* rawChars, std::size_t size)
noexcept ->
StringRef {
700constexpr auto operator"" _catch_sr(
char const* rawChars, std::size_t size)
noexcept
708#define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
709#define CATCH_RECURSION_LEVEL1(...) \
710 CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
711#define CATCH_RECURSION_LEVEL2(...) \
712 CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
713#define CATCH_RECURSION_LEVEL3(...) \
714 CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
715#define CATCH_RECURSION_LEVEL4(...) \
716 CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
717#define CATCH_RECURSION_LEVEL5(...) \
718 CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
720#ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
721#define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
723#define CATCH_RECURSION_LEVEL6(...) \
724 CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
725#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
727#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
730#define CATCH_REC_END(...)
734#define CATCH_DEFER(id) id CATCH_EMPTY()
736#define CATCH_REC_GET_END2() 0, CATCH_REC_END
737#define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
738#define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
739#define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
740#define CATCH_REC_NEXT1(test, next) CATCH_DEFER(CATCH_REC_NEXT0)(test, next, 0)
741#define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
743#define CATCH_REC_LIST0(f, x, peek, ...) \
744 , f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1))(f, peek, __VA_ARGS__)
745#define CATCH_REC_LIST1(f, x, peek, ...) \
746 , f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST0))(f, peek, __VA_ARGS__)
747#define CATCH_REC_LIST2(f, x, peek, ...) \
748 f(x) CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1))(f, peek, __VA_ARGS__)
750#define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) \
752 CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD))(f, userdata, peek, __VA_ARGS__)
753#define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) \
755 CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD))(f, userdata, peek, __VA_ARGS__)
756#define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) \
758 CATCH_DEFER(CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD))(f, userdata, peek, __VA_ARGS__)
764#define CATCH_REC_LIST_UD(f, userdata, ...) \
765 CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
767#define CATCH_REC_LIST(f, ...) \
768 CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
770#define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
771#define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO##__VA_ARGS__
772#define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
773#define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
774#define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
775#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
776#define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
777#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) \
778 INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
782#define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
783#define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
784#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) \
785 (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
788#define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
789#define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
791#define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
793#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
794#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) \
795 decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
796#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) \
797 INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
799#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) \
800 INTERNAL_CATCH_EXPAND_VARGS( \
801 decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
802#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) \
803 INTERNAL_CATCH_EXPAND_VARGS( \
804 INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
807#define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...) \
808 CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST, __VA_ARGS__)
810#define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
811#define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) \
812 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
813#define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) \
814 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
815#define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) \
816 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3)
817#define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) \
818 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4)
819#define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) \
820 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5)
821#define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) \
822 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6)
823#define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) \
824 INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7)
825#define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) \
826 INTERNAL_CATCH_REMOVE_PARENS(_0), \
827 INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8)
828#define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) \
829 INTERNAL_CATCH_REMOVE_PARENS(_0), \
830 INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9)
831#define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) \
832 INTERNAL_CATCH_REMOVE_PARENS(_0), \
833 INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10)
835#define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
837#define INTERNAL_CATCH_TYPE_GEN \
838 template <typename...> struct TypeList {}; \
839 template <typename... Ts> constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { \
842 template <template <typename...> class...> struct TemplateTypeList {}; \
843 template <template <typename...> class... Cs> \
844 constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { \
847 template <typename...> struct append; \
848 template <typename...> struct rewrap; \
849 template <template <typename...> class, typename...> struct create; \
850 template <template <typename...> class, typename> struct convert; \
852 template <typename T> struct append<T> { \
855 template <template <typename...> class L1, typename... E1, template <typename...> class L2, \
856 typename... E2, typename... Rest> \
857 struct append<L1<E1...>, L2<E2...>, Rest...> { \
858 using type = typename append<L1<E1..., E2...>, Rest...>::type; \
860 template <template <typename...> class L1, typename... E1, typename... Rest> \
861 struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { \
862 using type = L1<E1...>; \
865 template <template <typename...> class Container, template <typename...> class List, \
867 struct rewrap<TemplateTypeList<Container>, List<elems...>> { \
868 using type = TypeList<Container<elems...>>; \
870 template <template <typename...> class Container, template <typename...> class List, \
871 class... Elems, typename... Elements> \
872 struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { \
873 using type = typename append< \
874 TypeList<Container<Elems...>>, \
875 typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; \
878 template <template <typename...> class Final, template <typename...> class... Containers, \
880 struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { \
881 using type = typename append< \
882 Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; \
884 template <template <typename...> class Final, template <typename...> class List, \
886 struct convert<Final, List<Ts...>> { \
887 using type = typename append<Final<>, TypeList<Ts>...>::type; \
890#define INTERNAL_CATCH_NTTP_1(signature, ...) \
891 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp {}; \
892 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
893 constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { \
896 template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> \
897 struct NttpTemplateTypeList {}; \
898 template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class... Cs> \
899 constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { \
903 template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, \
904 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, \
905 INTERNAL_CATCH_REMOVE_PARENS(signature)> \
906 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { \
907 using type = TypeList<Container<__VA_ARGS__>>; \
909 template <template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, \
910 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, \
911 INTERNAL_CATCH_REMOVE_PARENS(signature), typename... Elements> \
912 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { \
913 using type = typename append< \
914 TypeList<Container<__VA_ARGS__>>, \
915 typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; \
917 template <template <typename...> class Final, \
918 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> class... Containers, \
920 struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { \
921 using type = typename append< \
922 Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; \
925#define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
926#define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature) \
927 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
928#define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...) \
929 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
931#define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
932#define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature) \
933 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
934#define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature, ...) \
935 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> static void TestName()
937#define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature) \
938 template <typename Type> void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags) { \
939 Catch::AutoReg(Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, \
940 Catch::StringRef(), nameAndTags); \
943#define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...) \
944 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
945 void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags) { \
946 Catch::AutoReg(Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, \
947 Catch::StringRef(), nameAndTags); \
950#define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...) \
951 template <typename Type> \
952 void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags) { \
953 Catch::AutoReg(Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, \
954 className, nameAndTags); \
957#define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...) \
958 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
959 void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags) { \
960 Catch::AutoReg(Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), \
961 CATCH_INTERNAL_LINEINFO, className, nameAndTags); \
964#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
965#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature) \
966 template <typename TestType> \
967 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
971#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...) \
972 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
973 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
977#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
978#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature) \
979 template <typename TestType> \
980 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
981#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...) \
982 template <INTERNAL_CATCH_REMOVE_PARENS(signature)> \
983 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
985#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
986#define INTERNAL_CATCH_NTTP_0
987#define INTERNAL_CATCH_NTTP_GEN(...) \
988 INTERNAL_CATCH_VA_NARGS_IMPL( \
989 __VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
990 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
991 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
992 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
993 INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), \
994 INTERNAL_CATCH_NTTP_0)
995#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) \
996 INTERNAL_CATCH_VA_NARGS_IMPL( \
997 "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
998 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
999 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1000 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1001 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1002 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, \
1003 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)
1004#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) \
1005 INTERNAL_CATCH_VA_NARGS_IMPL( \
1006 "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1007 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1008 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1009 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1010 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1011 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, \
1012 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)
1013#define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) \
1014 INTERNAL_CATCH_VA_NARGS_IMPL( \
1015 "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1016 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1017 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1018 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1019 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1020 INTERNAL_CATCH_NTTP_REGISTER_METHOD0, \
1021 INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)
1022#define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) \
1023 INTERNAL_CATCH_VA_NARGS_IMPL( \
1024 "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1025 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1026 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1027 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, \
1028 INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)
1029#define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) \
1030 INTERNAL_CATCH_VA_NARGS_IMPL( \
1031 "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1032 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1033 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1034 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1035 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST1, \
1036 INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)
1037#define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) \
1038 INTERNAL_CATCH_VA_NARGS_IMPL( \
1039 "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1040 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1041 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1042 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1043 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1044 INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)
1045#define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) \
1046 INTERNAL_CATCH_VA_NARGS_IMPL( \
1047 __VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG, INTERNAL_CATCH_REMOVE_PARENS_10_ARG, \
1048 INTERNAL_CATCH_REMOVE_PARENS_9_ARG, INTERNAL_CATCH_REMOVE_PARENS_8_ARG, \
1049 INTERNAL_CATCH_REMOVE_PARENS_7_ARG, INTERNAL_CATCH_REMOVE_PARENS_6_ARG, \
1050 INTERNAL_CATCH_REMOVE_PARENS_5_ARG, INTERNAL_CATCH_REMOVE_PARENS_4_ARG, \
1051 INTERNAL_CATCH_REMOVE_PARENS_3_ARG, INTERNAL_CATCH_REMOVE_PARENS_2_ARG, \
1052 INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)
1054#define INTERNAL_CATCH_NTTP_0(signature)
1055#define INTERNAL_CATCH_NTTP_GEN(...) \
1056 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1057 __VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, \
1058 INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, \
1059 INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, \
1060 INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)(__VA_ARGS__))
1061#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) \
1062 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1063 "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1064 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1065 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1066 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1067 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, \
1068 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, \
1069 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__))
1070#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) \
1071 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1072 "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1073 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1074 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1075 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1076 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, \
1077 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, \
1078 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__))
1079#define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) \
1080 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1081 "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1082 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1083 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1084 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1085 INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, \
1086 INTERNAL_CATCH_NTTP_REGISTER_METHOD0, \
1087 INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__))
1088#define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) \
1089 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1090 "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1091 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1092 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, \
1093 INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, \
1094 INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__))
1095#define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) \
1096 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1097 "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1098 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1099 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1100 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1101 INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST1, \
1102 INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__))
1103#define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) \
1104 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1105 "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1106 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1107 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1108 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, \
1109 INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, \
1110 INTERNAL_CATCH_DECLARE_SIG_TEST1, \
1111 INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__))
1112#define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) \
1113 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( \
1114 __VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG, INTERNAL_CATCH_REMOVE_PARENS_10_ARG, \
1115 INTERNAL_CATCH_REMOVE_PARENS_9_ARG, INTERNAL_CATCH_REMOVE_PARENS_8_ARG, \
1116 INTERNAL_CATCH_REMOVE_PARENS_7_ARG, INTERNAL_CATCH_REMOVE_PARENS_6_ARG, \
1117 INTERNAL_CATCH_REMOVE_PARENS_5_ARG, INTERNAL_CATCH_REMOVE_PARENS_4_ARG, \
1118 INTERNAL_CATCH_REMOVE_PARENS_3_ARG, INTERNAL_CATCH_REMOVE_PARENS_2_ARG, \
1119 INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__))
1125#include <type_traits>
1132 template <
typename Fun,
typename... Args>
1134 template <
typename...> std::false_type
static test(...);
1139template <
typename Fun,
typename... Args>
1140struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
1142#if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
1145template <
typename Func,
typename... U>
1146using FunctionReturnType =
1147 std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
1150template <
typename Func,
typename... U>
1151using FunctionReturnType =
typename std::remove_reference<
1152 typename std::remove_cv<
typename std::result_of<Func(U...)>::type>::type>::type;
1165 void (C::*m_testAsMethod)();
1168 TestInvokerAsMethod(
void (C::*testAsMethod)()) noexcept : m_testAsMethod(testAsMethod) {}
1170 void invoke()
const override {
1172 (obj.*m_testAsMethod)();
1176auto makeTestInvoker(
void (*testAsFunction)()) noexcept ->
ITestInvoker*;
1178template <typename C> auto makeTestInvoker(
void (C::*testAsMethod)()) noexcept ->
ITestInvoker* {
1189struct AutoReg : NonCopyable {
1197#if defined(CATCH_CONFIG_DISABLE)
1198#define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(TestName, ...) static void TestName()
1199#define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(TestName, ClassName, ...) \
1201 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1205 void TestName::test()
1206#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2(TestName, TestFunc, Name, Tags, \
1208 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1209#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1210 TestNameClass, TestName, ClassName, Name, Tags, Signature, ...) \
1212 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1213 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, \
1214 INTERNAL_CATCH_REMOVE_PARENS(Signature)); \
1217 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1219#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1220#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1221 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \
1222 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1223 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, \
1224 typename TestType, __VA_ARGS__)
1226#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1227 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \
1228 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1229 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, \
1230 typename TestType, __VA_ARGS__))
1233#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1234#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1235 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \
1236 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1237 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, \
1238 Signature, __VA_ARGS__)
1240#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1241 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( \
1242 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1243 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, \
1244 Signature, __VA_ARGS__))
1247#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1248#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(ClassName, Name, Tags, ...) \
1249 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1250 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_), \
1251 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), ClassName, Name, Tags, \
1252 typename T, __VA_ARGS__)
1254#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(ClassName, Name, Tags, ...) \
1255 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1256 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_), \
1257 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), ClassName, Name, Tags, \
1258 typename T, __VA_ARGS__))
1261#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1262#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(ClassName, Name, Tags, \
1264 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1265 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_), \
1266 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), ClassName, Name, Tags, \
1267 Signature, __VA_ARGS__)
1269#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(ClassName, Name, Tags, \
1271 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( \
1272 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_), \
1273 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), ClassName, Name, Tags, \
1274 Signature, __VA_ARGS__))
1279#define INTERNAL_CATCH_TESTCASE2(TestName, ...) \
1280 static void TestName(); \
1281 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1282 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1284 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(Catch::makeTestInvoker(&TestName), \
1285 CATCH_INTERNAL_LINEINFO, \
1286 Catch::StringRef(), \
1287 Catch::NameAndTags{__VA_ARGS__}); \
1289 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1290 static void TestName()
1291#define INTERNAL_CATCH_TESTCASE(...) \
1292 INTERNAL_CATCH_TESTCASE2(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_), __VA_ARGS__)
1295#define INTERNAL_CATCH_METHOD_AS_TEST_CASE(QualifiedMethod, ...) \
1296 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1297 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1300 INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(Catch::makeTestInvoker(&QualifiedMethod), \
1301 CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, \
1302 Catch::NameAndTags{__VA_ARGS__}); \
1304 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1307#define INTERNAL_CATCH_TEST_CASE_METHOD2(TestName, ClassName, ...) \
1308 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1309 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1311 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1315 INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)(Catch::makeTestInvoker(&TestName::test), \
1316 CATCH_INTERNAL_LINEINFO, #ClassName, \
1317 Catch::NameAndTags{__VA_ARGS__}); \
1319 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1320 void TestName::test()
1321#define INTERNAL_CATCH_TEST_CASE_METHOD(ClassName, ...) \
1322 INTERNAL_CATCH_TEST_CASE_METHOD2(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_), ClassName, \
1326#define INTERNAL_CATCH_REGISTER_TESTCASE(Function, ...) \
1327 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1328 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1329 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME(autoRegistrar)( \
1330 Catch::makeTestInvoker(Function), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), \
1331 Catch::NameAndTags{__VA_ARGS__}); \
1332 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1335#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ...) \
1336 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1337 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1338 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1339 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1340 INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature)); \
1342 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1343 INTERNAL_CATCH_TYPE_GEN \
1344 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1345 INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1346 template <typename... Types> struct TestName { \
1349 constexpr char const* tmpl_types[] = { \
1350 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)}; \
1351 using expander = int[]; \
1353 (reg_test(Types{}, \
1354 Catch::NameAndTags{Name " - " + std::string(tmpl_types[index]), Tags}), \
1358 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1359 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>(); \
1364 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1365 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1367#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1368#define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1369 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \
1370 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1371 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, \
1372 typename TestType, __VA_ARGS__)
1374#define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1375 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \
1376 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1377 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, \
1378 typename TestType, __VA_ARGS__))
1381#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1382#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1383 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \
1384 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1385 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, \
1386 Signature, __VA_ARGS__)
1388#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1389 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( \
1390 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1391 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, \
1392 Signature, __VA_ARGS__))
1395#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, \
1396 TmplTypes, TypesList) \
1397 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1398 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1399 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1400 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1401 template <typename TestType> static void TestFuncName(); \
1403 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1404 INTERNAL_CATCH_TYPE_GEN \
1405 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1406 template <typename... Types> struct TestName { \
1407 void reg_tests() { \
1409 using expander = int[]; \
1410 constexpr char const* tmpl_types[] = { \
1411 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \
1412 INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))}; \
1413 constexpr char const* types_list[] = { \
1414 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \
1415 INTERNAL_CATCH_REMOVE_PARENS(TypesList))}; \
1416 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]); \
1418 (Catch::AutoReg(Catch::makeTestInvoker(&TestFuncName<Types>), \
1419 CATCH_INTERNAL_LINEINFO, Catch::StringRef(), \
1420 Catch::NameAndTags{ \
1421 Name " - " + std::string(tmpl_types[index / num_types]) + \
1422 "<" + std::string(types_list[index % num_types]) + ">", \
1427 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1429 typename create<TestName, \
1430 decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), \
1431 TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES( \
1432 INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
1439 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1440 template <typename TestType> static void TestFuncName()
1442#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1443#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...) \
1444 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \
1445 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1446 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, \
1447 typename T, __VA_ARGS__)
1449#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...) \
1450 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \
1451 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1452 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, \
1453 typename T, __VA_ARGS__))
1456#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1457#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1458 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \
1459 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1460 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, \
1461 Signature, __VA_ARGS__)
1463#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1464 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( \
1465 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1466 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, \
1467 Signature, __VA_ARGS__))
1470#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList) \
1471 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1472 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1473 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1474 template <typename TestType> static void TestFunc(); \
1476 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1477 INTERNAL_CATCH_TYPE_GEN \
1478 template <typename... Types> struct TestName { \
1479 void reg_tests() { \
1481 using expander = int[]; \
1483 (Catch::AutoReg(Catch::makeTestInvoker(&TestFunc<Types>), CATCH_INTERNAL_LINEINFO, \
1484 Catch::StringRef(), \
1485 Catch::NameAndTags{ \
1486 Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + \
1487 " - " + std::to_string(index), \
1492 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1493 using TestInit = typename convert<TestName, TmplList>::type; \
1500 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1501 template <typename TestType> static void TestFunc()
1503#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
1504 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( \
1505 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1506 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, \
1509#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, \
1511 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1512 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1513 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1514 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1516 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1517 INTERNAL_CATCH_TYPE_GEN \
1518 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1519 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, \
1520 INTERNAL_CATCH_REMOVE_PARENS(Signature)); \
1521 INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1522 template <typename... Types> struct TestNameClass { \
1525 constexpr char const* tmpl_types[] = { \
1526 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)}; \
1527 using expander = int[]; \
1529 (reg_test(Types{}, #ClassName, \
1530 Catch::NameAndTags{Name " - " + std::string(tmpl_types[index]), Tags}), \
1534 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1535 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>(); \
1540 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1541 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1543#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1544#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
1545 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \
1546 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_), \
1547 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), ClassName, Name, Tags, \
1548 typename T, __VA_ARGS__)
1550#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
1551 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \
1552 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_), \
1553 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), ClassName, Name, Tags, \
1554 typename T, __VA_ARGS__))
1557#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1558#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, ...) \
1559 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \
1560 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_), \
1561 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), ClassName, Name, Tags, \
1562 Signature, __VA_ARGS__)
1564#define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, ...) \
1565 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( \
1566 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_), \
1567 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), ClassName, Name, Tags, \
1568 Signature, __VA_ARGS__))
1571#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1572 TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList) \
1573 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1574 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1575 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1576 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1577 template <typename TestType> \
1578 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName<TestType>) { \
1582 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) { \
1583 INTERNAL_CATCH_TYPE_GEN \
1584 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1585 template <typename... Types> struct TestNameClass { \
1586 void reg_tests() { \
1588 using expander = int[]; \
1589 constexpr char const* tmpl_types[] = { \
1590 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \
1591 INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))}; \
1592 constexpr char const* types_list[] = { \
1593 CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, \
1594 INTERNAL_CATCH_REMOVE_PARENS(TypesList))}; \
1595 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]); \
1597 (Catch::AutoReg(Catch::makeTestInvoker(&TestName<Types>::test), \
1598 CATCH_INTERNAL_LINEINFO, #ClassName, \
1599 Catch::NameAndTags{ \
1600 Name " - " + std::string(tmpl_types[index / num_types]) + \
1601 "<" + std::string(types_list[index % num_types]) + ">", \
1606 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1608 typename create<TestNameClass, \
1609 decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), \
1610 TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES( \
1611 INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
1618 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1619 template <typename TestType> void TestName<TestType>::test()
1621#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1622#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
1623 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1624 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1625 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, \
1626 Tags, typename T, __VA_ARGS__)
1628#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(ClassName, Name, Tags, ...) \
1629 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1630 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1631 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, \
1632 Tags, typename T, __VA_ARGS__))
1635#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1636#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, \
1638 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1639 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1640 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, \
1641 Tags, Signature, __VA_ARGS__)
1643#define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(ClassName, Name, Tags, Signature, \
1645 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( \
1646 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1647 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, \
1648 Tags, Signature, __VA_ARGS__))
1651#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, \
1653 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1654 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1655 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1656 template <typename TestType> \
1657 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName<TestType>) { \
1661 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1662 INTERNAL_CATCH_TYPE_GEN \
1663 template <typename... Types> struct TestNameClass { \
1664 void reg_tests() { \
1666 using expander = int[]; \
1668 (Catch::AutoReg(Catch::makeTestInvoker(&TestName<Types>::test), \
1669 CATCH_INTERNAL_LINEINFO, #ClassName, \
1670 Catch::NameAndTags{ \
1671 Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + \
1672 " - " + std::to_string(index), \
1677 static int INTERNAL_CATCH_UNIQUE_NAME(globalRegistrar) = []() { \
1678 using TestInit = typename convert<TestNameClass, TmplList>::type; \
1685 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1686 template <typename TestType> void TestName<TestType>::test()
1688#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
1689 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( \
1690 INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_), \
1691 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, \
1715 ExpressionFailed = FailureBit | 1,
1716 ExplicitFailure = FailureBit | 2,
1718 Exception = 0x100 | FailureBit,
1720 ThrewException = Exception | 1,
1721 DidntThrowException = Exception | 2,
1723 FatalErrorCondition = 0x200 | FailureBit
1728bool isOk(ResultWas::OfType resultType);
1729bool isJustInfo(
int flags);
1736 ContinueOnFailure = 0x02,
1742ResultDisposition::Flags operator|(ResultDisposition::Flags lhs, ResultDisposition::Flags rhs);
1744bool shouldContinueOnFailure(
int flags);
1745inline bool isFalseTest(
int flags) {
1746 return (flags & ResultDisposition::FalseTest) != 0;
1748bool shouldSuppressFailure(
int flags);
1759 ResultDisposition::Flags resultDisposition;
1775#include <type_traits>
1785std::ostream& cout();
1786std::ostream& cerr();
1787std::ostream& clog();
1793 virtual std::ostream& stream()
const = 0;
1798class ReusableStringStream : NonCopyable {
1799 std::size_t m_index;
1800 std::ostream* m_oss;
1803 ReusableStringStream();
1804 ~ReusableStringStream();
1806 auto str()
const -> std::string;
1808 template <
typename T>
auto operator<<(T
const& value) -> ReusableStringStream& {
1812 auto get() -> std::ostream& {
return *m_oss; }
1826 std::vector<std::pair<int, StringRef>> m_values;
1838 std::vector<int>
const& values) = 0;
1840 template <
typename E>
1842 std::initializer_list<E> values) {
1843 static_assert(
sizeof(int) >=
sizeof(E),
"Cannot serialize enum to int");
1844 std::vector<int> intValues;
1845 intValues.reserve(values.size());
1846 for (
auto enumValue : values)
1847 intValues.push_back(
static_cast<int>(enumValue));
1848 return registerEnum(enumName, allEnums, intValues);
1856#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1857#include <string_view>
1863#import <Foundation/Foundation.h>
1866#define CATCH_ARC_ENABLED __has_feature(objc_arc)
1868#define CATCH_ARC_ENABLED 0
1871void arcSafeRelease(NSObject* obj);
1872id performOptionalSelector(
id obj,
SEL sel);
1874#if !CATCH_ARC_ENABLED
1875inline void arcSafeRelease(NSObject* obj) {
1878inline id performOptionalSelector(
id obj,
SEL sel) {
1879 if ([obj respondsToSelector:sel])
1880 return [obj performSelector:sel];
1883#define CATCH_UNSAFE_UNRETAINED
1884#define CATCH_ARC_STRONG
1886inline void arcSafeRelease(NSObject*) {}
1887inline id performOptionalSelector(
id obj,
SEL sel) {
1889#pragma clang diagnostic push
1890#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
1892 if ([obj respondsToSelector:sel])
1893 return [obj performSelector:sel];
1895#pragma clang diagnostic pop
1899#define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
1900#define CATCH_ARC_STRONG __strong
1907#pragma warning(push)
1908#pragma warning(disable : 4180)
1915extern const std::string unprintableString;
1917std::string rawMemoryToString(
const void*
object, std::size_t size);
1919template <
typename T> std::string rawMemoryToString(
const T&
object) {
1920 return rawMemoryToString(&
object,
sizeof(
object));
1924 template <
typename Stream,
typename U>
1925 static auto test(
int)
1926 ->
decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
1928 template <
typename,
typename>
static auto test(...) -> std::false_type;
1931 static const bool value =
decltype(test<std::ostream, const T&>(0))::value;
1934template <
typename E> std::string convertUnknownEnumToString(E e);
1936template <
typename T>
1937typename std::enable_if<!std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
1939convertUnstreamable(T
const&) {
1940 return Detail::unprintableString;
1942template <
typename T>
1943typename std::enable_if<!std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
1945convertUnstreamable(T
const& ex) {
1949template <
typename T>
1950typename std::enable_if<std::is_enum<T>::value, std::string>::type
1951convertUnstreamable(T
const& value) {
1952 return convertUnknownEnumToString(value);
1955#if defined(_MANAGED)
1957template <
typename T> std::string clrReferenceToString(T ^ ref) {
1959 return std::string(
"null");
1960 auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
1961 cli::pin_ptr<System::Byte> p = &bytes[0];
1962 return std::string(
reinterpret_cast<char const*
>(p), bytes->Length);
1970 template <
typename Fake = T>
1972 typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
1973 convert(
const Fake& value) {
1977 rss.operator<<(value);
1981 template <
typename Fake = T>
1982 static typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value,
1984 convert(
const Fake& value) {
1985#if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
1986 return Detail::convertUnstreamable(value);
1988 return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
1997template <
typename T> std::string stringify(
const T& e) {
1998 return ::Catch::StringMaker<
1999 typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
2002template <
typename E> std::string convertUnknownEnumToString(E e) {
2003 return ::Catch::Detail::stringify(
static_cast<typename std::underlying_type<E>::type
>(e));
2006#if defined(_MANAGED)
2007template <
typename T> std::string stringify(T ^ e) {
2008 return ::Catch::StringMaker<T ^>::convert(e);
2017 static std::string convert(
const std::string& str);
2020#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
2022 static std::string convert(std::string_view str);
2027 static std::string convert(
char const* str);
2030 static std::string convert(
char* str);
2033#ifdef CATCH_CONFIG_WCHAR
2035 static std::string convert(
const std::wstring& wstr);
2038#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
2039template <>
struct StringMaker<std::wstring_view> {
2040 static std::string convert(std::wstring_view str);
2045 static std::string convert(
wchar_t const* str);
2048 static std::string convert(
wchar_t* str);
2055 static std::string convert(
char const* str) {
2056 return ::Catch::Detail::stringify(std::string{str});
2060 static std::string convert(
signed char const* str) {
2061 return ::Catch::Detail::stringify(std::string{
reinterpret_cast<char const*
>(str)});
2065 static std::string convert(
unsigned char const* str) {
2066 return ::Catch::Detail::stringify(std::string{
reinterpret_cast<char const*
>(str)});
2070#if defined(CATCH_CONFIG_CPP17_BYTE)
2072 static std::string convert(std::byte value);
2076 static std::string convert(
int value);
2079 static std::string convert(
long value);
2082 static std::string convert(
long long value);
2085 static std::string convert(
unsigned int value);
2088 static std::string convert(
unsigned long value);
2091 static std::string convert(
unsigned long long value);
2095 static std::string convert(
bool b);
2099 static std::string convert(
char c);
2102 static std::string convert(
signed char c);
2105 static std::string convert(
unsigned char c);
2109 static std::string convert(std::nullptr_t);
2113 static std::string convert(
float value);
2114 static int precision;
2118 static std::string convert(
double value);
2119 static int precision;
2123 template <
typename U>
static std::string convert(U* p) {
2125 return ::Catch::Detail::rawMemoryToString(p);
2133 static std::string convert(R C::* p) {
2135 return ::Catch::Detail::rawMemoryToString(p);
2142#if defined(_MANAGED)
2144 static std::string convert(T ^ ref) { return ::Catch::Detail::clrReferenceToString(ref); }
2149template <
typename InputIterator,
typename Sentinel = InputIterator>
2150std::string rangeToString(InputIterator first, Sentinel last) {
2151 ReusableStringStream rss;
2153 if (first != last) {
2154 rss << ::Catch::Detail::stringify(*first);
2155 for (++first; first != last; ++first)
2156 rss <<
", " << ::Catch::Detail::stringify(*first);
2165 static std::string convert(NSString* nsstring) {
2168 return std::string(
"@") + [nsstring UTF8String];
2172 static std::string convert(NSObject* nsObject) {
2173 return ::Catch::Detail::stringify([nsObject description]);
2177inline std::string stringify(NSString* nsstring) {
2178 return StringMaker<NSString*>::convert(nsstring);
2190#if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
2191#define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
2192#define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
2193#define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
2194#define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2195#define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
2199#if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
2202template <
typename T1,
typename T2>
struct StringMaker<std::pair<T1, T2>> {
2203 static std::string convert(
const std::pair<T1, T2>& pair) {
2204 ReusableStringStream rss;
2205 rss <<
"{ " << ::Catch::Detail::stringify(pair.first) <<
", "
2206 << ::Catch::Detail::stringify(pair.second) <<
" }";
2213#if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
2216template <
typename T>
struct StringMaker<std::optional<T>> {
2217 static std::string convert(
const std::optional<T>& optional) {
2218 ReusableStringStream rss;
2219 if (optional.has_value()) {
2220 rss << ::Catch::Detail::stringify(*optional);
2231#if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
2235template <
typename Tuple, std::
size_t N = 0,
bool = (N < std::tuple_size<Tuple>::value)>
2236struct TupleElementPr
inter {
2237 static
void pr
int(const Tuple& tuple, std::ostream& os) {
2238 os << (N ? ", " : " ") << ::Catch::Detail::
stringify(std::get<N>(tuple));
2239 TupleElementPr
inter<Tuple, N + 1>::pr
int(tuple, os);
2243template <
typename Tuple, std::
size_t N>
struct TupleElementPrinter<Tuple, N, false> {
2244 static void print(
const Tuple&, std::ostream&) {}
2249template <
typename... Types>
struct StringMaker<std::tuple<Types...>> {
2250 static std::string convert(
const std::tuple<Types...>& tuple) {
2251 ReusableStringStream rss;
2253 Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
2261#if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
2265 static std::string convert(
const std::monostate&) {
return "{ }"; }
2268template <
typename... Elements>
struct StringMaker<std::variant<Elements...>> {
2269 static std::string convert(
const std::variant<Elements...>& variant) {
2270 if (variant.valueless_by_exception()) {
2271 return "{valueless variant}";
2273 return std::visit([](
const auto& value) { return ::Catch::Detail::stringify(value); },
2291template <
typename T,
typename =
void>
struct is_range_impl : std::false_type {};
2293template <
typename T>
2295 : std::true_type {};
2300#if defined(_MANAGED)
2301template <
typename T>
struct is_range<T ^> {
2302 static const bool value =
false;
2306template <
typename Range> std::string rangeToString(Range
const& range) {
2307 return ::Catch::Detail::rangeToString(begin(range), end(range));
2311template <
typename Allocator> std::string rangeToString(std::vector<bool, Allocator>
const& v) {
2320 rss << ::Catch::Detail::stringify(b);
2326template <
typename R>
2328 typename std::enable_if<is_range<R>::value &&
2329 !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
2330 static std::string convert(R
const& range) {
return rangeToString(range); }
2334 static std::string convert(T
const (&arr)[SZ]) {
return rangeToString(arr); }
2340#if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
2347template <
class Ratio>
struct ratio_string {
2348 static std::string symbol();
2351template <
class Ratio> std::string ratio_string<Ratio>::symbol() {
2352 Catch::ReusableStringStream rss;
2353 rss <<
'[' << Ratio::num <<
'/' << Ratio::den <<
']';
2356template <>
struct ratio_string<std::atto> {
2357 static std::string symbol();
2359template <>
struct ratio_string<std::femto> {
2360 static std::string symbol();
2362template <>
struct ratio_string<std::pico> {
2363 static std::string symbol();
2365template <>
struct ratio_string<std::nano> {
2366 static std::string symbol();
2368template <>
struct ratio_string<std::micro> {
2369 static std::string symbol();
2371template <>
struct ratio_string<std::milli> {
2372 static std::string symbol();
2377template <
typename Value,
typename Ratio>
struct StringMaker<std::chrono::duration<Value, Ratio>> {
2378 static std::string convert(std::chrono::duration<Value, Ratio>
const& duration) {
2379 ReusableStringStream rss;
2380 rss << duration.count() <<
' ' << ratio_string<Ratio>::symbol() <<
's';
2384template <
typename Value>
struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
2385 static std::string convert(std::chrono::duration<Value, std::ratio<1>>
const& duration) {
2386 ReusableStringStream rss;
2387 rss << duration.count() <<
" s";
2391template <
typename Value>
struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
2392 static std::string convert(std::chrono::duration<Value, std::ratio<60>>
const& duration) {
2393 ReusableStringStream rss;
2394 rss << duration.count() <<
" m";
2398template <
typename Value>
struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
2399 static std::string convert(std::chrono::duration<Value, std::ratio<3600>>
const& duration) {
2400 ReusableStringStream rss;
2401 rss << duration.count() <<
" h";
2410template <
typename Clock,
typename Duration>
2411struct StringMaker<std::chrono::time_point<Clock, Duration>> {
2412 static std::string convert(std::chrono::time_point<Clock, Duration>
const& time_point) {
2413 return ::Catch::Detail::stringify(time_point.time_since_epoch()) +
" since epoch";
2417template <
typename Duration>
2418struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
2420 convert(std::chrono::time_point<std::chrono::system_clock, Duration>
const& time_point) {
2421 auto converted = std::chrono::system_clock::to_time_t(time_point);
2424 std::tm timeInfo = {};
2425 gmtime_s(&timeInfo, &converted);
2427 std::tm* timeInfo = std::gmtime(&converted);
2430 auto const timeStampSize =
sizeof(
"2017-01-16T17:06:45Z");
2431 char timeStamp[timeStampSize];
2432 const char*
const fmt =
"%Y-%m-%dT%H:%M:%SZ";
2435 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2437 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2439 return std::string(timeStamp);
2445#define INTERNAL_CATCH_REGISTER_ENUM(enumName, ...) \
2447 template <> struct StringMaker<enumName> { \
2448 static std::string convert(enumName value) { \
2449 static const auto& enumInfo = \
2450 ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( \
2451 #enumName, #__VA_ARGS__, {__VA_ARGS__}); \
2452 return static_cast<std::string>(enumInfo.lookup(static_cast<int>(value))); \
2457#define CATCH_REGISTER_ENUM(enumName, ...) INTERNAL_CATCH_REGISTER_ENUM(enumName, __VA_ARGS__)
2467#pragma warning(push)
2468#pragma warning(disable : 4389)
2469#pragma warning(disable : 4018)
2470#pragma warning(disable : 4312)
2472#pragma warning(disable : 4180)
2473#pragma warning(disable : 4800)
2478struct ITransientExpression {
2479 auto isBinaryExpression()
const ->
bool {
return m_isBinaryExpression; }
2480 auto getResult()
const ->
bool {
return m_result; }
2481 virtual void streamReconstructedExpression(std::ostream& os)
const = 0;
2483 ITransientExpression(
bool isBinaryExpression,
bool result)
2484 : m_isBinaryExpression(isBinaryExpression), m_result(result) {}
2488 virtual ~ITransientExpression();
2490 bool m_isBinaryExpression;
2494void formatReconstructedExpression(std::ostream& os, std::string
const& lhs,
StringRef op,
2495 std::string
const& rhs);
2497template <
typename LhsT,
typename RhsT>
class BinaryExpr :
public ITransientExpression {
2502 void streamReconstructedExpression(std::ostream& os)
const override {
2503 formatReconstructedExpression(os, Catch::Detail::stringify(m_lhs), m_op,
2504 Catch::Detail::stringify(m_rhs));
2508 BinaryExpr(
bool comparisonResult, LhsT lhs,
StringRef op, RhsT rhs)
2509 : ITransientExpression{
true, comparisonResult}, m_lhs(lhs), m_op(op), m_rhs(rhs) {}
2511 template <
typename T>
auto operator&&(T)
const -> BinaryExpr<LhsT, RhsT const&>
const {
2513 "chained comparisons are not supported inside assertions, "
2514 "wrap the expression inside parentheses, or decompose it");
2517 template <
typename T>
auto operator||(T)
const -> BinaryExpr<LhsT, RhsT const&>
const {
2519 "chained comparisons are not supported inside assertions, "
2520 "wrap the expression inside parentheses, or decompose it");
2523 template <
typename T>
auto operator==(T)
const -> BinaryExpr<LhsT, RhsT const&>
const {
2525 "chained comparisons are not supported inside assertions, "
2526 "wrap the expression inside parentheses, or decompose it");
2529 template <
typename T>
auto operator!=(T)
const -> BinaryExpr<LhsT, RhsT const&>
const {
2531 "chained comparisons are not supported inside assertions, "
2532 "wrap the expression inside parentheses, or decompose it");
2535 template <
typename T>
auto operator>(T)
const -> BinaryExpr<LhsT, RhsT const&>
const {
2537 "chained comparisons are not supported inside assertions, "
2538 "wrap the expression inside parentheses, or decompose it");
2541 template <
typename T>
auto operator<(T)
const -> BinaryExpr<LhsT, RhsT const&>
const {
2543 "chained comparisons are not supported inside assertions, "
2544 "wrap the expression inside parentheses, or decompose it");
2547 template <
typename T>
auto operator>=(T)
const -> BinaryExpr<LhsT, RhsT const&>
const {
2549 "chained comparisons are not supported inside assertions, "
2550 "wrap the expression inside parentheses, or decompose it");
2553 template <
typename T>
auto operator<=(T)
const -> BinaryExpr<LhsT, RhsT const&>
const {
2555 "chained comparisons are not supported inside assertions, "
2556 "wrap the expression inside parentheses, or decompose it");
2560template <
typename LhsT>
class UnaryExpr :
public ITransientExpression {
2563 void streamReconstructedExpression(std::ostream& os)
const override {
2564 os << Catch::Detail::stringify(m_lhs);
2568 explicit UnaryExpr(LhsT lhs)
2569 : ITransientExpression{
false,
static_cast<bool>(lhs)}, m_lhs(lhs) {}
2574template <
typename LhsT,
typename RhsT>
2575auto compareEqual(LhsT
const& lhs, RhsT
const& rhs) ->
bool {
2576 return static_cast<bool>(lhs == rhs);
2578template <
typename T>
auto compareEqual(T*
const& lhs,
int rhs) ->
bool {
2579 return lhs ==
reinterpret_cast<void const*
>(rhs);
2581template <
typename T>
auto compareEqual(T*
const& lhs,
long rhs) ->
bool {
2582 return lhs ==
reinterpret_cast<void const*
>(rhs);
2584template <
typename T>
auto compareEqual(
int lhs, T*
const& rhs) ->
bool {
2585 return reinterpret_cast<void const*
>(lhs) == rhs;
2587template <
typename T>
auto compareEqual(
long lhs, T*
const& rhs) ->
bool {
2588 return reinterpret_cast<void const*
>(lhs) == rhs;
2591template <
typename LhsT,
typename RhsT>
auto compareNotEqual(LhsT
const& lhs, RhsT&& rhs) ->
bool {
2592 return static_cast<bool>(lhs != rhs);
2594template <
typename T>
auto compareNotEqual(T*
const& lhs,
int rhs) ->
bool {
2595 return lhs !=
reinterpret_cast<void const*
>(rhs);
2597template <
typename T>
auto compareNotEqual(T*
const& lhs,
long rhs) ->
bool {
2598 return lhs !=
reinterpret_cast<void const*
>(rhs);
2600template <
typename T>
auto compareNotEqual(
int lhs, T*
const& rhs) ->
bool {
2601 return reinterpret_cast<void const*
>(lhs) != rhs;
2603template <
typename T>
auto compareNotEqual(
long lhs, T*
const& rhs) ->
bool {
2604 return reinterpret_cast<void const*
>(lhs) != rhs;
2607template <
typename LhsT>
class ExprLhs {
2611 explicit ExprLhs(LhsT lhs) : m_lhs(lhs) {}
2613 template <
typename RhsT>
2615 return {compareEqual(m_lhs, rhs), m_lhs,
"==", rhs};
2618 return {m_lhs == rhs, m_lhs,
"==", rhs};
2621 template <
typename RhsT>
2623 return {compareNotEqual(m_lhs, rhs), m_lhs,
"!=", rhs};
2626 return {m_lhs != rhs, m_lhs,
"!=", rhs};
2629 template <
typename RhsT>
2631 return {
static_cast<bool>(m_lhs > rhs), m_lhs,
">", rhs};
2633 template <
typename RhsT>
2635 return {
static_cast<bool>(m_lhs < rhs), m_lhs,
"<", rhs};
2637 template <
typename RhsT>
2639 return {
static_cast<bool>(m_lhs >= rhs), m_lhs,
">=", rhs};
2641 template <
typename RhsT>
2643 return {
static_cast<bool>(m_lhs <= rhs), m_lhs,
"<=", rhs};
2645 template <
typename RhsT>
2647 return {
static_cast<bool>(m_lhs | rhs), m_lhs,
"|", rhs};
2649 template <
typename RhsT>
2651 return {
static_cast<bool>(m_lhs & rhs), m_lhs,
"&", rhs};
2653 template <
typename RhsT>
2655 return {
static_cast<bool>(m_lhs ^ rhs), m_lhs,
"^", rhs};
2660 "operator&& is not supported inside assertions, "
2661 "wrap the expression inside parentheses, or decompose it");
2666 "operator|| is not supported inside assertions, "
2667 "wrap the expression inside parentheses, or decompose it");
2675template <
typename T>
void handleExpression(
ExprLhs<T> const& expr) {
2676 handleExpression(expr.makeUnaryExpr());
2701class AssertionResult;
2702struct AssertionInfo;
2704struct SectionEndInfo;
2706struct MessageBuilder;
2708struct AssertionReaction;
2709struct SourceLineInfo;
2711struct ITransientExpression;
2712struct IGeneratorTracker;
2714#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2715struct BenchmarkInfo;
2716template <
typename Duration = std::chrono::duration<
double, std::nano>>
struct BenchmarkStats;
2723 virtual bool sectionStarted(
SectionInfo const& sectionInfo,
Counts& assertions) = 0;
2725 virtual void sectionEndedEarly(
SectionEndInfo const& endInfo) = 0;
2730#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2731 virtual void benchmarkPreparing(std::string
const& name) = 0;
2732 virtual void benchmarkStarting(BenchmarkInfo
const& info) = 0;
2733 virtual void benchmarkEnded(BenchmarkStats<>
const& stats) = 0;
2734 virtual void benchmarkFailed(std::string
const& error) = 0;
2737 virtual void pushScopedMessage(
MessageInfo const& message) = 0;
2738 virtual void popScopedMessage(
MessageInfo const& message) = 0;
2740 virtual void emplaceUnscopedMessage(
MessageBuilder const& builder) = 0;
2742 virtual void handleFatalErrorCondition(
StringRef message) = 0;
2746 virtual void handleMessage(
AssertionInfo const& info, ResultWas::OfType resultType,
2748 virtual void handleUnexpectedExceptionNotThrown(
AssertionInfo const& info,
2750 virtual void handleUnexpectedInflightException(
AssertionInfo const& info,
2751 std::string
const& message,
2753 virtual void handleIncomplete(
AssertionInfo const& info) = 0;
2754 virtual void handleNonExpr(
AssertionInfo const& info, ResultWas::OfType resultType,
2757 virtual bool lastAssertionPassed() = 0;
2758 virtual void assertionPassed() = 0;
2761 virtual std::string getCurrentTestName()
const = 0;
2762 virtual const AssertionResult* getLastResult()
const = 0;
2763 virtual void exceptionEarlyReported() = 0;
2773struct AssertionResultData;
2777class LazyExpression {
2778 friend class AssertionHandler;
2779 friend struct AssertionStats;
2780 friend class RunContext;
2786 LazyExpression(
bool isNegated);
2787 LazyExpression(LazyExpression
const& other);
2788 LazyExpression& operator=(LazyExpression
const&) =
delete;
2790 explicit operator bool()
const;
2792 friend auto operator<<(std::ostream& os, LazyExpression
const& lazyExpr) -> std::ostream&;
2796 bool shouldDebugBreak =
false;
2797 bool shouldThrow =
false;
2800class AssertionHandler {
2803 bool m_completed =
false;
2808 StringRef capturedExpression, ResultDisposition::Flags resultDisposition);
2809 ~AssertionHandler() {
2811 m_resultCapture.handleIncomplete(m_assertionInfo);
2815 template <
typename T>
void handleExpr(
ExprLhs<T> const& expr) {
2816 handleExpr(expr.makeUnaryExpr());
2820 void handleMessage(ResultWas::OfType resultType,
StringRef const& message);
2822 void handleExceptionThrownAsExpected();
2823 void handleUnexpectedExceptionNotThrown();
2824 void handleExceptionNotThrownAsExpected();
2825 void handleThrowingCallSkipped();
2826 void handleUnexpectedInflightException();
2829 void setCompleted();
2832 auto allowThrows()
const -> bool;
2835void handleExceptionMatchExpr(
AssertionHandler& handler, std::string
const& str,
2850 ResultWas::OfType _type);
2853 std::string message;
2855 ResultWas::OfType type;
2856 unsigned int sequence;
2858 bool operator==(MessageInfo
const& other)
const;
2859 bool operator<(MessageInfo
const& other)
const;
2862 static unsigned int globalCount;
2867 template <
typename T>
MessageStream& operator<<(T
const& value) {
2877 ResultWas::OfType type);
2879 template <
typename T> MessageBuilder& operator<<(T
const& value) {
2887class ScopedMessage {
2890 ScopedMessage(ScopedMessage& duplicate) =
delete;
2891 ScopedMessage(ScopedMessage&& old);
2899 std::vector<MessageInfo> m_messages;
2901 size_t m_captured = 0;
2908 void captureValue(
size_t index, std::string
const& value);
2910 template <
typename T>
void captureValues(
size_t index, T
const& value) {
2911 captureValue(index, Catch::Detail::stringify(value));
2914 template <
typename T,
typename... Ts>
2915 void captureValues(
size_t index, T
const& value, Ts
const&... values) {
2916 captureValue(index, Catch::Detail::stringify(value));
2917 captureValues(index + 1, values...);
2924#if !defined(CATCH_CONFIG_DISABLE)
2926#if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
2927#define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
2929#define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
2932#if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
2937#define INTERNAL_CATCH_TRY
2938#define INTERNAL_CATCH_CATCH(capturer)
2942#define INTERNAL_CATCH_TRY try
2943#define INTERNAL_CATCH_CATCH(handler) \
2945 handler.handleUnexpectedInflightException(); \
2950#define INTERNAL_CATCH_REACT(handler) handler.complete();
2953#define INTERNAL_CATCH_TEST(macroName, resultDisposition, ...) \
2955 CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \
2956 Catch::AssertionHandler catchAssertionHandler( \
2957 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), \
2958 resultDisposition); \
2959 INTERNAL_CATCH_TRY { \
2960 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2961 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
2962 catchAssertionHandler.handleExpr(Catch::Decomposer() <= __VA_ARGS__); \
2963 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
2965 INTERNAL_CATCH_CATCH(catchAssertionHandler) \
2966 INTERNAL_CATCH_REACT(catchAssertionHandler) \
2967 } while ((void)0, (false) && static_cast<bool>(!!(__VA_ARGS__)))
2970#define INTERNAL_CATCH_IF(macroName, resultDisposition, ...) \
2971 INTERNAL_CATCH_TEST(macroName, resultDisposition, __VA_ARGS__); \
2972 if (Catch::getResultCapture().lastAssertionPassed())
2975#define INTERNAL_CATCH_ELSE(macroName, resultDisposition, ...) \
2976 INTERNAL_CATCH_TEST(macroName, resultDisposition, __VA_ARGS__); \
2977 if (!Catch::getResultCapture().lastAssertionPassed())
2980#define INTERNAL_CATCH_NO_THROW(macroName, resultDisposition, ...) \
2982 Catch::AssertionHandler catchAssertionHandler( \
2983 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), \
2984 resultDisposition); \
2986 static_cast<void>(__VA_ARGS__); \
2987 catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
2989 catchAssertionHandler.handleUnexpectedInflightException(); \
2991 INTERNAL_CATCH_REACT(catchAssertionHandler) \
2995#define INTERNAL_CATCH_THROWS(macroName, resultDisposition, ...) \
2997 Catch::AssertionHandler catchAssertionHandler( \
2998 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), \
2999 resultDisposition); \
3000 if (catchAssertionHandler.allowThrows()) \
3002 static_cast<void>(__VA_ARGS__); \
3003 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3005 catchAssertionHandler.handleExceptionThrownAsExpected(); \
3008 catchAssertionHandler.handleThrowingCallSkipped(); \
3009 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3013#define INTERNAL_CATCH_THROWS_AS(macroName, exceptionType, resultDisposition, expr) \
3015 Catch::AssertionHandler catchAssertionHandler( \
3016 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
3017 CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), \
3018 resultDisposition); \
3019 if (catchAssertionHandler.allowThrows()) \
3021 static_cast<void>(expr); \
3022 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3023 } catch (exceptionType const&) { \
3024 catchAssertionHandler.handleExceptionThrownAsExpected(); \
3026 catchAssertionHandler.handleUnexpectedInflightException(); \
3029 catchAssertionHandler.handleThrowingCallSkipped(); \
3030 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3034#define INTERNAL_CATCH_MSG(macroName, messageType, resultDisposition, ...) \
3036 Catch::AssertionHandler catchAssertionHandler( \
3037 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition); \
3038 catchAssertionHandler.handleMessage( \
3040 (Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop()).m_stream.str()); \
3041 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3045#define INTERNAL_CATCH_CAPTURE(varName, macroName, ...) \
3047 Catch::Capturer(macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__); \
3048 varName.captureValues(0, __VA_ARGS__)
3051#define INTERNAL_CATCH_INFO(macroName, log) \
3052 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME(scopedMessage)( \
3053 Catch::MessageBuilder(macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
3054 Catch::ResultWas::Info) \
3058#define INTERNAL_CATCH_UNSCOPED_INFO(macroName, log) \
3059 Catch::getResultCapture().emplaceUnscopedMessage( \
3060 Catch::MessageBuilder(macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
3061 Catch::ResultWas::Info) \
3066#define INTERNAL_CATCH_THROWS_STR_MATCHES(macroName, resultDisposition, matcher, ...) \
3068 Catch::AssertionHandler catchAssertionHandler( \
3069 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
3070 CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), \
3071 resultDisposition); \
3072 if (catchAssertionHandler.allowThrows()) \
3074 static_cast<void>(__VA_ARGS__); \
3075 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3077 Catch::handleExceptionMatchExpr(catchAssertionHandler, matcher, \
3078 #matcher##_catch_sr); \
3081 catchAssertionHandler.handleThrowingCallSkipped(); \
3082 INTERNAL_CATCH_REACT(catchAssertionHandler) \
3102 std::size_t total()
const;
3103 bool allPassed()
const;
3106 std::size_t passed = 0;
3107 std::size_t failed = 0;
3108 std::size_t failedButOk = 0;
3130 SectionInfo(
SourceLineInfo const& _lineInfo, std::string
const& _name);
3133 SectionInfo(
SourceLineInfo const& _lineInfo, std::string
const& _name, std::string
const&)
3134 : SectionInfo(_lineInfo, _name) {}
3137 std::string description;
3144 double durationInSeconds;
3156auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
3157auto getEstimatedClockResolution() -> uint64_t;
3160 uint64_t m_nanoseconds = 0;
3164 auto getElapsedNanoseconds()
const -> uint64_t;
3165 auto getElapsedMicroseconds()
const -> uint64_t;
3166 auto getElapsedMilliseconds()
const ->
unsigned int;
3167 auto getElapsedSeconds()
const -> double;
3177class Section : NonCopyable {
3183 explicit operator bool()
const;
3190 bool m_sectionIncluded;
3196#define INTERNAL_CATCH_SECTION(...) \
3197 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3198 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
3199 if (Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME(catch_internal_Section) = \
3200 Catch::SectionInfo(CATCH_INTERNAL_LINEINFO, __VA_ARGS__)) \
3201 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
3203#define INTERNAL_CATCH_DYNAMIC_SECTION(...) \
3204 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3205 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
3206 if (Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME(catch_internal_Section) = \
3207 Catch::SectionInfo(CATCH_INTERNAL_LINEINFO, \
3208 (Catch::ReusableStringStream() << __VA_ARGS__).str())) \
3209 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
3222struct ITestCaseRegistry;
3223struct IExceptionTranslatorRegistry;
3224struct IExceptionTranslator;
3225struct IReporterRegistry;
3226struct IReporterFactory;
3227struct ITagAliasRegistry;
3228struct IMutableEnumValuesRegistry;
3230class StartupExceptionRegistry;
3232using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
3237 virtual IReporterRegistry
const& getReporterRegistry()
const = 0;
3239 virtual ITagAliasRegistry
const& getTagAliasRegistry()
const = 0;
3242 virtual StartupExceptionRegistry
const& getStartupExceptionRegistry()
const = 0;
3247 virtual void registerReporter(std::string
const& name, IReporterFactoryPtr
const& factory) = 0;
3248 virtual void registerListener(IReporterFactoryPtr
const& factory) = 0;
3249 virtual void registerTest(
TestCase const& testInfo) = 0;
3251 virtual void registerTagAlias(std::string
const& alias, std::string
const& tag,
3253 virtual void registerStartupException()
noexcept = 0;
3260std::string translateActiveException();
3265#if defined(CATCH_CONFIG_DISABLE)
3266#define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG(translatorName, signature) \
3267 static std::string translatorName(signature)
3275using exceptionTranslateFunction = std::string (*)();
3277struct IExceptionTranslator;
3278using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
3282 virtual std::string translate(ExceptionTranslators::const_iterator it,
3283 ExceptionTranslators::const_iterator itEnd)
const = 0;
3289 virtual std::string translateActiveException()
const = 0;
3292class ExceptionTranslatorRegistrar {
3295 ExceptionTranslator(std::string (*translateFunction)(T&))
3296 : m_translateFunction(translateFunction) {}
3298 std::string translate(ExceptionTranslators::const_iterator it,
3299 ExceptionTranslators::const_iterator itEnd)
const override {
3300#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3305 std::rethrow_exception(std::current_exception());
3307 return (*it)->translate(it + 1, itEnd);
3309 return m_translateFunction(ex);
3315 std::string (*m_translateFunction)(T&);
3319 template <
typename T> ExceptionTranslatorRegistrar(std::string (*translateFunction)(T&)) {
3320 getMutableRegistryHub().registerTranslator(
new ExceptionTranslator<T>(translateFunction));
3326#define INTERNAL_CATCH_TRANSLATE_EXCEPTION2(translatorName, signature) \
3327 static std::string translatorName(signature); \
3328 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3329 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
3331 Catch::ExceptionTranslatorRegistrar \
3332 INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionRegistrar)(&translatorName); \
3334 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
3335 static std::string translatorName(signature)
3337#define INTERNAL_CATCH_TRANSLATE_EXCEPTION(signature) \
3338 INTERNAL_CATCH_TRANSLATE_EXCEPTION2( \
3339 INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionTranslator), signature)
3344#include <type_traits>
3351 bool equalityComparisonImpl(
double other)
const;
3354 void setMargin(
double margin);
3357 void setEpsilon(
double epsilon);
3360 explicit Approx(
double value);
3362 static Approx custom();
3364 Approx operator-()
const;
3366 template <
typename T,
3367 typename =
typename std::enable_if<std::is_constructible<double, T>::value>::type>
3368 Approx operator()(T
const& value)
const {
3369 Approx approx(
static_cast<double>(value));
3370 approx.m_epsilon = m_epsilon;
3371 approx.m_margin = m_margin;
3372 approx.m_scale = m_scale;
3376 template <
typename T,
3377 typename =
typename std::enable_if<std::is_constructible<double, T>::value>::type>
3378 explicit Approx(T
const& value) : Approx(
static_cast<double>(value)) {}
3380 template <
typename T,
3381 typename =
typename std::enable_if<std::is_constructible<double, T>::value>::type>
3382 friend bool operator==(
const T& lhs, Approx
const& rhs) {
3383 auto lhs_v =
static_cast<double>(lhs);
3384 return rhs.equalityComparisonImpl(lhs_v);
3387 template <
typename T,
3388 typename =
typename std::enable_if<std::is_constructible<double, T>::value>::type>
3389 friend bool operator==(Approx
const& lhs,
const T& rhs) {
3390 return operator==(rhs, lhs);
3393 template <
typename T,
3394 typename =
typename std::enable_if<std::is_constructible<double, T>::value>::type>
3395 friend bool operator!=(T
const& lhs, Approx
const& rhs) {
3396 return !operator==(lhs, rhs);
3399 template <
typename T,
3400 typename =
typename std::enable_if<std::is_constructible<double, T>::value>::type>
3401 friend bool operator!=(Approx
const& lhs, T
const& rhs) {
3402 return !operator==(rhs, lhs);
3405 template <
typename T,
3406 typename =
typename std::enable_if<std::is_constructible<double, T>::value>::type>
3407 friend bool operator<=(T
const& lhs, Approx
const& rhs) {
3408 return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
3411 template <
typename T,
3412 typename =
typename std::enable_if<std::is_constructible<double, T>::value>::type>
3413 friend bool operator<=(Approx
const& lhs, T
const& rhs) {
3414 return lhs.m_value <
static_cast<double>(rhs) || lhs == rhs;
3417 template <
typename T,
3418 typename =
typename std::enable_if<std::is_constructible<double, T>::value>::type>
3419 friend bool operator>=(T
const& lhs, Approx
const& rhs) {
3420 return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3423 template <
typename T,
3424 typename =
typename std::enable_if<std::is_constructible<double, T>::value>::type>
3425 friend bool operator>=(Approx
const& lhs, T
const& rhs) {
3426 return lhs.m_value >
static_cast<double>(rhs) || lhs == rhs;
3429 template <
typename T,
3430 typename =
typename std::enable_if<std::is_constructible<double, T>::value>::type>
3431 Approx& epsilon(T
const& newEpsilon) {
3432 double epsilonAsDouble =
static_cast<double>(newEpsilon);
3433 setEpsilon(epsilonAsDouble);
3437 template <
typename T,
3438 typename =
typename std::enable_if<std::is_constructible<double, T>::value>::type>
3439 Approx& margin(T
const& newMargin) {
3440 double marginAsDouble =
static_cast<double>(newMargin);
3441 setMargin(marginAsDouble);
3445 template <
typename T,
3446 typename =
typename std::enable_if<std::is_constructible<double, T>::value>::type>
3447 Approx& scale(T
const& newScale) {
3448 m_scale =
static_cast<double>(newScale);
3452 std::string toString()
const;
3463Detail::Approx
operator"" _a(
long double val);
3464Detail::Approx
operator"" _a(
unsigned long long val);
3482bool startsWith(std::string
const& s, std::string
const& prefix);
3483bool startsWith(std::string
const& s,
char prefix);
3484bool endsWith(std::string
const& s, std::string
const& suffix);
3485bool endsWith(std::string
const& s,
char suffix);
3486bool contains(std::string
const& s, std::string
const& infix);
3487void toLowerInPlace(std::string& s);
3488std::string toLower(std::string
const& s);
3490std::string trim(std::string
const& str);
3493StringRef trim(StringRef ref);
3497std::vector<StringRef> splitStringRef(StringRef str,
char delimiter);
3498bool replaceInPlace(std::string& str, std::string
const& replaceThis, std::string
const& withThis);
3501 pluralise(std::size_t count, std::string
const& label);
3503 friend std::ostream& operator<<(std::ostream& os, pluralise
const& pluraliser);
3505 std::size_t m_count;
3506 std::string m_label;
3511#ifndef CATCH_CONFIG_DISABLE_MATCHERS
3523template <
typename ArgT>
struct MatchAllOf;
3524template <
typename ArgT>
struct MatchAnyOf;
3525template <
typename ArgT>
struct MatchNotOf;
3527class MatcherUntypedBase {
3529 MatcherUntypedBase() =
default;
3530 MatcherUntypedBase(MatcherUntypedBase
const&) =
default;
3531 MatcherUntypedBase& operator=(MatcherUntypedBase
const&) =
delete;
3532 std::string toString()
const;
3535 virtual ~MatcherUntypedBase();
3536 virtual std::string describe()
const = 0;
3537 mutable std::string m_cachedToString;
3541#pragma clang diagnostic push
3542#pragma clang diagnostic ignored "-Wnon-virtual-dtor"
3546 virtual bool match(ObjectT
const& arg)
const = 0;
3549#if defined(__OBJC__)
3554 virtual bool match(NSString* arg)
const = 0;
3559#pragma clang diagnostic pop
3562template <
typename T>
struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
3564 MatchAllOf<T> operator&&(
MatcherBase const& other)
const;
3565 MatchAnyOf<T> operator||(
MatcherBase const& other)
const;
3566 MatchNotOf<T> operator!()
const;
3570 bool match(ArgT
const& arg)
const override {
3571 for (
auto matcher : m_matchers) {
3572 if (!matcher->match(arg))
3577 std::string describe()
const override {
3578 std::string description;
3579 description.reserve(4 + m_matchers.size() * 32);
3580 description +=
"( ";
3582 for (
auto matcher : m_matchers) {
3586 description +=
" and ";
3587 description += matcher->toString();
3589 description +=
" )";
3595 copy.m_matchers.push_back(&other);
3599 std::vector<MatcherBase<ArgT>
const*> m_matchers;
3603 bool match(ArgT
const& arg)
const override {
3604 for (
auto matcher : m_matchers) {
3605 if (matcher->match(arg))
3610 std::string describe()
const override {
3611 std::string description;
3612 description.reserve(4 + m_matchers.size() * 32);
3613 description +=
"( ";
3615 for (
auto matcher : m_matchers) {
3619 description +=
" or ";
3620 description += matcher->toString();
3622 description +=
" )";
3628 copy.m_matchers.push_back(&other);
3632 std::vector<MatcherBase<ArgT>
const*> m_matchers;
3638 : m_underlyingMatcher(underlyingMatcher) {}
3640 bool match(ArgT
const& arg)
const override {
return !m_underlyingMatcher.match(arg); }
3642 std::string describe()
const override {
return "not " + m_underlyingMatcher.toString(); }
3649template <
typename T> MatchAnyOf<T> MatcherBase<T>::operator||(
MatcherBase const& other)
const {
3650 return MatchAnyOf<T>() || *
this || other;
3652template <
typename T> MatchNotOf<T> MatcherBase<T>::operator!()
const {
3653 return MatchNotOf<T>(*
this);
3660using namespace Matchers;
3670namespace Exception {
3673 std::string m_message;
3676 ExceptionMessageMatcher(std::string
const& message) : m_message(message) {}
3678 bool match(std::exception
const& ex)
const override;
3680 std::string describe()
const override;
3698enum class FloatingPointKind : uint8_t;
3701 WithinAbsMatcher(
double target,
double margin);
3702 bool match(
double const& matchee)
const override;
3703 std::string describe()
const override;
3711 WithinUlpsMatcher(
double target, uint64_t ulps, FloatingPointKind baseType);
3712 bool match(
double const& matchee)
const override;
3713 std::string describe()
const override;
3718 FloatingPointKind m_type;
3728 WithinRelMatcher(
double target,
double epsilon);
3729 bool match(
double const& matchee)
const override;
3730 std::string describe()
const override;
3757#include <functional>
3765std::string finalizeDescription(
const std::string& desc);
3769 std::function<bool(T
const&)> m_predicate;
3770 std::string m_description;
3773 PredicateMatcher(std::function<
bool(T
const&)>
const& elem, std::string
const& descr)
3774 : m_predicate(std::move(elem)), m_description(Detail::finalizeDescription(descr)) {}
3776 bool match(T
const& item)
const override {
return m_predicate(item); }
3778 std::string describe()
const override {
return m_description; }
3787template <
typename T>
3789 std::string
const& description =
"") {
3804namespace StdString {
3807 CasedString(std::string
const& str, CaseSensitive::Choice caseSensitivity);
3808 std::string adjustString(std::string
const& str)
const;
3809 std::string caseSensitivitySuffix()
const;
3811 CaseSensitive::Choice m_caseSensitivity;
3816 StringMatcherBase(std::string
const& operation,
CasedString const& comparator);
3817 std::string describe()
const override;
3820 std::string m_operation;
3823struct EqualsMatcher : StringMatcherBase {
3825 bool match(std::string
const& source)
const override;
3827struct ContainsMatcher : StringMatcherBase {
3829 bool match(std::string
const& source)
const override;
3831struct StartsWithMatcher : StringMatcherBase {
3833 bool match(std::string
const& source)
const override;
3835struct EndsWithMatcher : StringMatcherBase {
3837 bool match(std::string
const& source)
const override;
3841 RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity);
3842 bool match(std::string
const& matchee)
const override;
3843 std::string describe()
const override;
3846 std::string m_regex;
3847 CaseSensitive::Choice m_caseSensitivity;
3856 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
3858 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
3860 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
3862 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
3864 CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes);
3878template <
typename T,
typename Alloc>
3881 ContainsElementMatcher(T
const& comparator) : m_comparator(comparator) {}
3883 bool match(std::vector<T, Alloc>
const& v)
const override {
3884 for (
auto const& el : v) {
3885 if (el == m_comparator) {
3892 std::string describe()
const override {
3893 return "Contains: " + ::Catch::Detail::stringify(m_comparator);
3896 T
const& m_comparator;
3899template <
typename T,
typename AllocComp,
typename AllocMatch>
3902 ContainsMatcher(std::vector<T, AllocComp>
const& comparator) : m_comparator(comparator) {}
3904 bool match(std::vector<T, AllocMatch>
const& v)
const override {
3906 if (m_comparator.size() > v.size())
3908 for (
auto const& comparator : m_comparator) {
3909 auto present =
false;
3910 for (
const auto& el : v) {
3911 if (el == comparator) {
3922 std::string describe()
const override {
3923 return "Contains: " + ::Catch::Detail::stringify(m_comparator);
3926 std::vector<T, AllocComp>
const& m_comparator;
3929template <
typename T,
typename AllocComp,
typename AllocMatch>
3932 EqualsMatcher(std::vector<T, AllocComp>
const& comparator) : m_comparator(comparator) {}
3934 bool match(std::vector<T, AllocMatch>
const& v)
const override {
3939 if (m_comparator.size() != v.size())
3941 for (std::size_t i = 0; i < v.size(); ++i)
3942 if (m_comparator[i] != v[i])
3946 std::string describe()
const override {
3947 return "Equals: " + ::Catch::Detail::stringify(m_comparator);
3949 std::vector<T, AllocComp>
const& m_comparator;
3952template <
typename T,
typename AllocComp,
typename AllocMatch>
3955 ApproxMatcher(std::vector<T, AllocComp>
const& comparator) : m_comparator(comparator) {}
3957 bool match(std::vector<T, AllocMatch>
const& v)
const override {
3958 if (m_comparator.size() != v.size())
3960 for (std::size_t i = 0; i < v.size(); ++i)
3961 if (m_comparator[i] != approx(v[i]))
3965 std::string describe()
const override {
3966 return "is approx: " + ::Catch::Detail::stringify(m_comparator);
3968 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3969 ApproxMatcher& epsilon(T
const& newEpsilon) {
3970 approx.epsilon(newEpsilon);
3973 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3974 ApproxMatcher& margin(T
const& newMargin) {
3975 approx.margin(newMargin);
3978 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3979 ApproxMatcher& scale(T
const& newScale) {
3980 approx.scale(newScale);
3984 std::vector<T, AllocComp>
const& m_comparator;
3988template <
typename T,
typename AllocComp,
typename AllocMatch>
3989struct UnorderedEqualsMatcher :
MatcherBase<std::vector<T, AllocMatch>> {
3990 UnorderedEqualsMatcher(std::vector<T, AllocComp>
const& target) : m_target(target) {}
3991 bool match(std::vector<T, AllocMatch>
const& vec)
const override {
3992 if (m_target.size() != vec.size()) {
3995 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
3998 std::string describe()
const override {
3999 return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
4003 std::vector<T, AllocComp>
const& m_target;
4011template <
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
4013Contains(std::vector<T, AllocComp>
const& comparator) {
4017template <
typename T,
typename Alloc = std::allocator<T>>
4022template <
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
4023Vector::EqualsMatcher<T, AllocComp, AllocMatch>
4024Equals(std::vector<T, AllocComp>
const& comparator) {
4025 return Vector::EqualsMatcher<T, AllocComp, AllocMatch>(comparator);
4028template <
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
4030Approx(std::vector<T, AllocComp>
const& comparator) {
4034template <
typename T,
typename AllocComp = std::allocator<T>,
typename AllocMatch = AllocComp>
4036UnorderedEquals(std::vector<T, AllocComp>
const& target) {
4046template <
typename ArgT,
typename MatcherT>
class MatchExpr :
public ITransientExpression {
4052 MatchExpr(ArgT
const& arg, MatcherT
const& matcher,
StringRef const& matcherString)
4053 : ITransientExpression{
true, matcher.match(arg)}, m_arg(arg), m_matcher(matcher),
4054 m_matcherString(matcherString) {}
4056 void streamReconstructedExpression(std::ostream& os)
const override {
4057 auto matcherAsString = m_matcher.toString();
4058 os << Catch::Detail::stringify(m_arg) <<
' ';
4059 if (matcherAsString == Detail::unprintableString)
4060 os << m_matcherString;
4062 os << matcherAsString;
4068void handleExceptionMatchExpr(
AssertionHandler& handler, StringMatcher
const& matcher,
4071template <
typename ArgT,
typename MatcherT>
4072auto makeMatchExpr(ArgT
const& arg, MatcherT
const& matcher,
StringRef const& matcherString)
4080#define INTERNAL_CHECK_THAT(macroName, matcher, resultDisposition, arg) \
4082 Catch::AssertionHandler catchAssertionHandler( \
4083 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
4084 CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), \
4085 resultDisposition); \
4086 INTERNAL_CATCH_TRY { \
4087 catchAssertionHandler.handleExpr( \
4088 Catch::makeMatchExpr(arg, matcher, #matcher##_catch_sr)); \
4090 INTERNAL_CATCH_CATCH(catchAssertionHandler) \
4091 INTERNAL_CATCH_REACT(catchAssertionHandler) \
4095#define INTERNAL_CATCH_THROWS_MATCHES(macroName, exceptionType, resultDisposition, matcher, ...) \
4097 Catch::AssertionHandler catchAssertionHandler( \
4098 macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, \
4099 CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY( \
4100 exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), \
4101 resultDisposition); \
4102 if (catchAssertionHandler.allowThrows()) \
4104 static_cast<void>(__VA_ARGS__); \
4105 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
4106 } catch (exceptionType const& ex) { \
4107 catchAssertionHandler.handleExpr( \
4108 Catch::makeMatchExpr(ex, matcher, #matcher##_catch_sr)); \
4110 catchAssertionHandler.handleUnexpectedInflightException(); \
4113 catchAssertionHandler.handleThrowingCallSkipped(); \
4114 INTERNAL_CATCH_REACT(catchAssertionHandler) \
4127namespace Generators {
4128class GeneratorUntypedBase {
4130 GeneratorUntypedBase() =
default;
4131 virtual ~GeneratorUntypedBase();
4136 virtual bool next() = 0;
4138using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
4144 virtual auto hasGenerator()
const ->
bool = 0;
4145 virtual auto getGenerator()
const -> Generators::GeneratorBasePtr
const& = 0;
4146 virtual void setGenerator(Generators::GeneratorBasePtr&& generator) = 0;
4157#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
4158template <
typename Ex>
4160void throw_exception(Ex
const& e) {
4165void throw_exception(std::exception
const& e);
4169void throw_logic_error(std::string
const& msg);
4171void throw_domain_error(std::string
const& msg);
4173void throw_runtime_error(std::string
const& msg);
4177#define CATCH_MAKE_MSG(...) (Catch::ReusableStringStream() << __VA_ARGS__).str()
4179#define CATCH_INTERNAL_ERROR(...) \
4180 Catch::throw_logic_error( \
4181 CATCH_MAKE_MSG(CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
4183#define CATCH_ERROR(...) Catch::throw_domain_error(CATCH_MAKE_MSG(__VA_ARGS__))
4185#define CATCH_RUNTIME_ERROR(...) Catch::throw_runtime_error(CATCH_MAKE_MSG(__VA_ARGS__))
4187#define CATCH_ENFORCE(condition, ...) \
4190 CATCH_ERROR(__VA_ARGS__); \
4203class GeneratorException :
public std::exception {
4204 const char*
const m_msg =
"";
4207 GeneratorException(
const char* msg) : m_msg(msg) {}
4209 const char* what()
const noexcept override final;
4212namespace Generators {
4216template <
typename T,
typename... Args> std::unique_ptr<T> make_unique(Args&&... args) {
4217 return std::unique_ptr<T>(
new T(std::forward<Args>(args)...));
4228 virtual T
const& get()
const = 0;
4232template <
typename T>
class SingleValueGenerator final :
public IGenerator<T> {
4236 SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
4238 T
const& get()
const override {
return m_value; }
4239 bool next()
override {
return false; }
4242template <
typename T>
class FixedValuesGenerator final :
public IGenerator<T> {
4243 static_assert(!std::is_same<T, bool>::value,
4244 "FixedValuesGenerator does not support bools because of std::vector<bool>"
4245 "specialization, use SingleValue Generator instead.");
4246 std::vector<T> m_values;
4250 FixedValuesGenerator(std::initializer_list<T> values) : m_values(values) {}
4252 T
const& get()
const override {
return m_values[m_idx]; }
4253 bool next()
override {
4255 return m_idx < m_values.size();
4259template <
typename T>
class GeneratorWrapper final {
4260 std::unique_ptr<IGenerator<T>> m_generator;
4264 : m_generator(std::move(generator)) {}
4265 T
const& get()
const {
return m_generator->get(); }
4266 bool next() {
return m_generator->next(); }
4272template <
typename T> GeneratorWrapper<T> values(std::initializer_list<T> values) {
4273 return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
4277 std::vector<GeneratorWrapper<T>> m_generators;
4278 size_t m_current = 0;
4281 m_generators.emplace_back(std::move(generator));
4283 void populate(T&& val) { m_generators.emplace_back(value(std::forward<T>(val))); }
4284 template <
typename U>
void populate(U&& val) { populate(T(std::forward<U>(val))); }
4285 template <
typename U,
typename... Gs>
4286 void populate(U&& valueOrGenerator, Gs&&... moreGenerators) {
4287 populate(std::forward<U>(valueOrGenerator));
4288 populate(std::forward<Gs>(moreGenerators)...);
4292 template <
typename... Gs> Generators(Gs&&... moreGenerators) {
4293 m_generators.reserve(
sizeof...(Gs));
4294 populate(std::forward<Gs>(moreGenerators)...);
4297 T
const& get()
const override {
return m_generators[m_current].get(); }
4299 bool next()
override {
4300 if (m_current >= m_generators.size()) {
4303 const bool current_status = m_generators[m_current].next();
4304 if (!current_status) {
4307 return m_current < m_generators.size();
4311template <
typename... Ts>
4313table(std::initializer_list<std::tuple<
typename std::decay<Ts>::type...>> tuples) {
4314 return values<std::tuple<Ts...>>(tuples);
4319template <
typename T>
struct as {};
4321template <
typename T,
typename... Gs>
4323 return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
4325template <
typename T>
auto makeGenerators(GeneratorWrapper<T>&& generator) -> Generators<T> {
4326 return Generators<T>(std::move(generator));
4328template <
typename T,
typename... Gs>
4329auto makeGenerators(T&& val, Gs&&... moreGenerators) -> Generators<T> {
4330 return makeGenerators(value(std::forward<T>(val)), std::forward<Gs>(moreGenerators)...);
4332template <
typename T,
typename U,
typename... Gs>
4334 return makeGenerators(value(T(std::forward<U>(val))), std::forward<Gs>(moreGenerators)...);
4337auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo
const& lineInfo)
4338 -> IGeneratorTracker&;
4340template <
typename L>
4344auto generate(StringRef generatorName, SourceLineInfo
const& lineInfo, L
const& generatorExpression)
4345 ->
decltype(std::declval<decltype(generatorExpression())>().get()) {
4346 using UnderlyingType =
typename decltype(generatorExpression())::type;
4348 IGeneratorTracker& tracker = acquireGeneratorTracker(generatorName, lineInfo);
4349 if (!tracker.hasGenerator()) {
4354 return generator.get();
4360#define GENERATE(...) \
4361 Catch::Generators::generate(INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4362 CATCH_INTERNAL_LINEINFO, [] { \
4363 using namespace Catch::Generators; \
4364 return makeGenerators(__VA_ARGS__); \
4366#define GENERATE_COPY(...) \
4367 Catch::Generators::generate(INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4368 CATCH_INTERNAL_LINEINFO, [=] { \
4369 using namespace Catch::Generators; \
4370 return makeGenerators(__VA_ARGS__); \
4372#define GENERATE_REF(...) \
4373 Catch::Generators::generate(INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4374 CATCH_INTERNAL_LINEINFO, [&] { \
4375 using namespace Catch::Generators; \
4376 return makeGenerators(__VA_ARGS__); \
4383namespace Generators {
4385template <
typename T>
class TakeGenerator :
public IGenerator<T> {
4387 size_t m_returned = 0;
4392 : m_generator(std::move(generator)), m_target(target) {
4393 assert(target != 0 &&
"Empty generators are not allowed");
4395 T
const& get()
const override {
return m_generator.get(); }
4396 bool next()
override {
4398 if (m_returned >= m_target) {
4402 const auto success = m_generator.next();
4406 m_returned = m_target;
4416template <
typename T,
typename Predicate>
class FilterGenerator :
public IGenerator<T> {
4418 Predicate m_predicate;
4421 template <
typename P = Predicate>
4423 : m_generator(std::move(generator)), m_predicate(std::forward<P>(pred)) {
4424 if (!m_predicate(m_generator.get())) {
4427 auto has_initial_value = nextImpl();
4428 if (!has_initial_value) {
4429 Catch::throw_exception(
4435 T
const& get()
const override {
return m_generator.get(); }
4437 bool next()
override {
return nextImpl(); }
4441 bool success = m_generator.next();
4445 while (!m_predicate(m_generator.get()) && (success = m_generator.next()) ==
true)
4451template <
typename T,
typename Predicate>
4455 std::forward<Predicate>(pred), std::move(generator))));
4458template <
typename T>
class RepeatGenerator :
public IGenerator<T> {
4459 static_assert(!std::is_same<T, bool>::value,
"RepeatGenerator currently does not support bools"
4460 "because of std::vector<bool> specialization");
4462 mutable std::vector<T> m_returned;
4463 size_t m_target_repeats;
4464 size_t m_current_repeat = 0;
4465 size_t m_repeat_index = 0;
4469 : m_generator(std::move(generator)), m_target_repeats(repeats) {
4470 assert(m_target_repeats > 0 &&
"Repeat generator must repeat at least once");
4473 T
const& get()
const override {
4474 if (m_current_repeat == 0) {
4475 m_returned.push_back(m_generator.get());
4476 return m_returned.back();
4478 return m_returned[m_repeat_index];
4481 bool next()
override {
4489 if (m_current_repeat == 0) {
4490 const auto success = m_generator.next();
4494 return m_current_repeat < m_target_repeats;
4500 if (m_repeat_index == m_returned.size()) {
4504 return m_current_repeat < m_target_repeats;
4512template <
typename T,
typename U,
typename Func>
class MapGenerator :
public IGenerator<T> {
4520 template <
typename F2 = Func>
4522 : m_generator(std::move(generator)), m_function(std::forward<F2>(function)),
4523 m_cache(m_function(m_generator.get())) {}
4525 T
const& get()
const override {
return m_cache; }
4526 bool next()
override {
4527 const auto success = m_generator.next();
4529 m_cache = m_function(m_generator.get());
4535template <
typename Func,
typename U,
typename T = FunctionReturnType<Func, U>>
4538 std::forward<Func>(function), std::move(generator)));
4541template <
typename T,
typename U,
typename Func>
4542GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4543 return GeneratorWrapper<T>(pf::make_unique<MapGenerator<T, U, Func>>(
4544 std::forward<Func>(function), std::move(generator)));
4547template <
typename T>
class ChunkGenerator final :
public IGenerator<std::vector<T>> {
4548 std::vector<T> m_chunk;
4549 size_t m_chunk_size;
4551 bool m_used_up =
false;
4555 : m_chunk_size(size), m_generator(std::move(generator)) {
4556 m_chunk.reserve(m_chunk_size);
4557 if (m_chunk_size != 0) {
4558 m_chunk.push_back(m_generator.get());
4559 for (
size_t i = 1; i < m_chunk_size; ++i) {
4560 if (!m_generator.next()) {
4561 Catch::throw_exception(
4564 m_chunk.push_back(m_generator.get());
4568 std::vector<T>
const& get()
const override {
return m_chunk; }
4569 bool next()
override {
4571 for (
size_t idx = 0; idx < m_chunk_size; ++idx) {
4572 if (!m_generator.next()) {
4575 m_chunk.push_back(m_generator.get());
4581template <
typename T>
4584 pf::make_unique<ChunkGenerator<T>>(size, std::move(generator)));
4604using IConfigPtr = std::shared_ptr<IConfig const>;
4610 virtual IRunner* getRunner() = 0;
4611 virtual IConfigPtr
const& getConfig()
const = 0;
4616 virtual void setResultCapture(
IResultCapture* resultCapture) = 0;
4617 virtual void setRunner(
IRunner* runner) = 0;
4618 virtual void setConfig(IConfigPtr
const& config) = 0;
4623 friend void cleanUpContext();
4624 static void createContext();
4628 if (!IMutableContext::currentContext)
4629 IMutableContext::createContext();
4631 return *IMutableContext::currentContext;
4634inline IContext& getCurrentContext() {
4635 return getCurrentMutableContext();
4638void cleanUpContext();
4652template <
typename T>
class Option {
4654 Option() : nullableValue(
nullptr) {}
4655 Option(T
const& _value) : nullableValue(
new(storage) T(_value)) {}
4656 Option(Option
const& _other) : nullableValue(_other ?
new(storage) T(*_other) :
nullptr) {}
4658 ~Option() { reset(); }
4660 Option& operator=(Option
const& _other) {
4661 if (&_other !=
this) {
4664 nullableValue =
new (storage) T(*_other);
4668 Option& operator=(T
const& _value) {
4670 nullableValue =
new (storage) T(_value);
4676 nullableValue->~T();
4677 nullableValue =
nullptr;
4680 T& operator*() {
return *nullableValue; }
4681 T
const& operator*()
const {
return *nullableValue; }
4682 T* operator->() {
return nullableValue; }
4683 const T* operator->()
const {
return nullableValue; }
4685 T valueOr(T
const& defaultValue)
const {
return nullableValue ? *nullableValue : defaultValue; }
4687 bool some()
const {
return nullableValue !=
nullptr; }
4688 bool none()
const {
return nullableValue ==
nullptr; }
4690 bool operator!()
const {
return nullableValue ==
nullptr; }
4691 explicit operator bool()
const {
return some(); }
4695 alignas(
alignof(T))
char storage[
sizeof(T)];
4709enum class Verbosity { Quiet = 0, Normal, High };
4712 enum What { Nothing = 0x00, NoAssertions = 0x01, NoTests = 0x02 };
4716 enum OrNot { DefaultForReporter, Always, Never };
4719 enum InWhatOrder { InDeclarationOrder, InLexicographicalOrder, InRandomOrder };
4722 enum YesOrNo { Auto, Yes, No };
4729 BeforeStartAndExit = BeforeStart | BeforeExit
4739 virtual bool allowThrows()
const = 0;
4740 virtual std::ostream& stream()
const = 0;
4741 virtual std::string name()
const = 0;
4742 virtual bool includeSuccessfulResults()
const = 0;
4743 virtual bool shouldDebugBreak()
const = 0;
4744 virtual bool warnAboutMissingAssertions()
const = 0;
4745 virtual bool warnAboutNoTests()
const = 0;
4746 virtual int abortAfter()
const = 0;
4747 virtual bool showInvisibles()
const = 0;
4748 virtual ShowDurations::OrNot showDurations()
const = 0;
4749 virtual double minDuration()
const = 0;
4750 virtual TestSpec
const& testSpec()
const = 0;
4751 virtual bool hasTestFilters()
const = 0;
4752 virtual std::vector<std::string>
const& getTestsOrTags()
const = 0;
4753 virtual RunTests::InWhatOrder runOrder()
const = 0;
4754 virtual unsigned int rngSeed()
const = 0;
4755 virtual UseColour::YesOrNo useColour()
const = 0;
4756 virtual std::vector<std::string>
const& getSectionsToRun()
const = 0;
4757 virtual Verbosity verbosity()
const = 0;
4759 virtual bool benchmarkNoAnalysis()
const = 0;
4760 virtual int benchmarkSamples()
const = 0;
4761 virtual double benchmarkConfidenceInterval()
const = 0;
4762 virtual unsigned int benchmarkResamples()
const = 0;
4763 virtual std::chrono::milliseconds benchmarkWarmupTime()
const = 0;
4766using IConfigPtr = std::shared_ptr<IConfig const>;
4782 using state_type = std::uint64_t;
4785 using result_type = std::uint32_t;
4786 static constexpr result_type(min)() {
return 0; }
4787 static constexpr result_type(max)() {
return static_cast<result_type
>(-1); }
4790 SimplePcg32() : SimplePcg32(0xed743cc4U) {}
4792 explicit SimplePcg32(result_type seed_);
4794 void seed(result_type seed_);
4795 void discard(uint64_t skip);
4797 result_type operator()();
4800 friend bool operator==(SimplePcg32
const& lhs, SimplePcg32
const& rhs);
4801 friend bool operator!=(SimplePcg32
const& lhs, SimplePcg32
const& rhs);
4806 std::uint64_t m_state;
4811 static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
4820namespace Generators {
4822template <
typename Float>
class RandomFloatingGenerator final :
public IGenerator<Float> {
4824 std::uniform_real_distribution<Float> m_dist;
4825 Float m_current_number;
4828 RandomFloatingGenerator(Float a, Float b) : m_rng(rng()), m_dist(a, b) {
4829 static_cast<void>(next());
4832 Float
const& get()
const override {
return m_current_number; }
4833 bool next()
override {
4834 m_current_number = m_dist(m_rng);
4839template <
typename Integer>
class RandomIntegerGenerator final :
public IGenerator<Integer> {
4841 std::uniform_int_distribution<Integer> m_dist;
4842 Integer m_current_number;
4845 RandomIntegerGenerator(Integer a, Integer b) : m_rng(rng()), m_dist(a, b) {
4846 static_cast<void>(next());
4849 Integer
const& get()
const override {
return m_current_number; }
4850 bool next()
override {
4851 m_current_number = m_dist(m_rng);
4858template <
typename T>
4859typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
4865template <
typename T>
4866typename std::enable_if<std::is_floating_point<T>::value, GeneratorWrapper<T>>::type random(T a,
4868 return GeneratorWrapper<T>(pf::make_unique<RandomFloatingGenerator<T>>(a, b));
4871template <
typename T>
class RangeGenerator final :
public IGenerator<T> {
4878 RangeGenerator(T
const& start, T
const& end, T
const& step)
4879 : m_current(start), m_end(end), m_step(step), m_positive(m_step > T(0)) {
4880 assert(m_current != m_end &&
"Range start and end cannot be equal");
4881 assert(m_step != T(0) &&
"Step size cannot be zero");
4882 assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) &&
4883 "Step moves away from end");
4886 RangeGenerator(T
const& start, T
const& end)
4887 : RangeGenerator(start, end, (start < end) ? T(1) : T(-1)) {}
4889 T
const& get()
const override {
return m_current; }
4891 bool next()
override {
4892 m_current += m_step;
4893 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
4897template <
typename T>
GeneratorWrapper<T> range(T
const& start, T
const& end, T
const& step) {
4898 static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value,
4899 "Type must be numeric");
4903template <
typename T> GeneratorWrapper<T> range(T
const& start, T
const& end) {
4904 static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value,
4905 "Type must be an integer");
4906 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
4909template <
typename T>
class IteratorGenerator final :
public IGenerator<T> {
4910 static_assert(!std::is_same<T, bool>::value,
4911 "IteratorGenerator currently does not support bools"
4912 "because of std::vector<bool> specialization");
4914 std::vector<T> m_elems;
4915 size_t m_current = 0;
4918 template <
typename InputIterator,
typename InputSentinel>
4919 IteratorGenerator(InputIterator first, InputSentinel last) : m_elems(first, last) {
4920 if (m_elems.empty()) {
4921 Catch::throw_exception(
4926 T
const& get()
const override {
return m_elems[m_current]; }
4928 bool next()
override {
4930 return m_current != m_elems.size();
4934template <
typename InputIterator,
typename InputSentinel,
4935 typename ResultType =
typename std::iterator_traits<InputIterator>::value_type>
4940template <
typename Container,
typename ResultType =
typename Container::value_type>
4941GeneratorWrapper<ResultType> from_range(Container
const& cnt) {
4942 return GeneratorWrapper<ResultType>(
4943 pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
4960#pragma clang diagnostic push
4961#pragma clang diagnostic ignored "-Wpadded"
4968struct TestCaseInfo {
4969 enum SpecialProperties {
4972 ShouldFail = 1 << 2,
4975 NonPortable = 1 << 5,
4979 TestCaseInfo(std::string
const& _name, std::string
const& _className,
4980 std::string
const& _description, std::vector<std::string>
const& _tags,
4983 friend void setTags(TestCaseInfo& testCaseInfo, std::vector<std::string> tags);
4985 bool isHidden()
const;
4986 bool throws()
const;
4987 bool okToFail()
const;
4988 bool expectedToFail()
const;
4990 std::string tagsAsString()
const;
4993 std::string className;
4994 std::string description;
4995 std::vector<std::string> tags;
4996 std::vector<std::string> lcaseTags;
4998 SpecialProperties properties;
5001class TestCase :
public TestCaseInfo {
5005 TestCase withName(std::string
const& _newName)
const;
5007 void invoke()
const;
5009 TestCaseInfo
const& getTestCaseInfo()
const;
5011 bool operator==(TestCase
const& other)
const;
5012 bool operator<(TestCase
const& other)
const;
5015 std::shared_ptr<ITestInvoker> test;
5023#pragma clang diagnostic pop
5033 virtual bool aborting()
const = 0;
5042#import <objc/runtime.h>
5064class OcMethod :
public ITestInvoker {
5067 OcMethod(Class cls,
SEL sel) : m_cls(cls), m_sel(sel) {}
5069 virtual void invoke()
const {
5070 id obj = [[m_cls alloc] init];
5072 performOptionalSelector(obj,
@selector(setUp));
5073 performOptionalSelector(obj, m_sel);
5074 performOptionalSelector(obj,
@selector(tearDown));
5076 arcSafeRelease(obj);
5080 virtual ~OcMethod() {}
5088inline std::string getAnnotation(Class cls, std::string
const& annotationName,
5089 std::string
const& testCaseName) {
5090 NSString* selStr = [[NSString alloc]
5091 initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
5092 SEL sel = NSSelectorFromString(selStr);
5093 arcSafeRelease(selStr);
5094 id value = performOptionalSelector(cls, sel);
5096 return [(NSString*)value UTF8String];
5101inline std::size_t registerTestMethods() {
5102 std::size_t noTestMethods = 0;
5103 int noClasses = objc_getClassList(
nullptr, 0);
5105 Class* classes = (CATCH_UNSAFE_UNRETAINED Class*)malloc(
sizeof(Class) * noClasses);
5106 objc_getClassList(classes, noClasses);
5108 for (
int c = 0; c < noClasses; c++) {
5109 Class cls = classes[c];
5112 Method* methods = class_copyMethodList(cls, &count);
5113 for (u_int m = 0; m < count; m++) {
5114 SEL selector = method_getName(methods[m]);
5115 std::string methodName = sel_getName(selector);
5116 if (startsWith(methodName,
"Catch_TestCase_")) {
5117 std::string testCaseName = methodName.substr(15);
5118 std::string name = Detail::getAnnotation(cls,
"Name", testCaseName);
5119 std::string desc = Detail::getAnnotation(cls,
"Description", testCaseName);
5120 const char* className = class_getName(cls);
5122 getMutableRegistryHub().registerTest(makeTestCase(
5123 new OcMethod(cls, selector), className,
5131 return noTestMethods;
5134#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
5138namespace NSStringMatchers {
5140struct StringHolder : MatcherBase<NSString*> {
5141 StringHolder(NSString* substr) : m_substr([substr copy]) {}
5142 StringHolder(StringHolder
const& other) : m_substr([other.m_substr copy]) {}
5143 StringHolder() { arcSafeRelease(m_substr); }
5145 bool match(NSString* str)
const override {
return false; }
5147 NSString* CATCH_ARC_STRONG m_substr;
5150struct Equals : StringHolder {
5151 Equals(NSString* substr) : StringHolder(substr) {}
5153 bool match(NSString* str)
const override {
5154 return (str != nil || m_substr == nil) && [str isEqualToString:m_substr];
5157 std::string describe()
const override {
5158 return "equals string: " + Catch::Detail::stringify(m_substr);
5162struct Contains : StringHolder {
5163 Contains(NSString* substr) : StringHolder(substr) {}
5165 bool match(NSString* str)
const override {
5166 return (str != nil || m_substr == nil) &&
5167 [str rangeOfString:m_substr].location != NSNotFound;
5170 std::string describe()
const override {
5171 return "contains string: " + Catch::Detail::stringify(m_substr);
5175struct StartsWith : StringHolder {
5176 StartsWith(NSString* substr) : StringHolder(substr) {}
5178 bool match(NSString* str)
const override {
5179 return (str != nil || m_substr == nil) && [str rangeOfString:m_substr].location == 0;
5182 std::string describe()
const override {
5183 return "starts with: " + Catch::Detail::stringify(m_substr);
5186struct EndsWith : StringHolder {
5187 EndsWith(NSString* substr) : StringHolder(substr) {}
5189 bool match(NSString* str)
const override {
5190 return (str != nil || m_substr == nil) &&
5191 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
5194 std::string describe()
const override {
5195 return "ends with: " + Catch::Detail::stringify(m_substr);
5202inline Impl::NSStringMatchers::Equals Equals(NSString* substr) {
5203 return Impl::NSStringMatchers::Equals(substr);
5206inline Impl::NSStringMatchers::Contains Contains(NSString* substr) {
5207 return Impl::NSStringMatchers::Contains(substr);
5210inline Impl::NSStringMatchers::StartsWith StartsWith(NSString* substr) {
5211 return Impl::NSStringMatchers::StartsWith(substr);
5214inline Impl::NSStringMatchers::EndsWith EndsWith(NSString* substr) {
5215 return Impl::NSStringMatchers::EndsWith(substr);
5220using namespace Matchers;
5227#define OC_MAKE_UNIQUE_NAME(root, uniqueSuffix) root##uniqueSuffix
5228#define OC_TEST_CASE2(name, desc, uniqueSuffix) \
5229 +(NSString*)OC_MAKE_UNIQUE_NAME(Catch_Name_test_, uniqueSuffix) { \
5232 +(NSString*)OC_MAKE_UNIQUE_NAME(Catch_Description_test_, uniqueSuffix) { \
5235 -(void)OC_MAKE_UNIQUE_NAME(Catch_TestCase_test_, uniqueSuffix)
5237#define OC_TEST_CASE(name, desc) OC_TEST_CASE2(name, desc, __LINE__)
5243#if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5255#pragma clang diagnostic push
5256#pragma clang diagnostic ignored "-Wpadded"
5262#pragma clang diagnostic push
5263#pragma clang diagnostic ignored "-Wpadded"
5269class WildcardPattern {
5270 enum WildcardPosition {
5272 WildcardAtStart = 1,
5274 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
5278 WildcardPattern(std::string
const& pattern, CaseSensitive::Choice caseSensitivity);
5279 virtual ~WildcardPattern() =
default;
5280 virtual bool matches(std::string
const& str)
const;
5283 std::string normaliseString(std::string
const& str)
const;
5284 CaseSensitive::Choice m_caseSensitivity;
5285 WildcardPosition m_wildcard = NoWildcard;
5286 std::string m_pattern;
5302 explicit Pattern(std::string
const& name);
5304 virtual bool matches(TestCaseInfo
const& testCase)
const = 0;
5305 std::string
const& name()
const;
5308 std::string
const m_name;
5310 using PatternPtr = std::shared_ptr<Pattern>;
5312 class NamePattern :
public Pattern {
5314 explicit NamePattern(std::string
const& name, std::string
const& filterString);
5315 bool matches(TestCaseInfo
const& testCase)
const override;
5318 WildcardPattern m_wildcardPattern;
5321 class TagPattern :
public Pattern {
5323 explicit TagPattern(std::string
const& tag, std::string
const& filterString);
5324 bool matches(TestCaseInfo
const& testCase)
const override;
5330 class ExcludedPattern :
public Pattern {
5332 explicit ExcludedPattern(PatternPtr
const& underlyingPattern);
5333 bool matches(TestCaseInfo
const& testCase)
const override;
5336 PatternPtr m_underlyingPattern;
5340 std::vector<PatternPtr> m_patterns;
5342 bool matches(TestCaseInfo
const& testCase)
const;
5343 std::string name()
const;
5347 struct FilterMatch {
5349 std::vector<TestCase const*> tests;
5351 using Matches = std::vector<FilterMatch>;
5352 using vectorStrings = std::vector<std::string>;
5354 bool hasFilters()
const;
5355 bool matches(TestCaseInfo
const& testCase)
const;
5356 Matches matchesByFilter(std::vector<TestCase>
const& testCases, IConfig
const& config)
const;
5357 const vectorStrings& getInvalidArgs()
const;
5360 std::vector<Filter> m_filters;
5361 std::vector<std::string> m_invalidArgs;
5362 friend class TestSpecParser;
5367#pragma clang diagnostic pop
5379struct ITagAliasRegistry {
5380 virtual ~ITagAliasRegistry();
5382 virtual TagAlias
const* find(std::string
const& alias)
const = 0;
5383 virtual std::string expandAliases(std::string
const& unexpandedTestSpec)
const = 0;
5385 static ITagAliasRegistry
const& get();
5393class TestSpecParser {
5394 enum Mode { None, Name, QuotedName, Tag, EscapedName };
5396 Mode lastMode = None;
5397 bool m_exclusion =
false;
5398 std::size_t m_pos = 0;
5399 std::size_t m_realPatternPos = 0;
5401 std::string m_substring;
5402 std::string m_patternName;
5403 std::vector<std::size_t> m_escapeChars;
5404 TestSpec::Filter m_currentFilter;
5405 TestSpec m_testSpec;
5406 ITagAliasRegistry
const* m_tagAliases =
nullptr;
5409 TestSpecParser(ITagAliasRegistry
const& tagAliases);
5411 TestSpecParser& parse(std::string
const& arg);
5412 TestSpec testSpec();
5415 bool visitChar(
char c);
5416 void startNewMode(Mode mode);
5417 bool processNoneChar(
char c);
5418 void processNameChar(
char c);
5419 bool processOtherChar(
char c);
5422 bool isControlChar(
char c)
const;
5423 void saveLastMode();
5424 void revertBackToLastMode();
5429 std::string preprocessPattern();
5431 void addNamePattern();
5433 void addTagPattern();
5435 inline void addCharToPattern(
char c) {
5441TestSpec parseTestSpec(std::string
const& arg);
5446#pragma clang diagnostic pop
5456#ifndef CATCH_CONFIG_CONSOLE_WIDTH
5457#define CATCH_CONFIG_CONSOLE_WIDTH 80
5465 bool listTests =
false;
5466 bool listTags =
false;
5467 bool listReporters =
false;
5468 bool listTestNamesOnly =
false;
5470 bool showSuccessfulTests =
false;
5471 bool shouldDebugBreak =
false;
5472 bool noThrow =
false;
5473 bool showHelp =
false;
5474 bool showInvisibles =
false;
5475 bool filenamesAsTags =
false;
5476 bool libIdentify =
false;
5478 int abortAfter = -1;
5479 unsigned int rngSeed = 0;
5481 bool benchmarkNoAnalysis =
false;
5482 unsigned int benchmarkSamples = 100;
5483 double benchmarkConfidenceInterval = 0.95;
5484 unsigned int benchmarkResamples = 100000;
5485 std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
5487 Verbosity verbosity = Verbosity::Normal;
5488 WarnAbout::What warnings = WarnAbout::Nothing;
5489 ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
5490 double minDuration = -1;
5491 RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
5492 UseColour::YesOrNo useColour = UseColour::Auto;
5493 WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
5495 std::string outputFilename;
5497 std::string processName;
5498#ifndef CATCH_CONFIG_DEFAULT_REPORTER
5499#define CATCH_CONFIG_DEFAULT_REPORTER "console"
5501 std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5502#undef CATCH_CONFIG_DEFAULT_REPORTER
5504 std::vector<std::string> testsOrTags;
5505 std::vector<std::string> sectionsToRun;
5508class Config :
public IConfig {
5511 Config(ConfigData
const& data);
5512 virtual ~Config() =
default;
5514 std::string
const& getFilename()
const;
5516 bool listTests()
const;
5517 bool listTestNamesOnly()
const;
5518 bool listTags()
const;
5519 bool listReporters()
const;
5521 std::string getProcessName()
const;
5522 std::string
const& getReporterName()
const;
5524 std::vector<std::string>
const& getTestsOrTags()
const override;
5525 std::vector<std::string>
const& getSectionsToRun()
const override;
5527 TestSpec
const& testSpec()
const override;
5528 bool hasTestFilters()
const override;
5530 bool showHelp()
const;
5533 bool allowThrows()
const override;
5534 std::ostream& stream()
const override;
5535 std::string name()
const override;
5536 bool includeSuccessfulResults()
const override;
5537 bool warnAboutMissingAssertions()
const override;
5538 bool warnAboutNoTests()
const override;
5539 ShowDurations::OrNot showDurations()
const override;
5540 double minDuration()
const override;
5541 RunTests::InWhatOrder runOrder()
const override;
5542 unsigned int rngSeed()
const override;
5543 UseColour::YesOrNo useColour()
const override;
5544 bool shouldDebugBreak()
const override;
5545 int abortAfter()
const override;
5546 bool showInvisibles()
const override;
5547 Verbosity verbosity()
const override;
5548 bool benchmarkNoAnalysis()
const override;
5549 int benchmarkSamples()
const override;
5550 double benchmarkConfidenceInterval()
const override;
5551 unsigned int benchmarkResamples()
const override;
5552 std::chrono::milliseconds benchmarkWarmupTime()
const override;
5555 IStream
const* openStream();
5558 std::unique_ptr<IStream const> m_stream;
5559 TestSpec m_testSpec;
5560 bool m_hasTestFilters =
false;
5572struct AssertionResultData {
5573 AssertionResultData() =
delete;
5575 AssertionResultData(ResultWas::OfType _resultType, LazyExpression
const& _lazyExpression);
5577 std::string message;
5578 mutable std::string reconstructedExpression;
5579 LazyExpression lazyExpression;
5580 ResultWas::OfType resultType;
5582 std::string reconstructExpression()
const;
5585class AssertionResult {
5587 AssertionResult() =
delete;
5588 AssertionResult(AssertionInfo
const& info, AssertionResultData
const& data);
5591 bool succeeded()
const;
5592 ResultWas::OfType getResultType()
const;
5593 bool hasExpression()
const;
5594 bool hasMessage()
const;
5595 std::string getExpression()
const;
5596 std::string getExpressionInMacro()
const;
5597 bool hasExpandedExpression()
const;
5598 std::string getExpandedExpression()
const;
5599 std::string getMessage()
const;
5600 SourceLineInfo getSourceInfo()
const;
5601 StringRef getTestMacroName()
const;
5604 AssertionInfo m_info;
5605 AssertionResultData m_resultData;
5611#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5617namespace Benchmark {
5618template <
typename Duration>
struct Estimate {
5620 Duration lower_bound;
5621 Duration upper_bound;
5622 double confidence_interval;
5624 template <
typename Duration2>
operator Estimate<Duration2>()
const {
5625 return {point, lower_bound, upper_bound, confidence_interval};
5637namespace Benchmark {
5638struct OutlierClassification {
5639 int samples_seen = 0;
5643 int high_severe = 0;
5645 int total()
const {
return low_severe + low_mild + high_mild + high_severe; }
5664struct ReporterConfig {
5665 explicit ReporterConfig(IConfigPtr
const& _fullConfig);
5667 ReporterConfig(IConfigPtr
const& _fullConfig, std::ostream& _stream);
5669 std::ostream& stream()
const;
5670 IConfigPtr fullConfig()
const;
5673 std::ostream* m_stream;
5674 IConfigPtr m_fullConfig;
5677struct ReporterPreferences {
5678 bool shouldRedirectStdOut =
false;
5679 bool shouldReportAllAssertions =
false;
5682template <
typename T>
struct LazyStat :
Option<T> {
5683 LazyStat& operator=(T
const& _value) {
5684 Option<T>::operator=(_value);
5696 TestRunInfo(std::string
const& _name);
5700 GroupInfo(std::string
const& _name, std::size_t _groupIndex, std::size_t _groupsCount);
5703 std::size_t groupIndex;
5704 std::size_t groupsCounts;
5707struct AssertionStats {
5708 AssertionStats(AssertionResult
const& _assertionResult,
5709 std::vector<MessageInfo>
const& _infoMessages, Totals
const& _totals);
5711 AssertionStats(AssertionStats
const&) =
default;
5712 AssertionStats(AssertionStats&&) =
default;
5713 AssertionStats& operator=(AssertionStats
const&) =
delete;
5714 AssertionStats& operator=(AssertionStats&&) =
delete;
5715 virtual ~AssertionStats();
5717 AssertionResult assertionResult;
5718 std::vector<MessageInfo> infoMessages;
5722struct SectionStats {
5723 SectionStats(SectionInfo
const& _sectionInfo, Counts
const& _assertions,
5724 double _durationInSeconds,
bool _missingAssertions);
5725 SectionStats(SectionStats
const&) =
default;
5726 SectionStats(SectionStats&&) =
default;
5727 SectionStats& operator=(SectionStats
const&) =
default;
5728 SectionStats& operator=(SectionStats&&) =
default;
5729 virtual ~SectionStats();
5731 SectionInfo sectionInfo;
5733 double durationInSeconds;
5734 bool missingAssertions;
5737struct TestCaseStats {
5738 TestCaseStats(TestCaseInfo
const& _testInfo, Totals
const& _totals, std::string
const& _stdOut,
5739 std::string
const& _stdErr,
bool _aborting);
5741 TestCaseStats(TestCaseStats
const&) =
default;
5742 TestCaseStats(TestCaseStats&&) =
default;
5743 TestCaseStats& operator=(TestCaseStats
const&) =
default;
5744 TestCaseStats& operator=(TestCaseStats&&) =
default;
5745 virtual ~TestCaseStats();
5747 TestCaseInfo testInfo;
5754struct TestGroupStats {
5755 TestGroupStats(GroupInfo
const& _groupInfo, Totals
const& _totals,
bool _aborting);
5756 TestGroupStats(GroupInfo
const& _groupInfo);
5758 TestGroupStats(TestGroupStats
const&) =
default;
5759 TestGroupStats(TestGroupStats&&) =
default;
5760 TestGroupStats& operator=(TestGroupStats
const&) =
default;
5761 TestGroupStats& operator=(TestGroupStats&&) =
default;
5762 virtual ~TestGroupStats();
5764 GroupInfo groupInfo;
5769struct TestRunStats {
5770 TestRunStats(TestRunInfo
const& _runInfo, Totals
const& _totals,
bool _aborting);
5772 TestRunStats(TestRunStats
const&) =
default;
5773 TestRunStats(TestRunStats&&) =
default;
5774 TestRunStats& operator=(TestRunStats
const&) =
default;
5775 TestRunStats& operator=(TestRunStats&&) =
default;
5776 virtual ~TestRunStats();
5778 TestRunInfo runInfo;
5783#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5784struct BenchmarkInfo {
5786 double estimatedDuration;
5789 unsigned int resamples;
5790 double clockResolution;
5794template <
class Duration>
struct BenchmarkStats {
5797 std::vector<Duration> samples;
5798 Benchmark::Estimate<Duration> mean;
5799 Benchmark::Estimate<Duration> standardDeviation;
5800 Benchmark::OutlierClassification outliers;
5801 double outlierVariance;
5803 template <
typename Duration2>
operator BenchmarkStats<Duration2>()
const {
5804 std::vector<Duration2> samples2;
5805 samples2.reserve(samples.size());
5806 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2),
5807 [](Duration d) { return Duration2(d); });
5809 info, std::move(samples2), mean, standardDeviation, outliers, outlierVariance,
5815struct IStreamingReporter {
5816 virtual ~IStreamingReporter() =
default;
5822 virtual ReporterPreferences getPreferences()
const = 0;
5824 virtual void noMatchingTestCases(std::string
const& spec) = 0;
5826 virtual void reportInvalidArguments(std::string
const&) {}
5828 virtual void testRunStarting(TestRunInfo
const& testRunInfo) = 0;
5829 virtual void testGroupStarting(GroupInfo
const& groupInfo) = 0;
5831 virtual void testCaseStarting(TestCaseInfo
const& testInfo) = 0;
5832 virtual void sectionStarting(SectionInfo
const& sectionInfo) = 0;
5834#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5835 virtual void benchmarkPreparing(std::string
const&) {}
5836 virtual void benchmarkStarting(BenchmarkInfo
const&) {}
5837 virtual void benchmarkEnded(BenchmarkStats<>
const&) {}
5838 virtual void benchmarkFailed(std::string
const&) {}
5841 virtual void assertionStarting(AssertionInfo
const& assertionInfo) = 0;
5844 virtual bool assertionEnded(AssertionStats
const& assertionStats) = 0;
5846 virtual void sectionEnded(SectionStats
const& sectionStats) = 0;
5847 virtual void testCaseEnded(TestCaseStats
const& testCaseStats) = 0;
5848 virtual void testGroupEnded(TestGroupStats
const& testGroupStats) = 0;
5849 virtual void testRunEnded(TestRunStats
const& testRunStats) = 0;
5851 virtual void skipTest(TestCaseInfo
const& testInfo) = 0;
5854 virtual void fatalErrorEncountered(StringRef name);
5856 virtual bool isMulti()
const;
5858using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
5860struct IReporterFactory {
5861 virtual ~IReporterFactory();
5862 virtual IStreamingReporterPtr create(ReporterConfig
const& config)
const = 0;
5863 virtual std::string getDescription()
const = 0;
5865using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
5867struct IReporterRegistry {
5868 using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
5869 using Listeners = std::vector<IReporterFactoryPtr>;
5871 virtual ~IReporterRegistry();
5872 virtual IStreamingReporterPtr create(std::string
const& name,
5873 IConfigPtr
const& config)
const = 0;
5874 virtual FactoryMap
const& getFactories()
const = 0;
5875 virtual Listeners
const& getListeners()
const = 0;
5890void prepareExpandedExpression(AssertionResult& result);
5893std::string getFormattedDuration(
double duration);
5896bool shouldShowDuration(
IConfig const& config,
double duration);
5898std::string serializeFilters(std::vector<std::string>
const& container);
5900template <
typename DerivedT>
struct StreamingReporterBase : IStreamingReporter {
5902 StreamingReporterBase(ReporterConfig
const& _config)
5903 : m_config(_config.fullConfig()), stream(_config.stream()) {
5904 m_reporterPrefs.shouldRedirectStdOut =
false;
5905 if (!DerivedT::getSupportedVerbosities().count(m_config->verbosity()))
5906 CATCH_ERROR(
"Verbosity level not supported by this reporter");
5909 ReporterPreferences getPreferences()
const override {
return m_reporterPrefs; }
5911 static std::set<Verbosity> getSupportedVerbosities() {
return {Verbosity::Normal}; }
5913 ~StreamingReporterBase()
override =
default;
5915 void noMatchingTestCases(std::string
const&)
override {}
5917 void reportInvalidArguments(std::string
const&)
override {}
5919 void testRunStarting(TestRunInfo
const& _testRunInfo)
override {
5920 currentTestRunInfo = _testRunInfo;
5923 void testGroupStarting(GroupInfo
const& _groupInfo)
override { currentGroupInfo = _groupInfo; }
5925 void testCaseStarting(TestCaseInfo
const& _testInfo)
override {
5926 currentTestCaseInfo = _testInfo;
5928 void sectionStarting(SectionInfo
const& _sectionInfo)
override {
5929 m_sectionStack.push_back(_sectionInfo);
5932 void sectionEnded(SectionStats
const& )
override {
5933 m_sectionStack.pop_back();
5935 void testCaseEnded(TestCaseStats
const& )
override {
5936 currentTestCaseInfo.reset();
5938 void testGroupEnded(TestGroupStats
const& )
override {
5939 currentGroupInfo.reset();
5941 void testRunEnded(TestRunStats
const& )
override {
5942 currentTestCaseInfo.reset();
5943 currentGroupInfo.reset();
5944 currentTestRunInfo.reset();
5947 void skipTest(TestCaseInfo
const&)
override {
5952 IConfigPtr m_config;
5953 std::ostream& stream;
5955 LazyStat<TestRunInfo> currentTestRunInfo;
5956 LazyStat<GroupInfo> currentGroupInfo;
5957 LazyStat<TestCaseInfo> currentTestCaseInfo;
5959 std::vector<SectionInfo> m_sectionStack;
5960 ReporterPreferences m_reporterPrefs;
5963template <
typename DerivedT>
struct CumulativeReporterBase : IStreamingReporter {
5964 template <
typename T,
typename ChildNodeT>
struct Node {
5965 explicit Node(T
const& _value) : value(_value) {}
5968 using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
5970 ChildNodes children;
5972 struct SectionNode {
5973 explicit SectionNode(SectionStats
const& _stats) : stats(_stats) {}
5974 virtual ~SectionNode() =
default;
5976 bool operator==(SectionNode
const& other)
const {
5977 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
5979 bool operator==(std::shared_ptr<SectionNode>
const& other)
const {
5980 return operator==(*other);
5984 using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
5985 using Assertions = std::vector<AssertionStats>;
5986 ChildSections childSections;
5987 Assertions assertions;
5992 struct BySectionInfo {
5993 BySectionInfo(SectionInfo
const& other) : m_other(other) {}
5994 BySectionInfo(BySectionInfo
const& other) : m_other(other.m_other) {}
5995 bool operator()(std::shared_ptr<SectionNode>
const& node)
const {
5996 return ((node->stats.sectionInfo.name == m_other.name) &&
5997 (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
5999 void operator=(BySectionInfo
const&) =
delete;
6002 SectionInfo
const& m_other;
6005 using TestCaseNode = Node<TestCaseStats, SectionNode>;
6006 using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
6007 using TestRunNode = Node<TestRunStats, TestGroupNode>;
6009 CumulativeReporterBase(ReporterConfig
const& _config)
6010 : m_config(_config.fullConfig()), stream(_config.stream()) {
6011 m_reporterPrefs.shouldRedirectStdOut =
false;
6012 if (!DerivedT::getSupportedVerbosities().count(m_config->verbosity()))
6013 CATCH_ERROR(
"Verbosity level not supported by this reporter");
6015 ~CumulativeReporterBase()
override =
default;
6017 ReporterPreferences getPreferences()
const override {
return m_reporterPrefs; }
6019 static std::set<Verbosity> getSupportedVerbosities() {
return {Verbosity::Normal}; }
6021 void testRunStarting(TestRunInfo
const&)
override {}
6022 void testGroupStarting(GroupInfo
const&)
override {}
6024 void testCaseStarting(TestCaseInfo
const&)
override {}
6026 void sectionStarting(SectionInfo
const& sectionInfo)
override {
6027 SectionStats incompleteStats(sectionInfo, Counts(), 0,
false);
6028 std::shared_ptr<SectionNode> node;
6029 if (m_sectionStack.empty()) {
6031 m_rootSection = std::make_shared<SectionNode>(incompleteStats);
6032 node = m_rootSection;
6034 SectionNode& parentNode = *m_sectionStack.back();
6035 auto it = std::find_if(parentNode.childSections.begin(), parentNode.childSections.end(),
6036 BySectionInfo(sectionInfo));
6037 if (it == parentNode.childSections.end()) {
6038 node = std::make_shared<SectionNode>(incompleteStats);
6039 parentNode.childSections.push_back(node);
6043 m_sectionStack.push_back(node);
6044 m_deepestSection = std::move(node);
6047 void assertionStarting(AssertionInfo
const&)
override {}
6049 bool assertionEnded(AssertionStats
const& assertionStats)
override {
6050 assert(!m_sectionStack.empty());
6056 prepareExpandedExpression(
const_cast<AssertionResult&
>(assertionStats.assertionResult));
6057 SectionNode& sectionNode = *m_sectionStack.back();
6058 sectionNode.assertions.push_back(assertionStats);
6061 void sectionEnded(SectionStats
const& sectionStats)
override {
6062 assert(!m_sectionStack.empty());
6063 SectionNode& node = *m_sectionStack.back();
6064 node.stats = sectionStats;
6065 m_sectionStack.pop_back();
6067 void testCaseEnded(TestCaseStats
const& testCaseStats)
override {
6068 auto node = std::make_shared<TestCaseNode>(testCaseStats);
6069 assert(m_sectionStack.size() == 0);
6070 node->children.push_back(m_rootSection);
6071 m_testCases.push_back(node);
6072 m_rootSection.reset();
6074 assert(m_deepestSection);
6075 m_deepestSection->stdOut = testCaseStats.stdOut;
6076 m_deepestSection->stdErr = testCaseStats.stdErr;
6078 void testGroupEnded(TestGroupStats
const& testGroupStats)
override {
6079 auto node = std::make_shared<TestGroupNode>(testGroupStats);
6080 node->children.swap(m_testCases);
6081 m_testGroups.push_back(node);
6083 void testRunEnded(TestRunStats
const& testRunStats)
override {
6084 auto node = std::make_shared<TestRunNode>(testRunStats);
6085 node->children.swap(m_testGroups);
6086 m_testRuns.push_back(node);
6087 testRunEndedCumulative();
6089 virtual void testRunEndedCumulative() = 0;
6091 void skipTest(TestCaseInfo
const&)
override {}
6093 IConfigPtr m_config;
6094 std::ostream& stream;
6095 std::vector<AssertionStats> m_assertions;
6096 std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
6097 std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
6098 std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
6100 std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
6102 std::shared_ptr<SectionNode> m_rootSection;
6103 std::shared_ptr<SectionNode> m_deepestSection;
6104 std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
6105 ReporterPreferences m_reporterPrefs;
6108template <
char C>
char const* getLineOfChars() {
6109 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
6111 std::memset(line, C, CATCH_CONFIG_CONSOLE_WIDTH - 1);
6112 line[CATCH_CONFIG_CONSOLE_WIDTH - 1] = 0;
6117struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
6118 TestEventListenerBase(ReporterConfig
const& _config);
6120 static std::set<Verbosity> getSupportedVerbosities();
6122 void assertionStarting(AssertionInfo
const&)
override;
6123 bool assertionEnded(AssertionStats
const&)
override;
6147 BrightRed = Bright | Red,
6148 BrightGreen = Bright | Green,
6149 LightGrey = Bright | Grey,
6150 BrightWhite = Bright | White,
6151 BrightYellow = Bright | Yellow,
6154 FileName = LightGrey,
6155 Warning = BrightYellow,
6156 ResultError = BrightRed,
6157 ResultSuccess = BrightGreen,
6158 ResultExpectedFailure = Warning,
6163 OriginalExpression = Cyan,
6164 ReconstructedExpression = BrightYellow,
6166 SecondaryText = LightGrey,
6171 Colour(Code _colourCode);
6172 Colour(Colour&& other)
noexcept;
6173 Colour& operator=(Colour&& other)
noexcept;
6177 static void use(Code _colourCode);
6180 bool m_moved =
false;
6183std::ostream& operator<<(std::ostream& os, Colour
const&);
6192template <
typename T>
class ReporterRegistrar {
6194 class ReporterFactory :
public IReporterFactory {
6196 IStreamingReporterPtr create(ReporterConfig
const& config)
const override {
6197 return std::unique_ptr<T>(
new T(config));
6200 std::string getDescription()
const override {
return T::getDescription(); }
6204 explicit ReporterRegistrar(std::string
const& name) {
6205 getMutableRegistryHub().registerReporter(name, std::make_shared<ReporterFactory>());
6209template <
typename T>
class ListenerRegistrar {
6211 class ListenerFactory :
public IReporterFactory {
6213 IStreamingReporterPtr create(ReporterConfig
const& config)
const override {
6214 return std::unique_ptr<T>(
new T(config));
6216 std::string getDescription()
const override {
return std::string(); }
6220 ListenerRegistrar() {
6221 getMutableRegistryHub().registerListener(std::make_shared<ListenerFactory>());
6226#if !defined(CATCH_CONFIG_DISABLE)
6228#define CATCH_REGISTER_REPORTER(name, reporterType) \
6229 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6230 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6232 Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType(name); \
6234 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6236#define CATCH_REGISTER_LISTENER(listenerType) \
6237 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6238 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6240 Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; \
6242 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6245#define CATCH_REGISTER_REPORTER(name, reporterType)
6246#define CATCH_REGISTER_LISTENER(listenerType)
6256struct CompactReporter : StreamingReporterBase<CompactReporter> {
6258 using StreamingReporterBase::StreamingReporterBase;
6260 ~CompactReporter()
override;
6262 static std::string getDescription();
6264 void noMatchingTestCases(std::string
const& spec)
override;
6266 void assertionStarting(AssertionInfo
const&)
override;
6268 bool assertionEnded(AssertionStats
const& _assertionStats)
override;
6270 void sectionEnded(SectionStats
const& _sectionStats)
override;
6272 void testRunEnded(TestRunStats
const& _testRunStats)
override;
6280#if defined(_MSC_VER)
6281#pragma warning(push)
6282#pragma warning(disable : 4061)
6289struct SummaryColumn;
6292struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
6293 std::unique_ptr<TablePrinter> m_tablePrinter;
6295 ConsoleReporter(ReporterConfig
const& config);
6296 ~ConsoleReporter()
override;
6297 static std::string getDescription();
6299 void noMatchingTestCases(std::string
const& spec)
override;
6301 void reportInvalidArguments(std::string
const& arg)
override;
6303 void assertionStarting(AssertionInfo
const&)
override;
6305 bool assertionEnded(AssertionStats
const& _assertionStats)
override;
6307 void sectionStarting(SectionInfo
const& _sectionInfo)
override;
6308 void sectionEnded(SectionStats
const& _sectionStats)
override;
6310#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6311 void benchmarkPreparing(std::string
const& name)
override;
6312 void benchmarkStarting(BenchmarkInfo
const& info)
override;
6313 void benchmarkEnded(BenchmarkStats<>
const& stats)
override;
6314 void benchmarkFailed(std::string
const& error)
override;
6317 void testCaseEnded(TestCaseStats
const& _testCaseStats)
override;
6318 void testGroupEnded(TestGroupStats
const& _testGroupStats)
override;
6319 void testRunEnded(TestRunStats
const& _testRunStats)
override;
6320 void testRunStarting(TestRunInfo
const& _testRunInfo)
override;
6325 void lazyPrintWithoutClosingBenchmarkTable();
6326 void lazyPrintRunInfo();
6327 void lazyPrintGroupInfo();
6328 void printTestCaseAndSectionHeader();
6330 void printClosedHeader(std::string
const& _name);
6331 void printOpenHeader(std::string
const& _name);
6335 void printHeaderString(std::string
const& _string, std::size_t indent = 0);
6337 void printTotals(Totals
const& totals);
6338 void printSummaryRow(std::string
const& label, std::vector<SummaryColumn>
const& cols,
6341 void printTotalsDivider(Totals
const& totals);
6342 void printSummaryDivider();
6343 void printTestFilters();
6346 bool m_headerPrinted =
false;
6351#if defined(_MSC_VER)
6363enum class XmlFormatting {
6369XmlFormatting operator|(XmlFormatting lhs, XmlFormatting rhs);
6370XmlFormatting operator&(XmlFormatting lhs, XmlFormatting rhs);
6374 enum ForWhat { ForTextNodes, ForAttributes };
6376 XmlEncode(std::string
const& str, ForWhat forWhat = ForTextNodes);
6378 void encodeTo(std::ostream& os)
const;
6380 friend std::ostream& operator<<(std::ostream& os, XmlEncode
const& xmlEncode);
6389 class ScopedElement {
6391 ScopedElement(XmlWriter* writer, XmlFormatting fmt);
6393 ScopedElement(ScopedElement&& other)
noexcept;
6394 ScopedElement& operator=(ScopedElement&& other)
noexcept;
6398 ScopedElement& writeText(std::string
const& text,
6399 XmlFormatting fmt = XmlFormatting::Newline |
6400 XmlFormatting::Indent);
6402 template <
typename T>
6403 ScopedElement& writeAttribute(std::string
const& name, T
const& attribute) {
6404 m_writer->writeAttribute(name, attribute);
6409 mutable XmlWriter* m_writer =
nullptr;
6410 XmlFormatting m_fmt;
6413 XmlWriter(std::ostream& os = Catch::cout());
6416 XmlWriter(XmlWriter
const&) =
delete;
6417 XmlWriter& operator=(XmlWriter
const&) =
delete;
6419 XmlWriter& startElement(std::string
const& name,
6420 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6422 ScopedElement scopedElement(std::string
const& name,
6423 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6425 XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6427 XmlWriter& writeAttribute(std::string
const& name, std::string
const& attribute);
6429 XmlWriter& writeAttribute(std::string
const& name,
bool attribute);
6431 template <
typename T> XmlWriter& writeAttribute(std::string
const& name, T
const& attribute) {
6432 ReusableStringStream rss;
6434 return writeAttribute(name, rss.str());
6437 XmlWriter& writeText(std::string
const& text,
6438 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6440 XmlWriter& writeComment(std::string
const& text,
6441 XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6443 void writeStylesheetRef(std::string
const& url);
6445 XmlWriter& writeBlankLine();
6447 void ensureTagClosed();
6450 void applyFormatting(XmlFormatting fmt);
6452 void writeDeclaration();
6454 void newlineIfNecessary();
6456 bool m_tagIsOpen =
false;
6457 bool m_needsNewline =
false;
6458 std::vector<std::string> m_tags;
6459 std::string m_indent;
6468class JunitReporter :
public CumulativeReporterBase<JunitReporter> {
6470 JunitReporter(ReporterConfig
const& _config);
6472 ~JunitReporter()
override;
6474 static std::string getDescription();
6476 void noMatchingTestCases(std::string
const& )
override;
6478 void testRunStarting(TestRunInfo
const& runInfo)
override;
6480 void testGroupStarting(GroupInfo
const& groupInfo)
override;
6482 void testCaseStarting(TestCaseInfo
const& testCaseInfo)
override;
6483 bool assertionEnded(AssertionStats
const& assertionStats)
override;
6485 void testCaseEnded(TestCaseStats
const& testCaseStats)
override;
6487 void testGroupEnded(TestGroupStats
const& testGroupStats)
override;
6489 void testRunEndedCumulative()
override;
6491 void writeGroup(TestGroupNode
const& groupNode,
double suiteTime);
6493 void writeTestCase(TestCaseNode
const& testCaseNode);
6495 void writeSection(std::string
const& className, std::string
const& rootName,
6496 SectionNode
const& sectionNode,
bool testOkToFail);
6498 void writeAssertions(SectionNode
const& sectionNode);
6499 void writeAssertion(AssertionStats
const& stats);
6503 std::string stdOutForSuite;
6504 std::string stdErrForSuite;
6505 unsigned int unexpectedExceptions = 0;
6506 bool m_okToFail =
false;
6515class XmlReporter :
public StreamingReporterBase<XmlReporter> {
6517 XmlReporter(ReporterConfig
const& _config);
6519 ~XmlReporter()
override;
6521 static std::string getDescription();
6523 virtual std::string getStylesheetRef()
const;
6525 void writeSourceInfo(SourceLineInfo
const& sourceInfo);
6528 void noMatchingTestCases(std::string
const& s)
override;
6530 void testRunStarting(TestRunInfo
const& testInfo)
override;
6532 void testGroupStarting(GroupInfo
const& groupInfo)
override;
6534 void testCaseStarting(TestCaseInfo
const& testInfo)
override;
6536 void sectionStarting(SectionInfo
const& sectionInfo)
override;
6538 void assertionStarting(AssertionInfo
const&)
override;
6540 bool assertionEnded(AssertionStats
const& assertionStats)
override;
6542 void sectionEnded(SectionStats
const& sectionStats)
override;
6544 void testCaseEnded(TestCaseStats
const& testCaseStats)
override;
6546 void testGroupEnded(TestGroupStats
const& testGroupStats)
override;
6548 void testRunEnded(TestRunStats
const& testRunStats)
override;
6550#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6551 void benchmarkPreparing(std::string
const& name)
override;
6552 void benchmarkStarting(BenchmarkInfo
const&)
override;
6553 void benchmarkEnded(BenchmarkStats<>
const&)
override;
6554 void benchmarkFailed(std::string
const&)
override;
6558 Timer m_testCaseTimer;
6560 int m_sectionDepth = 0;
6570#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6593namespace Benchmark {
6594template <
typename Clock>
using ClockDuration =
typename Clock::duration;
6595template <
typename Clock>
6596using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6598template <
typename Clock>
using TimePoint =
typename Clock::time_point;
6600using default_clock = std::chrono::steady_clock;
6602template <
typename Clock>
struct now {
6603 TimePoint<Clock> operator()()
const {
return Clock::now(); }
6606using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6615#if defined(_MSC_VER)
6620namespace Benchmark {
6621#if defined(__GNUC__) || defined(__clang__)
6622template <
typename T>
inline void keep_memory(T* p) {
6623 asm volatile(
"" : :
"g"(p) :
"memory");
6625inline void keep_memory() {
6626 asm volatile(
"" : : :
"memory");
6630inline void optimizer_barrier() {
6634#elif defined(_MSC_VER)
6636#pragma optimize("", off)
6637template <
typename T>
inline void keep_memory(T* p) {
6639 *
reinterpret_cast<char volatile*
>(p) = *
reinterpret_cast<char const volatile*
>(p);
6642#pragma optimize("", on)
6645inline void optimizer_barrier() {
6646 std::atomic_thread_fence(std::memory_order_seq_cst);
6652template <
typename T>
inline void deoptimize_value(T&& x) {
6656template <
typename Fn,
typename... Args>
6657inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
6658 typename std::enable_if<!std::is_same<void,
decltype(fn(args...))>::value>::type {
6659 deoptimize_value(std::forward<Fn>(fn)(std::forward<Args...>(args...)));
6662template <
typename Fn,
typename... Args>
6663inline auto invoke_deoptimized(Fn&& fn, Args&&... args) ->
6664 typename std::enable_if<std::is_same<void,
decltype(fn(args...))>::value>::type {
6665 std::forward<Fn>(fn)(std::forward<Args...>(args...));
6675#include <type_traits>
6679namespace Benchmark {
6681template <
typename T>
struct CompleteType {
6684template <>
struct CompleteType<void> {
6688template <
typename T>
using CompleteType_t =
typename CompleteType<T>::type;
6690template <
typename Result>
struct CompleteInvoker {
6691 template <
typename Fun,
typename... Args>
static Result invoke(Fun&& fun, Args&&... args) {
6692 return std::forward<Fun>(fun)(std::forward<Args>(args)...);
6695template <>
struct CompleteInvoker<void> {
6696 template <
typename Fun,
typename... Args>
6697 static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
6698 std::forward<Fun>(fun)(std::forward<Args>(args)...);
6704template <
typename Fun,
typename... Args>
6705CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
6706 return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun),
6707 std::forward<Args>(args)...);
6710const std::string benchmarkErrorMsg =
"a benchmark failed to run successfully";
6713template <
typename Fun> Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
6715 return Detail::complete_invoke(std::forward<Fun>(fun));
6718 getResultCapture().benchmarkFailed(translateActiveException());
6719 CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
6727namespace Benchmark {
6729struct ChronometerConcept {
6730 virtual void start() = 0;
6731 virtual void finish() = 0;
6732 virtual ~ChronometerConcept() =
default;
6734template <
typename Clock>
struct ChronometerModel final :
public ChronometerConcept {
6735 void start()
override { started = Clock::now(); }
6736 void finish()
override { finished = Clock::now(); }
6738 ClockDuration<Clock> elapsed()
const {
return finished - started; }
6740 TimePoint<Clock> started;
6741 TimePoint<Clock> finished;
6747 template <
typename Fun>
void measure(Fun&& fun) {
6748 measure(std::forward<Fun>(fun), is_callable<Fun(
int)>());
6751 int runs()
const {
return k; }
6753 Chronometer(Detail::ChronometerConcept& meter,
int k) : impl(&meter), k(k) {}
6756 template <
typename Fun>
void measure(Fun&& fun, std::false_type) {
6757 measure([&fun](
int) {
return fun(); }, std::true_type());
6760 template <
typename Fun>
void measure(Fun&& fun, std::true_type) {
6761 Detail::optimizer_barrier();
6763 for (
int i = 0; i < k; ++i)
6764 invoke_deoptimized(fun, i);
6766 Detail::optimizer_barrier();
6769 Detail::ChronometerConcept* impl;
6781namespace Benchmark {
6782template <
typename Duration>
struct EnvironmentEstimate {
6784 OutlierClassification outliers;
6786 template <
typename Duration2>
operator EnvironmentEstimate<Duration2>()
const {
6787 return {mean, outliers};
6790template <
typename Clock>
struct Environment {
6791 using clock_type = Clock;
6792 EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
6793 EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
6809#include <type_traits>
6813namespace Benchmark {
6815template <
typename T>
using Decay =
typename std::decay<T>::type;
6816template <
typename T,
typename U>
struct is_related : std::is_same<Decay<T>, Decay<U>> {};
6825struct BenchmarkFunction {
6828 virtual void call(Chronometer meter)
const = 0;
6829 virtual callable* clone()
const = 0;
6830 virtual ~callable() =
default;
6832 template <
typename Fun>
struct model :
public callable {
6833 model(Fun&& fun) : fun(std::move(fun)) {}
6834 model(Fun
const& fun) : fun(fun) {}
6836 model<Fun>* clone()
const override {
return new model<Fun>(*
this); }
6838 void call(Chronometer meter)
const override {
6839 call(meter, is_callable<Fun(Chronometer)>());
6841 void call(Chronometer meter, std::true_type)
const { fun(meter); }
6842 void call(Chronometer meter, std::false_type)
const { meter.measure(fun); }
6848 void operator()()
const {}
6851 template <
typename T> BenchmarkFunction(model<T>* c) : f(c) {}
6854 BenchmarkFunction() : f(new model<do_nothing>{{}}) {}
6856 template <
typename Fun,
6857 typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value,
int>::type = 0>
6858 BenchmarkFunction(Fun&& fun)
6859 : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
6861 BenchmarkFunction(BenchmarkFunction&& that) : f(std::move(that.f)) {}
6863 BenchmarkFunction(BenchmarkFunction
const& that) : f(that.f->clone()) {}
6865 BenchmarkFunction& operator=(BenchmarkFunction&& that) {
6866 f = std::move(that.f);
6870 BenchmarkFunction& operator=(BenchmarkFunction
const& that) {
6871 f.reset(that.f->clone());
6875 void operator()(Chronometer meter)
const { f->call(meter); }
6878 std::unique_ptr<callable> f;
6889#include <type_traits>
6893namespace Benchmark {
6895template <
typename Fun>
struct repeater {
6896 void operator()(
int k)
const {
6897 for (
int i = 0; i < k; ++i) {
6903template <
typename Fun> repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
6904 return {std::forward<Fun>(fun)};
6924#include <type_traits>
6927namespace Benchmark {
6928template <
typename Duration,
typename Result>
struct Timing {
6933template <
typename Clock,
typename Func,
typename... Args>
6935 Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
6943namespace Benchmark {
6945template <
typename Clock,
typename Fun,
typename... Args>
6946TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
6947 auto start = Clock::now();
6948 auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
6949 auto end = Clock::now();
6950 auto delta = end - start;
6951 return {delta, std::forward<decltype(r)>(r), 1};
6958#include <type_traits>
6962namespace Benchmark {
6964template <
typename Clock,
typename Fun>
6965TimingOf<Clock, Fun, int> measure_one(Fun&& fun,
int iters, std::false_type) {
6966 return Detail::measure<Clock>(fun, iters);
6968template <
typename Clock,
typename Fun>
6969TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun,
int iters, std::true_type) {
6970 Detail::ChronometerModel<Clock> meter;
6971 auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
6973 return {meter.elapsed(), std::move(result), iters};
6976template <
typename Clock,
typename Fun>
6977using run_for_at_least_argument_t =
6978 typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer,
int>::type;
6980struct optimized_away_error : std::exception {
6981 const char* what() const noexcept
override {
6982 return "could not measure benchmark, maybe it was optimized away";
6986template <
typename Clock,
typename Fun>
6987TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>>
6988run_for_at_least(ClockDuration<Clock> how_long,
int seed, Fun&& fun) {
6990 while (iters < (1 << 30)) {
6991 auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
6993 if (Timing.elapsed >= how_long) {
6994 return {Timing.elapsed, std::move(Timing.result), iters};
6998 Catch::throw_exception(optimized_away_error{});
7009namespace Benchmark {
7010template <
typename Duration>
struct ExecutionPlan {
7011 int iterations_per_sample;
7012 Duration estimated_duration;
7013 Detail::BenchmarkFunction benchmark;
7014 Duration warmup_time;
7015 int warmup_iterations;
7017 template <
typename Duration2>
operator ExecutionPlan<Duration2>()
const {
7018 return {iterations_per_sample, estimated_duration, benchmark, warmup_time,
7022 template <
typename Clock>
7023 std::vector<FloatDuration<Clock>> run(
const IConfig& cfg,
7024 Environment<FloatDuration<Clock>> env)
const {
7026 Detail::run_for_at_least<Clock>(
7027 std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations,
7028 Detail::repeat(now<Clock>{}));
7030 std::vector<FloatDuration<Clock>> times;
7031 times.reserve(cfg.benchmarkSamples());
7032 std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [
this, env] {
7033 Detail::ChronometerModel<Clock> model;
7034 this->benchmark(Chronometer(model, iterations_per_sample));
7035 auto sample_time = model.elapsed() - env.clock_cost.mean;
7036 if (sample_time < FloatDuration<Clock>::zero())
7037 sample_time = FloatDuration<Clock>::zero();
7038 return sample_time / iterations_per_sample;
7058#include <functional>
7067namespace Benchmark {
7069using sample = std::vector<double>;
7071double weighted_average_quantile(
int k,
int q, std::vector<double>::iterator first,
7072 std::vector<double>::iterator last);
7074template <
typename Iterator>
7075OutlierClassification classify_outliers(Iterator first, Iterator last) {
7076 std::vector<double> copy(first, last);
7078 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
7079 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
7081 auto los = q1 - (iqr * 3.);
7082 auto lom = q1 - (iqr * 1.5);
7083 auto him = q3 + (iqr * 1.5);
7084 auto his = q3 + (iqr * 3.);
7086 OutlierClassification o;
7087 for (; first != last; ++first) {
7102template <
typename Iterator>
double mean(Iterator first, Iterator last) {
7103 auto count = last - first;
7104 double sum = std::accumulate(first, last, 0.);
7108template <
typename URng,
typename Iterator,
typename Estimator>
7109sample resample(URng& rng,
int resamples, Iterator first, Iterator last, Estimator& estimator) {
7110 auto n = last - first;
7111 std::uniform_int_distribution<
decltype(n)> dist(0, n - 1);
7114 out.reserve(resamples);
7115 std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
7116 std::vector<double> resampled;
7117 resampled.reserve(n);
7118 std::generate_n(std::back_inserter(resampled), n,
7119 [first, &dist, &rng] {
return first[dist(rng)]; });
7120 return estimator(resampled.begin(), resampled.end());
7122 std::sort(out.begin(), out.end());
7126template <
typename Estimator,
typename Iterator>
7127sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
7128 auto n = last - first;
7129 auto second = std::next(first);
7133 for (
auto it = first; it != last; ++it) {
7134 std::iter_swap(it, first);
7135 results.push_back(estimator(second, last));
7141inline double normal_cdf(
double x) {
7142 return std::erfc(-x / std::sqrt(2.0)) / 2.0;
7145double erfc_inv(
double x);
7147double normal_quantile(
double p);
7149template <
typename Iterator,
typename Estimator>
7150Estimate<double> bootstrap(
double confidence_level, Iterator first, Iterator last,
7151 sample
const& resample, Estimator&& estimator) {
7152 auto n_samples = last - first;
7154 double point = estimator(first, last);
7157 return {point, point, point, confidence_level};
7159 sample jack = jackknife(estimator, first, last);
7160 double jack_mean = mean(jack.begin(), jack.end());
7161 double sum_squares, sum_cubes;
7162 std::tie(sum_squares, sum_cubes) = std::accumulate(
7163 jack.begin(), jack.end(), std::make_pair(0., 0.),
7164 [jack_mean](std::pair<double, double> sqcb,
double x) -> std::pair<double, double> {
7165 auto d = jack_mean - x;
7168 return {sqcb.first + d2, sqcb.second + d3};
7171 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
7172 int n =
static_cast<int>(resample.size());
7174 std::count_if(resample.begin(), resample.end(), [point](
double x) { return x < point; }) /
7178 return {point, point, point, confidence_level};
7180 double bias = normal_quantile(prob_n);
7181 double z1 = normal_quantile((1. - confidence_level) / 2.);
7183 auto cumn = [n](
double x) ->
int {
return std::lround(normal_cdf(x) * n); };
7184 auto a = [bias, accel](
double b) {
return bias + b / (1. - accel * b); };
7185 double b1 = bias + z1;
7186 double b2 = bias - z1;
7189 auto lo = (std::max)(cumn(a1), 0);
7190 auto hi = (std::min)(cumn(a2), n - 1);
7192 return {point, resample[lo], resample[hi], confidence_level};
7195double outlier_variance(Estimate<double> mean, Estimate<double> stddev,
int n);
7197struct bootstrap_analysis {
7198 Estimate<double> mean;
7199 Estimate<double> standard_deviation;
7200 double outlier_variance;
7203bootstrap_analysis analyse_samples(
double confidence_level,
int n_resamples,
7204 std::vector<double>::iterator first,
7205 std::vector<double>::iterator last);
7218namespace Benchmark {
7220template <
typename Clock> std::vector<double> resolution(
int k) {
7221 std::vector<TimePoint<Clock>> times;
7222 times.reserve(k + 1);
7223 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
7225 std::vector<double> deltas;
7227 std::transform(std::next(times.begin()), times.end(), times.begin(), std::back_inserter(deltas),
7228 [](TimePoint<Clock> a, TimePoint<Clock> b) {
7229 return static_cast<double>((a - b).count());
7235const auto warmup_iterations = 10000;
7236const auto warmup_time = std::chrono::milliseconds(100);
7237const auto minimum_ticks = 1000;
7238const auto warmup_seed = 10000;
7239const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
7240const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
7241const auto clock_cost_estimation_tick_limit = 100000;
7242const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
7243const auto clock_cost_estimation_iterations = 10000;
7245template <
typename Clock>
int warmup() {
7246 return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time),
7247 warmup_seed, &resolution<Clock>)
7250template <
typename Clock>
7251EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(
int iterations) {
7252 auto r = run_for_at_least<Clock>(
7253 std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time),
7254 iterations, &resolution<Clock>)
7257 FloatDuration<Clock>(mean(r.begin(), r.end())),
7258 classify_outliers(r.begin(), r.end()),
7261template <
typename Clock>
7262EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
7263 auto time_limit = (std::min)(resolution * clock_cost_estimation_tick_limit,
7264 FloatDuration<Clock>(clock_cost_estimation_time_limit));
7265 auto time_clock = [](
int k) {
7266 return Detail::measure<Clock>([k] {
7267 for (
int i = 0; i < k; ++i) {
7268 volatile auto ignored = Clock::now();
7275 int iters = clock_cost_estimation_iterations;
7276 auto&& r = run_for_at_least<Clock>(
7277 std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters,
7279 std::vector<double> times;
7280 int nsamples =
static_cast<int>(std::ceil(time_limit / r.elapsed));
7281 times.reserve(nsamples);
7282 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
7283 return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
7286 FloatDuration<Clock>(mean(times.begin(), times.end())),
7287 classify_outliers(times.begin(), times.end()),
7291template <
typename Clock> Environment<FloatDuration<Clock>> measure_environment() {
7292 static Environment<FloatDuration<Clock>>* env =
nullptr;
7297 auto iters = Detail::warmup<Clock>();
7298 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
7299 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
7301 env =
new Environment<FloatDuration<Clock>>{resolution, cost};
7323namespace Benchmark {
7324template <
typename Duration>
struct SampleAnalysis {
7325 std::vector<Duration> samples;
7326 Estimate<Duration> mean;
7327 Estimate<Duration> standard_deviation;
7328 OutlierClassification outliers;
7329 double outlier_variance;
7331 template <
typename Duration2>
operator SampleAnalysis<Duration2>()
const {
7332 std::vector<Duration2> samples2;
7333 samples2.reserve(samples.size());
7334 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2),
7335 [](Duration d) { return Duration2(d); });
7337 std::move(samples2), mean, standard_deviation, outliers, outlier_variance,
7350namespace Benchmark {
7352template <
typename Duration,
typename Iterator>
7353SampleAnalysis<Duration> analyse(
const IConfig& cfg, Environment<Duration>, Iterator first,
7355 if (!cfg.benchmarkNoAnalysis()) {
7356 std::vector<double> samples;
7357 samples.reserve(last - first);
7358 std::transform(first, last, std::back_inserter(samples),
7359 [](Duration d) {
return d.count(); });
7361 auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(),
7362 cfg.benchmarkResamples(),
7363 samples.begin(), samples.end());
7364 auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7366 auto wrap_estimate = [](Estimate<double> e) {
7367 return Estimate<Duration>{
7369 Duration(e.lower_bound),
7370 Duration(e.upper_bound),
7371 e.confidence_interval,
7374 std::vector<Duration> samples2;
7375 samples2.reserve(samples.size());
7376 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2),
7377 [](
double d) { return Duration(d); });
7379 std::move(samples2),
7380 wrap_estimate(analysis.mean),
7381 wrap_estimate(analysis.standard_deviation),
7383 analysis.outlier_variance,
7386 std::vector<Duration> samples;
7387 samples.reserve(last - first);
7389 Duration mean = Duration(0);
7391 for (
auto it = first; it < last; ++it, ++i) {
7392 samples.push_back(Duration(*it));
7393 mean += Duration(*it);
7397 return {std::move(samples), Estimate<Duration>{mean, mean, mean, 0.0},
7398 Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
7399 OutlierClassification{}, 0.0};
7409#include <functional>
7414namespace Benchmark {
7416 Benchmark(std::string&& name) : name(std::move(name)) {}
7418 template <
class FUN>
7419 Benchmark(std::string&& name, FUN&& func) : fun(std::move(func)), name(std::move(name)) {}
7421 template <
typename Clock>
7422 ExecutionPlan<FloatDuration<Clock>> prepare(
const IConfig& cfg,
7423 Environment<FloatDuration<Clock>> env)
const {
7424 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7425 auto run_time = std::max(
7426 min_time, std::chrono::duration_cast<
decltype(min_time)>(cfg.benchmarkWarmupTime()));
7427 auto&& test = Detail::run_for_at_least<Clock>(
7428 std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7429 int new_iters =
static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
7430 return {new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun,
7431 std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()),
7432 Detail::warmup_iterations};
7435 template <
typename Clock = default_clock>
void run() {
7436 IConfigPtr cfg = getCurrentContext().getConfig();
7438 auto env = Detail::measure_environment<Clock>();
7440 getResultCapture().benchmarkPreparing(name);
7442 auto plan = user_code([&] {
return prepare<Clock>(*cfg, env); });
7444 BenchmarkInfo info{name,
7445 plan.estimated_duration.count(),
7446 plan.iterations_per_sample,
7447 cfg->benchmarkSamples(),
7448 cfg->benchmarkResamples(),
7449 env.clock_resolution.mean.count(),
7450 env.clock_cost.mean.count()};
7452 getResultCapture().benchmarkStarting(info);
7454 auto samples = user_code([&] {
return plan.template run<Clock>(*cfg, env); });
7456 auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
7457 BenchmarkStats<FloatDuration<Clock>> stats{info,
7460 analysis.standard_deviation,
7462 analysis.outlier_variance};
7463 getResultCapture().benchmarkEnded(stats);
7466 if (translateActiveException() !=
7467 Detail::benchmarkErrorMsg)
7469 std::rethrow_exception(std::current_exception());
7474 template <
typename Fun,
7475 typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value,
int>::type = 0>
7476 Benchmark& operator=(Fun func) {
7477 fun = Detail::BenchmarkFunction(func);
7482 explicit operator bool() {
return true; }
7485 Detail::BenchmarkFunction fun;
7491#define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
7492#define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
7494#define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex) \
7495 if (Catch::Benchmark::Benchmark BenchmarkName{name}) \
7496 BenchmarkName = [&](int benchmarkIndex)
7498#define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name) \
7499 if (Catch::Benchmark::Benchmark BenchmarkName{name}) \
7507#include <type_traits>
7510namespace Benchmark {
7512template <
typename T,
bool Destruct>
struct ObjectStorage {
7513 using TStorage =
typename std::aligned_storage<
sizeof(T), std::alignment_of<T>::value>::type;
7515 ObjectStorage() : data() {}
7517 ObjectStorage(
const ObjectStorage& other) {
new (&data) T(other.stored_object()); }
7519 ObjectStorage(ObjectStorage&& other) {
new (&data) T(std::move(other.stored_object())); }
7521 ~ObjectStorage() { destruct_on_exit<T>(); }
7523 template <
typename... Args>
void construct(Args&&... args) {
7524 new (&data) T(std::forward<Args>(args)...);
7527 template <
bool AllowManualDestruction = !Destruct>
7528 typename std::enable_if<AllowManualDestruction>::type destruct() {
7529 stored_object().~T();
7534 template <
typename U>
void destruct_on_exit(
typename std::enable_if<Destruct, U>::type* = 0) {
7538 template <
typename U>
void destruct_on_exit(
typename std::enable_if<!Destruct, U>::type* = 0) {}
7540 T& stored_object() {
return *
static_cast<T*
>(
static_cast<void*
>(&data)); }
7542 T
const& stored_object()
const {
return *
static_cast<T*
>(
static_cast<void*
>(&data)); }
7548template <
typename T>
using storage_for = Detail::ObjectStorage<T, true>;
7550template <
typename T>
using destructable_object = Detail::ObjectStorage<T, false>;
7564#pragma clang diagnostic push
7565#pragma clang diagnostic ignored "-Wweak-vtables"
7576namespace TestCaseTracking {
7578struct NameAndLocation {
7580 SourceLineInfo location;
7582 NameAndLocation(std::string
const& _name, SourceLineInfo
const& _location);
7583 friend bool operator==(NameAndLocation
const& lhs, NameAndLocation
const& rhs) {
7584 return lhs.name == rhs.name && lhs.location == rhs.location;
7590using ITrackerPtr = std::shared_ptr<ITracker>;
7593 NameAndLocation m_nameAndLocation;
7596 ITracker(NameAndLocation
const& nameAndLoc) : m_nameAndLocation(nameAndLoc) {}
7599 NameAndLocation
const& nameAndLocation()
const {
return m_nameAndLocation; }
7601 virtual ~ITracker();
7604 virtual bool isComplete()
const = 0;
7605 virtual bool isSuccessfullyCompleted()
const = 0;
7606 virtual bool isOpen()
const = 0;
7607 virtual bool hasChildren()
const = 0;
7608 virtual bool hasStarted()
const = 0;
7610 virtual ITracker& parent() = 0;
7613 virtual void close() = 0;
7614 virtual void fail() = 0;
7615 virtual void markAsNeedingAnotherRun() = 0;
7617 virtual void addChild(ITrackerPtr
const& child) = 0;
7618 virtual ITrackerPtr findChild(NameAndLocation
const& nameAndLocation) = 0;
7619 virtual void openChild() = 0;
7622 virtual bool isSectionTracker()
const = 0;
7623 virtual bool isGeneratorTracker()
const = 0;
7626class TrackerContext {
7628 enum RunState { NotStarted, Executing, CompletedCycle };
7630 ITrackerPtr m_rootTracker;
7631 ITracker* m_currentTracker =
nullptr;
7632 RunState m_runState = NotStarted;
7635 ITracker& startRun();
7639 void completeCycle();
7641 bool completedCycle()
const;
7642 ITracker& currentTracker();
7643 void setCurrentTracker(ITracker* tracker);
7646class TrackerBase :
public ITracker {
7653 CompletedSuccessfully,
7657 using Children = std::vector<ITrackerPtr>;
7658 TrackerContext& m_ctx;
7660 Children m_children;
7661 CycleState m_runState = NotStarted;
7664 TrackerBase(NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent);
7666 bool isComplete()
const override;
7667 bool isSuccessfullyCompleted()
const override;
7668 bool isOpen()
const override;
7669 bool hasChildren()
const override;
7670 bool hasStarted()
const override {
return m_runState != NotStarted; }
7672 void addChild(ITrackerPtr
const& child)
override;
7674 ITrackerPtr findChild(NameAndLocation
const& nameAndLocation)
override;
7675 ITracker& parent()
override;
7677 void openChild()
override;
7679 bool isSectionTracker()
const override;
7680 bool isGeneratorTracker()
const override;
7684 void close()
override;
7685 void fail()
override;
7686 void markAsNeedingAnotherRun()
override;
7689 void moveToParent();
7693class SectionTracker :
public TrackerBase {
7694 std::vector<std::string> m_filters;
7695 std::string m_trimmed_name;
7698 SectionTracker(NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent);
7700 bool isSectionTracker()
const override;
7702 bool isComplete()
const override;
7704 static SectionTracker& acquire(TrackerContext& ctx, NameAndLocation
const& nameAndLocation);
7708 void addInitialFilters(std::vector<std::string>
const& filters);
7709 void addNextFilters(std::vector<std::string>
const& filters);
7711 std::vector<std::string>
const& getFilters()
const;
7713 std::string
const& trimmedName()
const;
7718using TestCaseTracking::ITracker;
7719using TestCaseTracking::SectionTracker;
7720using TestCaseTracking::TrackerContext;
7730struct LeakDetector {
7742#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
7747#if defined(CATCH_CONFIG_USE_ASYNC)
7752double erf_inv(
double x) {
7757 w = -log((1.0 - x) * (1.0 + x));
7761 p = -3.6444120640178196996e-21;
7762 p = -1.685059138182016589e-19 + p * w;
7763 p = 1.2858480715256400167e-18 + p * w;
7764 p = 1.115787767802518096e-17 + p * w;
7765 p = -1.333171662854620906e-16 + p * w;
7766 p = 2.0972767875968561637e-17 + p * w;
7767 p = 6.6376381343583238325e-15 + p * w;
7768 p = -4.0545662729752068639e-14 + p * w;
7769 p = -8.1519341976054721522e-14 + p * w;
7770 p = 2.6335093153082322977e-12 + p * w;
7771 p = -1.2975133253453532498e-11 + p * w;
7772 p = -5.4154120542946279317e-11 + p * w;
7773 p = 1.051212273321532285e-09 + p * w;
7774 p = -4.1126339803469836976e-09 + p * w;
7775 p = -2.9070369957882005086e-08 + p * w;
7776 p = 4.2347877827932403518e-07 + p * w;
7777 p = -1.3654692000834678645e-06 + p * w;
7778 p = -1.3882523362786468719e-05 + p * w;
7779 p = 0.0001867342080340571352 + p * w;
7780 p = -0.00074070253416626697512 + p * w;
7781 p = -0.0060336708714301490533 + p * w;
7782 p = 0.24015818242558961693 + p * w;
7783 p = 1.6536545626831027356 + p * w;
7784 }
else if (w < 16.000000) {
7785 w = sqrt(w) - 3.250000;
7786 p = 2.2137376921775787049e-09;
7787 p = 9.0756561938885390979e-08 + p * w;
7788 p = -2.7517406297064545428e-07 + p * w;
7789 p = 1.8239629214389227755e-08 + p * w;
7790 p = 1.5027403968909827627e-06 + p * w;
7791 p = -4.013867526981545969e-06 + p * w;
7792 p = 2.9234449089955446044e-06 + p * w;
7793 p = 1.2475304481671778723e-05 + p * w;
7794 p = -4.7318229009055733981e-05 + p * w;
7795 p = 6.8284851459573175448e-05 + p * w;
7796 p = 2.4031110387097893999e-05 + p * w;
7797 p = -0.0003550375203628474796 + p * w;
7798 p = 0.00095328937973738049703 + p * w;
7799 p = -0.0016882755560235047313 + p * w;
7800 p = 0.0024914420961078508066 + p * w;
7801 p = -0.0037512085075692412107 + p * w;
7802 p = 0.005370914553590063617 + p * w;
7803 p = 1.0052589676941592334 + p * w;
7804 p = 3.0838856104922207635 + p * w;
7806 w = sqrt(w) - 5.000000;
7807 p = -2.7109920616438573243e-11;
7808 p = -2.5556418169965252055e-10 + p * w;
7809 p = 1.5076572693500548083e-09 + p * w;
7810 p = -3.7894654401267369937e-09 + p * w;
7811 p = 7.6157012080783393804e-09 + p * w;
7812 p = -1.4960026627149240478e-08 + p * w;
7813 p = 2.9147953450901080826e-08 + p * w;
7814 p = -6.7711997758452339498e-08 + p * w;
7815 p = 2.2900482228026654717e-07 + p * w;
7816 p = -9.9298272942317002539e-07 + p * w;
7817 p = 4.5260625972231537039e-06 + p * w;
7818 p = -1.9681778105531670567e-05 + p * w;
7819 p = 7.5995277030017761139e-05 + p * w;
7820 p = -0.00021503011930044477347 + p * w;
7821 p = -0.00013871931833623122026 + p * w;
7822 p = 1.0103004648645343977 + p * w;
7823 p = 4.8499064014085844221 + p * w;
7828double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
7829 auto m = Catch::Benchmark::Detail::mean(first, last);
7830 double variance = std::accumulate(first, last, 0.,
7831 [m](
double a,
double b) {
7832 double diff = b - m;
7833 return a + diff * diff;
7836 return std::sqrt(variance);
7842namespace Benchmark {
7845double weighted_average_quantile(
int k,
int q, std::vector<double>::iterator first,
7846 std::vector<double>::iterator last) {
7847 auto count = last - first;
7848 double idx = (count - 1) * k / static_cast<double>(q);
7849 int j =
static_cast<int>(idx);
7851 std::nth_element(first, first + j, last);
7856 auto xj1 = *std::min_element(first + (j + 1), last);
7857 return xj + g * (xj1 - xj);
7860double erfc_inv(
double x) {
7861 return erf_inv(1.0 - x);
7864double normal_quantile(
double p) {
7865 static const double ROOT_TWO = std::sqrt(2.0);
7867 double result = 0.0;
7868 assert(p >= 0 && p <= 1);
7869 if (p < 0 || p > 1) {
7873 result = -erfc_inv(2.0 * p);
7880double outlier_variance(Estimate<double> mean, Estimate<double> stddev,
int n) {
7881 double sb = stddev.point;
7882 double mn = mean.point / n;
7883 double mg_min = mn / 2.;
7884 double sg = (std::min)(mg_min / 4., sb / std::sqrt(n));
7885 double sg2 = sg * sg;
7886 double sb2 = sb * sb;
7888 auto c_max = [n, mn, sb2, sg2](
double x) ->
double {
7892 double k0 = -n * nd;
7893 double k1 = sb2 - n * sg2 + nd;
7894 double det = k1 * k1 - 4 * sg2 * k0;
7895 return (
int)(-2. * k0 / (k1 + std::sqrt(det)));
7898 auto var_out = [n, sb2, sg2](
double c) {
7900 return (nc / n) * (sb2 - nc * sg2);
7903 return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
7906bootstrap_analysis analyse_samples(
double confidence_level,
int n_resamples,
7907 std::vector<double>::iterator first,
7908 std::vector<double>::iterator last) {
7909 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
7910 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
7911 static std::random_device entropy;
7912 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
7914 auto n =
static_cast<int>(last -
7917 auto mean = &Detail::mean<std::vector<double>::iterator>;
7918 auto stddev = &standard_deviation;
7920#if defined(CATCH_CONFIG_USE_ASYNC)
7921 auto Estimate = [=](double (*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7922 auto seed = entropy();
7923 return std::async(std::launch::async, [=] {
7924 std::mt19937 rng(seed);
7925 auto resampled = resample(rng, n_resamples, first, last, f);
7926 return bootstrap(confidence_level, first, last, resampled, f);
7930 auto mean_future = Estimate(mean);
7931 auto stddev_future = Estimate(stddev);
7933 auto mean_estimate = mean_future.get();
7934 auto stddev_estimate = stddev_future.get();
7936 auto Estimate = [=](double (*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7937 auto seed = entropy();
7938 std::mt19937 rng(seed);
7939 auto resampled = resample(rng, n_resamples, first, last, f);
7940 return bootstrap(confidence_level, first, last, resampled, f);
7943 auto mean_estimate = Estimate(mean);
7944 auto stddev_estimate = Estimate(stddev);
7947 double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
7949 return {mean_estimate, stddev_estimate, outlier_variance};
7966bool marginComparison(
double lhs,
double rhs,
double margin) {
7967 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
7975Approx::Approx(
double value)
7976 : m_epsilon(std::numeric_limits<float>::epsilon() * 100), m_margin(0.0), m_scale(0.0),
7979Approx Approx::custom() {
7983Approx Approx::operator-()
const {
7985 temp.m_value = -temp.m_value;
7989std::string Approx::toString()
const {
7991 rss <<
"Approx( " << ::Catch::Detail::stringify(m_value) <<
" )";
7995bool Approx::equalityComparisonImpl(
const double other)
const {
7999 return marginComparison(m_value, other, m_margin) ||
8000 marginComparison(m_value, other,
8001 m_epsilon * (m_scale + std::fabs(std::isinf(m_value) ? 0 : m_value)));
8004void Approx::setMargin(
double newMargin) {
8005 CATCH_ENFORCE(newMargin >= 0,
8006 "Invalid Approx::margin: " << newMargin <<
'.'
8007 <<
" Approx::Margin has to be non-negative.");
8008 m_margin = newMargin;
8011void Approx::setEpsilon(
double newEpsilon) {
8012 CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
8013 "Invalid Approx::epsilon: " << newEpsilon <<
'.'
8014 <<
" Approx::epsilon has to be in [0, 1]");
8015 m_epsilon = newEpsilon;
8021Detail::Approx
operator"" _a(
long double val) {
8022 return Detail::Approx(val);
8024Detail::Approx
operator"" _a(
unsigned long long val) {
8025 return Detail::Approx(val);
8030 return value.toString();
8040bool isDebuggerActive();
8043#ifdef CATCH_PLATFORM_MAC
8045#if defined(__i386__) || defined(__x86_64__)
8046#define CATCH_TRAP() __asm__("int $3\n" : :)
8047#elif defined(__aarch64__)
8048#define CATCH_TRAP() __asm__(".inst 0xd4200000")
8051#elif defined(CATCH_PLATFORM_IPHONE)
8054#if defined(__i386__) || defined(__x86_64__)
8055#define CATCH_TRAP() __asm__("int $3")
8056#elif defined(__aarch64__)
8057#define CATCH_TRAP() __asm__(".inst 0xd4200000")
8058#elif defined(__arm__) && !defined(__thumb__)
8059#define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
8060#elif defined(__arm__) && defined(__thumb__)
8061#define CATCH_TRAP() __asm__(".inst 0xde01")
8064#elif defined(CATCH_PLATFORM_LINUX)
8068#if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
8069#define CATCH_TRAP() asm volatile("int $3")
8073#define CATCH_TRAP() raise(SIGTRAP)
8075#elif defined(_MSC_VER)
8076#define CATCH_TRAP() __debugbreak()
8077#elif defined(__MINGW32__)
8078extern "C" __declspec(dllimport)
void __stdcall DebugBreak();
8079#define CATCH_TRAP() DebugBreak()
8082#ifndef CATCH_BREAK_INTO_DEBUGGER
8084#define CATCH_BREAK_INTO_DEBUGGER() \
8086 if (Catch::isDebuggerActive()) { \
8091#define CATCH_BREAK_INTO_DEBUGGER() [] {}()
8112class FatalConditionHandler {
8113 bool m_started =
false;
8118 void engage_platform();
8119 void disengage_platform();
8123 FatalConditionHandler();
8124 ~FatalConditionHandler();
8127 assert(!m_started &&
"Handler cannot be installed twice.");
8133 assert(m_started &&
"Handler cannot be uninstalled without being installed first");
8135 disengage_platform();
8140class FatalConditionHandlerGuard {
8141 FatalConditionHandler* m_handler;
8144 FatalConditionHandlerGuard(FatalConditionHandler* handler) : m_handler(handler) {
8145 m_handler->engage();
8147 ~FatalConditionHandlerGuard() { m_handler->disengage(); }
8164 RunContext(RunContext
const&) =
delete;
8165 RunContext& operator=(RunContext
const&) =
delete;
8167 explicit RunContext(IConfigPtr
const& _config, IStreamingReporterPtr&& reporter);
8169 ~RunContext()
override;
8171 void testGroupStarting(std::string
const& testSpec, std::size_t groupIndex,
8172 std::size_t groupsCount);
8173 void testGroupEnded(std::string
const& testSpec, Totals
const& totals, std::size_t groupIndex,
8174 std::size_t groupsCount);
8176 Totals runTest(TestCase
const& testCase);
8178 IConfigPtr config()
const;
8179 IStreamingReporter& reporter()
const;
8183 void handleExpr(AssertionInfo
const& info, ITransientExpression
const& expr,
8184 AssertionReaction& reaction)
override;
8185 void handleMessage(AssertionInfo
const& info, ResultWas::OfType resultType,
8186 StringRef
const& message, AssertionReaction& reaction)
override;
8187 void handleUnexpectedExceptionNotThrown(AssertionInfo
const& info,
8188 AssertionReaction& reaction)
override;
8189 void handleUnexpectedInflightException(AssertionInfo
const& info, std::string
const& message,
8190 AssertionReaction& reaction)
override;
8191 void handleIncomplete(AssertionInfo
const& info)
override;
8192 void handleNonExpr(AssertionInfo
const& info, ResultWas::OfType resultType,
8193 AssertionReaction& reaction)
override;
8195 bool sectionStarted(SectionInfo
const& sectionInfo, Counts& assertions)
override;
8197 void sectionEnded(SectionEndInfo
const& endInfo)
override;
8198 void sectionEndedEarly(SectionEndInfo
const& endInfo)
override;
8200 auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo
const& lineInfo)
8201 -> IGeneratorTracker&
override;
8203#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
8204 void benchmarkPreparing(std::string
const& name)
override;
8205 void benchmarkStarting(BenchmarkInfo
const& info)
override;
8206 void benchmarkEnded(BenchmarkStats<>
const& stats)
override;
8207 void benchmarkFailed(std::string
const& error)
override;
8210 void pushScopedMessage(MessageInfo
const& message)
override;
8211 void popScopedMessage(MessageInfo
const& message)
override;
8213 void emplaceUnscopedMessage(MessageBuilder
const& builder)
override;
8215 std::string getCurrentTestName()
const override;
8217 const AssertionResult* getLastResult()
const override;
8219 void exceptionEarlyReported()
override;
8221 void handleFatalErrorCondition(StringRef message)
override;
8223 bool lastAssertionPassed()
override;
8225 void assertionPassed()
override;
8229 bool aborting() const final;
8232 void runCurrentTest(std::
string& redirectedCout, std::
string& redirectedCerr);
8233 void invokeActiveTestCase();
8235 void resetAssertionInfo();
8236 bool testForMissingAssertions(Counts& assertions);
8238 void assertionEnded(AssertionResult const& result);
8239 void reportExpr(AssertionInfo const& info, ResultWas::OfType resultType,
8240 ITransientExpression const* expr,
bool negated);
8242 void populateReaction(AssertionReaction& reaction);
8245 void handleUnfinishedSections();
8247 TestRunInfo m_runInfo;
8248 IMutableContext& m_context;
8249 TestCase const* m_activeTestCase =
nullptr;
8250 ITracker* m_testCaseTracker =
nullptr;
8251 Option<AssertionResult> m_lastResult;
8253 IConfigPtr m_config;
8255 IStreamingReporterPtr m_reporter;
8256 std::vector<MessageInfo> m_messages;
8257 std::vector<ScopedMessage> m_messageScopes;
8258 AssertionInfo m_lastAssertionInfo;
8259 std::vector<SectionEndInfo> m_unfinishedSections;
8260 std::vector<ITracker*> m_activeSections;
8261 TrackerContext m_trackerContext;
8262 FatalConditionHandler m_fatalConditionhandler;
8263 bool m_lastAssertionPassed = false;
8264 bool m_shouldReportUnexpected = true;
8265 bool m_includeSuccessfulResults;
8268void seedRng(IConfig const& config);
8269unsigned int rngSeed();
8276auto operator<<(std::ostream& os, ITransientExpression
const& expr) -> std::ostream& {
8277 expr.streamReconstructedExpression(os);
8282LazyExpression::LazyExpression(
bool isNegated) : m_isNegated(isNegated) {}
8284LazyExpression::LazyExpression(
LazyExpression const& other) : m_isNegated(other.m_isNegated) {}
8286LazyExpression::operator bool()
const {
8287 return m_transientExpression !=
nullptr;
8290auto operator<<(std::ostream& os,
LazyExpression const& lazyExpr) -> std::ostream& {
8291 if (lazyExpr.m_isNegated)
8295 if (lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression())
8296 os <<
"(" << *lazyExpr.m_transientExpression <<
")";
8298 os << *lazyExpr.m_transientExpression;
8300 os <<
"{** error - unchecked empty expression requested **}";
8307 ResultDisposition::Flags resultDisposition)
8308 : m_assertionInfo{macroName, lineInfo, capturedExpression, resultDisposition},
8309 m_resultCapture(getResultCapture()) {}
8312 m_resultCapture.handleExpr(m_assertionInfo, expr, m_reaction);
8314void AssertionHandler::handleMessage(ResultWas::OfType resultType,
StringRef const& message) {
8315 m_resultCapture.handleMessage(m_assertionInfo, resultType, message, m_reaction);
8318auto AssertionHandler::allowThrows() const ->
bool {
8319 return getCurrentContext().getConfig()->allowThrows();
8322void AssertionHandler::complete() {
8324 if (m_reaction.shouldDebugBreak) {
8330 CATCH_BREAK_INTO_DEBUGGER();
8332 if (m_reaction.shouldThrow) {
8333#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
8334 throw Catch::TestFailureException();
8336 CATCH_ERROR(
"Test failure requires aborting test!");
8340void AssertionHandler::setCompleted() {
8344void AssertionHandler::handleUnexpectedInflightException() {
8345 m_resultCapture.handleUnexpectedInflightException(
8346 m_assertionInfo, Catch::translateActiveException(), m_reaction);
8349void AssertionHandler::handleExceptionThrownAsExpected() {
8350 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8352void AssertionHandler::handleExceptionNotThrownAsExpected() {
8353 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8356void AssertionHandler::handleUnexpectedExceptionNotThrown() {
8357 m_resultCapture.handleUnexpectedExceptionNotThrown(m_assertionInfo, m_reaction);
8360void AssertionHandler::handleThrowingCallSkipped() {
8361 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8367void handleExceptionMatchExpr(
AssertionHandler& handler, std::string
const& str,
8369 handleExceptionMatchExpr(handler, Matchers::Equals(str), matcherString);
8377AssertionResultData::AssertionResultData(ResultWas::OfType _resultType,
8379 : lazyExpression(_lazyExpression), resultType(_resultType) {}
8381std::string AssertionResultData::reconstructExpression()
const {
8383 if (reconstructedExpression.empty()) {
8384 if (lazyExpression) {
8386 rss << lazyExpression;
8387 reconstructedExpression = rss.str();
8390 return reconstructedExpression;
8393AssertionResult::AssertionResult(
AssertionInfo const& info, AssertionResultData
const& data)
8394 : m_info(info), m_resultData(data) {}
8397bool AssertionResult::succeeded()
const {
8398 return Catch::isOk(m_resultData.resultType);
8402bool AssertionResult::isOk()
const {
8403 return Catch::isOk(m_resultData.resultType) || shouldSuppressFailure(m_info.resultDisposition);
8406ResultWas::OfType AssertionResult::getResultType()
const {
8407 return m_resultData.resultType;
8410bool AssertionResult::hasExpression()
const {
8411 return !m_info.capturedExpression.empty();
8414bool AssertionResult::hasMessage()
const {
8415 return !m_resultData.message.empty();
8418std::string AssertionResult::getExpression()
const {
8421 expr.reserve(m_info.capturedExpression.size() + 3);
8422 if (isFalseTest(m_info.resultDisposition)) {
8425 expr += m_info.capturedExpression;
8426 if (isFalseTest(m_info.resultDisposition)) {
8432std::string AssertionResult::getExpressionInMacro()
const {
8434 if (m_info.macroName.empty())
8435 expr =
static_cast<std::string
>(m_info.capturedExpression);
8437 expr.reserve(m_info.macroName.size() + m_info.capturedExpression.size() + 4);
8438 expr += m_info.macroName;
8440 expr += m_info.capturedExpression;
8446bool AssertionResult::hasExpandedExpression()
const {
8447 return hasExpression() && getExpandedExpression() != getExpression();
8450std::string AssertionResult::getExpandedExpression()
const {
8451 std::string expr = m_resultData.reconstructExpression();
8452 return expr.empty() ? getExpression() : expr;
8455std::string AssertionResult::getMessage()
const {
8456 return m_resultData.message;
8459 return m_info.lineInfo;
8462StringRef AssertionResult::getTestMacroName()
const {
8463 return m_info.macroName;
8478void handleExceptionMatchExpr(
AssertionHandler& handler, StringMatcher
const& matcher,
8480 std::string exceptionMessage = Catch::translateActiveException();
8482 handler.handleExpr(expr);
8495#ifdef CLARA_CONFIG_CONSOLE_WIDTH
8496#define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8497#undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8499#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH - 1
8502#pragma clang diagnostic push
8503#pragma clang diagnostic ignored "-Wweak-vtables"
8504#pragma clang diagnostic ignored "-Wexit-time-destructors"
8505#pragma clang diagnostic ignored "-Wshadow"
8518#ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8519#define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
8522#ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8523#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8526#ifndef CLARA_CONFIG_OPTIONAL_TYPE
8528#if __has_include(<optional>) && __cplusplus >= 201703L
8530#define CLARA_CONFIG_OPTIONAL_TYPE std::optional
8551#ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8552#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
8559inline auto isWhitespace(
char c) ->
bool {
8560 static std::string chars =
" \t\n\r";
8561 return chars.find(c) != std::string::npos;
8563inline auto isBreakableBefore(
char c) ->
bool {
8564 static std::string chars =
"[({<|";
8565 return chars.find(c) != std::string::npos;
8567inline auto isBreakableAfter(
char c) ->
bool {
8568 static std::string chars =
"])}>.,:;*+-=&/\\";
8569 return chars.find(c) != std::string::npos;
8575 std::vector<std::string> m_strings;
8576 size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8577 size_t m_indent = 0;
8578 size_t m_initialIndent = std::string::npos;
8584 Column
const& m_column;
8585 size_t m_stringIndex = 0;
8590 bool m_suffix =
false;
8592 iterator(Column
const& column,
size_t stringIndex)
8593 : m_column(column), m_stringIndex(stringIndex) {}
8595 auto line() const -> std::
string const& {
return m_column.m_strings[m_stringIndex]; }
8597 auto isBoundary(
size_t at)
const ->
bool {
8599 assert(at <= line().size());
8601 return at == line().size() ||
8602 (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
8603 isBreakableBefore(line()[at]) || isBreakableAfter(line()[at - 1]);
8607 assert(m_stringIndex < m_column.m_strings.size());
8610 auto width = m_column.m_width - indent();
8612 if (line()[m_pos] ==
'\n') {
8615 while (m_end < line().size() && line()[m_end] !=
'\n')
8618 if (m_end < m_pos + width) {
8619 m_len = m_end - m_pos;
8622 while (len > 0 && !isBoundary(m_pos + len))
8624 while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
8636 auto indent() const ->
size_t {
8638 m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
8639 return initial == std::string::npos ? m_column.m_indent : initial;
8642 auto addIndentAndSuffix(std::string
const& plain)
const -> std::string {
8643 return std::string(indent(),
' ') + (m_suffix ? plain + "-" : plain);
8647 using difference_type = std::ptrdiff_t;
8648 using value_type = std::string;
8649 using pointer = value_type*;
8650 using reference = value_type&;
8651 using iterator_category = std::forward_iterator_tag;
8653 explicit iterator(Column
const& column) : m_column(column) {
8654 assert(m_column.m_width > m_column.m_indent);
8655 assert(m_column.m_initialIndent == std::string::npos ||
8656 m_column.m_width > m_column.m_initialIndent);
8662 auto operator*() const -> std::
string {
8663 assert(m_stringIndex < m_column.m_strings.size());
8664 assert(m_pos <= m_end);
8665 return addIndentAndSuffix(line().substr(m_pos, m_len));
8668 auto operator++() -> iterator& {
8670 if (m_pos < line().size() && line()[m_pos] ==
'\n')
8673 while (m_pos < line().size() && isWhitespace(line()[m_pos]))
8676 if (m_pos == line().size()) {
8680 if (m_stringIndex < m_column.m_strings.size())
8684 auto operator++(
int) -> iterator {
8685 iterator prev(*
this);
8690 auto operator==(iterator
const& other)
const ->
bool {
8691 return m_pos == other.m_pos && m_stringIndex == other.m_stringIndex &&
8692 &m_column == &other.m_column;
8694 auto operator!=(iterator
const& other)
const ->
bool {
return !operator==(other); }
8696 using const_iterator = iterator;
8698 explicit Column(std::string
const& text) { m_strings.push_back(text); }
8700 auto width(
size_t newWidth) -> Column& {
8701 assert(newWidth > 0);
8705 auto indent(
size_t newIndent) -> Column& {
8706 m_indent = newIndent;
8709 auto initialIndent(
size_t newIndent) -> Column& {
8710 m_initialIndent = newIndent;
8714 auto width() const ->
size_t {
return m_width; }
8715 auto begin() const -> iterator {
return iterator(*
this); }
8716 auto end() const -> iterator {
return {*
this, m_strings.size()}; }
8718 inline friend std::ostream& operator<<(std::ostream& os, Column
const& col) {
8720 for (
auto line : col) {
8730 auto operator+(Column
const& other) -> Columns;
8732 auto toString() const -> std::
string {
8733 std::ostringstream oss;
8739class Spacer :
public Column {
8742 explicit Spacer(
size_t spaceWidth) : Column(
"") { width(spaceWidth); }
8746 std::vector<Column> m_columns;
8753 std::vector<Column>
const& m_columns;
8754 std::vector<Column::iterator> m_iterators;
8755 size_t m_activeIterators;
8757 iterator(Columns
const& columns, EndTag)
8758 : m_columns(columns.m_columns), m_activeIterators(0) {
8759 m_iterators.reserve(m_columns.size());
8761 for (
auto const& col : m_columns)
8762 m_iterators.push_back(col.end());
8766 using difference_type = std::ptrdiff_t;
8767 using value_type = std::string;
8768 using pointer = value_type*;
8769 using reference = value_type&;
8770 using iterator_category = std::forward_iterator_tag;
8772 explicit iterator(Columns
const& columns)
8773 : m_columns(columns.m_columns), m_activeIterators(m_columns.size()) {
8774 m_iterators.reserve(m_columns.size());
8776 for (
auto const& col : m_columns)
8777 m_iterators.push_back(col.begin());
8780 auto operator==(iterator
const& other)
const ->
bool {
8781 return m_iterators == other.m_iterators;
8783 auto operator!=(iterator
const& other)
const ->
bool {
8784 return m_iterators != other.m_iterators;
8786 auto operator*() const -> std::
string {
8787 std::string row, padding;
8789 for (
size_t i = 0; i < m_columns.size(); ++i) {
8790 auto width = m_columns[i].width();
8791 if (m_iterators[i] != m_columns[i].end()) {
8792 std::string col = *m_iterators[i];
8793 row += padding + col;
8794 if (col.size() < width)
8795 padding = std::string(width - col.size(),
' ');
8799 padding += std::string(width, ' ');
8804 auto operator++() -> iterator& {
8805 for (
size_t i = 0; i < m_columns.size(); ++i) {
8806 if (m_iterators[i] != m_columns[i].end())
8811 auto operator++(
int) -> iterator {
8812 iterator prev(*
this);
8817 using const_iterator = iterator;
8819 auto begin() const -> iterator {
return iterator(*
this); }
8820 auto end() const -> iterator {
return {*
this, iterator::EndTag()}; }
8822 auto operator+=(Column
const& col) -> Columns& {
8823 m_columns.push_back(col);
8826 auto operator+(Column
const& col) -> Columns {
8827 Columns combined = *
this;
8832 inline friend std::ostream& operator<<(std::ostream& os, Columns
const& cols) {
8835 for (
auto line : cols) {
8845 auto toString() const -> std::
string {
8846 std::ostringstream oss;
8852inline auto Column::operator+(Column
const& other) -> Columns {
8872#if !defined(CATCH_PLATFORM_WINDOWS) && \
8873 (defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER))
8874#define CATCH_PLATFORM_WINDOWS
8883template <
typename L>
struct UnaryLambdaTraits : UnaryLambdaTraits<decltype(&L::operator())> {};
8885template <
typename ClassT,
typename ReturnT,
typename... Args>
8886struct UnaryLambdaTraits<ReturnT (ClassT::*)(Args...) const> {
8887 static const bool isValid =
false;
8890template <
typename ClassT,
typename ReturnT,
typename ArgT>
8891struct UnaryLambdaTraits<ReturnT (ClassT::*)(ArgT) const> {
8892 static const bool isValid =
true;
8893 using ArgType =
typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
8894 using ReturnType = ReturnT;
8903 std::string m_exeName;
8904 std::vector<std::string> m_args;
8907 Args(
int argc,
char const*
const* argv) : m_exeName(argv[0]), m_args(argv + 1, argv + argc) {}
8909 Args(std::initializer_list<std::string> args)
8910 : m_exeName(*args.begin()), m_args(args.begin() + 1, args.end()) {}
8912 auto exeName() const -> std::
string {
return m_exeName; }
8918enum class TokenType { Option, Argument };
8924inline auto isOptPrefix(
char c) ->
bool {
8926#ifdef CATCH_PLATFORM_WINDOWS
8935 using Iterator = std::vector<std::string>::const_iterator;
8938 std::vector<Token> m_tokenBuffer;
8941 m_tokenBuffer.resize(0);
8944 while (it != itEnd && it->empty())
8948 auto const& next = *it;
8949 if (isOptPrefix(next[0])) {
8950 auto delimiterPos = next.find_first_of(
" :=");
8951 if (delimiterPos != std::string::npos) {
8952 m_tokenBuffer.push_back({TokenType::Option, next.substr(0, delimiterPos)});
8953 m_tokenBuffer.push_back({TokenType::Argument, next.substr(delimiterPos + 1)});
8955 if (next[1] !=
'-' && next.size() > 2) {
8956 std::string opt =
"- ";
8957 for (
size_t i = 1; i < next.size(); ++i) {
8959 m_tokenBuffer.push_back({TokenType::Option, opt});
8962 m_tokenBuffer.push_back({TokenType::Option, next});
8966 m_tokenBuffer.push_back({TokenType::Argument, next});
8972 explicit TokenStream(Args
const& args) : TokenStream(args.m_args.begin(), args.m_args.end()) {}
8974 TokenStream(Iterator it, Iterator itEnd) : it(it), itEnd(itEnd) { loadBuffer(); }
8976 explicit operator bool()
const {
return !m_tokenBuffer.empty() || it != itEnd; }
8978 auto count() const ->
size_t {
return m_tokenBuffer.size() + (itEnd - it); }
8980 auto operator*() const -> Token {
8981 assert(!m_tokenBuffer.empty());
8982 return m_tokenBuffer.front();
8985 auto operator->() const -> Token const* {
8986 assert(!m_tokenBuffer.empty());
8987 return &m_tokenBuffer.front();
8990 auto operator++() -> TokenStream& {
8991 if (m_tokenBuffer.size() >= 2) {
8992 m_tokenBuffer.erase(m_tokenBuffer.begin());
9004 enum Type { Ok, LogicError, RuntimeError };
9007 ResultBase(Type type) : m_type(type) {}
9008 virtual ~ResultBase() =
default;
9010 virtual void enforceOk()
const = 0;
9015template <
typename T>
class ResultValueBase :
public ResultBase {
9017 auto value() const -> T const& {
9023 ResultValueBase(Type type) : ResultBase(type) {}
9025 ResultValueBase(ResultValueBase
const& other) : ResultBase(other) {
9026 if (m_type == ResultBase::Ok)
9027 new (&m_value) T(other.m_value);
9030 ResultValueBase(Type, T
const& value) : ResultBase(Ok) {
new (&m_value) T(value); }
9032 auto operator=(ResultValueBase
const& other) -> ResultValueBase& {
9033 if (m_type == ResultBase::Ok)
9035 ResultBase::operator=(other);
9036 if (m_type == ResultBase::Ok)
9037 new (&m_value) T(other.m_value);
9041 ~ResultValueBase()
override {
9051template <>
class ResultValueBase<void> :
public ResultBase {
9053 using ResultBase::ResultBase;
9056template <
typename T =
void>
class BasicResult :
public ResultValueBase<T> {
9058 template <
typename U>
9059 explicit BasicResult(BasicResult<U>
const& other)
9060 : ResultValueBase<T>(other.type()), m_errorMessage(other.errorMessage()) {
9061 assert(type() != ResultBase::Ok);
9064 template <
typename U>
static auto ok(U
const& value) -> BasicResult {
9065 return {ResultBase::Ok, value};
9067 static auto ok() -> BasicResult {
return {ResultBase::Ok}; }
9068 static auto logicError(std::string
const& message) -> BasicResult {
9069 return {ResultBase::LogicError, message};
9071 static auto runtimeError(std::string
const& message) -> BasicResult {
9072 return {ResultBase::RuntimeError, message};
9075 explicit operator bool()
const {
return m_type == ResultBase::Ok; }
9076 auto type() const -> ResultBase::Type {
return m_type; }
9077 auto errorMessage() const -> std::
string {
return m_errorMessage; }
9080 void enforceOk()
const override {
9084 assert(m_type != ResultBase::LogicError);
9085 assert(m_type != ResultBase::RuntimeError);
9086 if (m_type != ResultBase::Ok)
9090 std::string m_errorMessage;
9092 BasicResult(ResultBase::Type type, std::string
const& message)
9093 : ResultValueBase<T>(type), m_errorMessage(message) {
9094 assert(m_type != ResultBase::Ok);
9097 using ResultValueBase<T>::ResultValueBase;
9098 using ResultBase::m_type;
9101enum class ParseResultType { Matched, NoMatch, ShortCircuitAll, ShortCircuitSame };
9105 ParseState(ParseResultType type, TokenStream
const& remainingTokens)
9106 : m_type(type), m_remainingTokens(remainingTokens) {}
9108 auto type() const -> ParseResultType {
return m_type; }
9109 auto remainingTokens() const -> TokenStream {
return m_remainingTokens; }
9112 ParseResultType m_type;
9113 TokenStream m_remainingTokens;
9116using Result = BasicResult<void>;
9117using ParserResult = BasicResult<ParseResultType>;
9118using InternalParseResult = BasicResult<ParseState>;
9125template <
typename T>
9126inline auto convertInto(std::string
const& source, T& target) -> ParserResult {
9127 std::stringstream ss;
9131 return ParserResult::runtimeError(
"Unable to convert '" + source +
"' to destination type");
9133 return ParserResult::ok(ParseResultType::Matched);
9135inline auto convertInto(std::string
const& source, std::string& target) -> ParserResult {
9137 return ParserResult::ok(ParseResultType::Matched);
9139inline auto convertInto(std::string
const& source,
bool& target) -> ParserResult {
9140 std::string srcLC = source;
9141 std::transform(srcLC.begin(), srcLC.end(), srcLC.begin(),
9142 [](
unsigned char c) { return static_cast<char>(std::tolower(c)); });
9143 if (srcLC ==
"y" || srcLC ==
"1" || srcLC ==
"true" || srcLC ==
"yes" || srcLC ==
"on")
9145 else if (srcLC ==
"n" || srcLC ==
"0" || srcLC ==
"false" || srcLC ==
"no" || srcLC ==
"off")
9148 return ParserResult::runtimeError(
"Expected a boolean value but did not recognise: '" +
9150 return ParserResult::ok(ParseResultType::Matched);
9152#ifdef CLARA_CONFIG_OPTIONAL_TYPE
9153template <
typename T>
9154inline auto convertInto(std::string
const& source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target)
9157 auto result = convertInto(source, temp);
9159 target = std::move(temp);
9165 NonCopyable() =
default;
9166 NonCopyable(NonCopyable
const&) =
delete;
9167 NonCopyable(NonCopyable&&) =
delete;
9168 NonCopyable& operator=(NonCopyable
const&) =
delete;
9169 NonCopyable& operator=(NonCopyable&&) =
delete;
9172struct BoundRef : NonCopyable {
9173 virtual ~BoundRef() =
default;
9174 virtual auto isContainer() const ->
bool {
return false; }
9175 virtual auto isFlag() const ->
bool {
return false; }
9177struct BoundValueRefBase : BoundRef {
9178 virtual auto setValue(std::string
const& arg) -> ParserResult = 0;
9180struct BoundFlagRefBase : BoundRef {
9181 virtual auto setFlag(
bool flag) -> ParserResult = 0;
9182 virtual auto isFlag() const ->
bool {
return true; }
9185template <
typename T>
struct BoundValueRef : BoundValueRefBase {
9188 explicit BoundValueRef(T& ref) : m_ref(ref) {}
9190 auto setValue(std::string
const& arg) -> ParserResult
override {
9191 return convertInto(arg, m_ref);
9195template <
typename T>
struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
9196 std::vector<T>& m_ref;
9198 explicit BoundValueRef(std::vector<T>& ref) : m_ref(ref) {}
9200 auto isContainer() const ->
bool override {
return true; }
9202 auto setValue(std::string
const& arg) -> ParserResult
override {
9204 auto result = convertInto(arg, temp);
9206 m_ref.push_back(temp);
9211struct BoundFlagRef : BoundFlagRefBase {
9214 explicit BoundFlagRef(
bool& ref) : m_ref(ref) {}
9216 auto setFlag(
bool flag) -> ParserResult
override {
9218 return ParserResult::ok(ParseResultType::Matched);
9222template <
typename ReturnType>
struct LambdaInvoker {
9223 static_assert(std::is_same<ReturnType, ParserResult>::value,
9224 "Lambda must return void or clara::ParserResult");
9226 template <
typename L,
typename ArgType>
9227 static auto invoke(L
const& lambda, ArgType
const& arg) -> ParserResult {
9232template <>
struct LambdaInvoker<void> {
9233 template <
typename L,
typename ArgType>
9234 static auto invoke(L
const& lambda, ArgType
const& arg) -> ParserResult {
9236 return ParserResult::ok(ParseResultType::Matched);
9240template <
typename ArgType,
typename L>
9241inline auto invokeLambda(L
const& lambda, std::string
const& arg) -> ParserResult {
9243 auto result = convertInto(arg, temp);
9244 return !result ? result
9245 : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke(lambda, temp);
9248template <
typename L>
struct BoundLambda : BoundValueRefBase {
9251 static_assert(UnaryLambdaTraits<L>::isValid,
"Supplied lambda must take exactly one argument");
9252 explicit BoundLambda(L
const& lambda) : m_lambda(lambda) {}
9254 auto setValue(std::string
const& arg) -> ParserResult
override {
9255 return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>(m_lambda, arg);
9259template <
typename L>
struct BoundFlagLambda : BoundFlagRefBase {
9262 static_assert(UnaryLambdaTraits<L>::isValid,
"Supplied lambda must take exactly one argument");
9263 static_assert(std::is_same<typename UnaryLambdaTraits<L>::ArgType,
bool>::value,
9264 "flags must be boolean");
9266 explicit BoundFlagLambda(L
const& lambda) : m_lambda(lambda) {}
9268 auto setFlag(
bool flag) -> ParserResult
override {
9269 return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke(m_lambda, flag);
9273enum class Optionality { Optional, Required };
9279 virtual ~ParserBase() =
default;
9280 virtual auto validate() const -> Result {
return Result::ok(); }
9281 virtual auto parse(std::string
const& exeName, TokenStream
const& tokens)
const
9282 -> InternalParseResult = 0;
9283 virtual auto cardinality() const ->
size_t {
return 1; }
9285 auto parse(Args
const& args)
const -> InternalParseResult {
9286 return parse(args.exeName(), TokenStream(args));
9290template <
typename DerivedT>
class ComposableParserImpl :
public ParserBase {
9292 template <
typename T>
auto operator|(T
const& other)
const -> Parser;
9294 template <
typename T>
auto operator+(T
const& other)
const -> Parser;
9298template <
typename DerivedT>
class ParserRefImpl :
public ComposableParserImpl<DerivedT> {
9300 Optionality m_optionality = Optionality::Optional;
9301 std::shared_ptr<BoundRef> m_ref;
9303 std::string m_description;
9305 explicit ParserRefImpl(std::shared_ptr<BoundRef>
const& ref) : m_ref(ref) {}
9308 template <
typename T>
9309 ParserRefImpl(T& ref, std::string
const& hint)
9310 : m_ref(std::make_shared<BoundValueRef<T>>(ref)), m_hint(hint) {}
9312 template <
typename LambdaT>
9313 ParserRefImpl(LambdaT
const& ref, std::string
const& hint)
9314 : m_ref(std::make_shared<BoundLambda<LambdaT>>(ref)), m_hint(hint) {}
9316 auto operator()(std::string
const& description) -> DerivedT& {
9317 m_description = description;
9318 return static_cast<DerivedT&
>(*this);
9321 auto optional() -> DerivedT& {
9322 m_optionality = Optionality::Optional;
9323 return static_cast<DerivedT&
>(*this);
9326 auto required() -> DerivedT& {
9327 m_optionality = Optionality::Required;
9328 return static_cast<DerivedT&
>(*this);
9331 auto isOptional() const ->
bool {
return m_optionality == Optionality::Optional; }
9333 auto cardinality() const ->
size_t override {
9334 if (m_ref->isContainer())
9340 auto hint() const -> std::
string {
return m_hint; }
9343class ExeName :
public ComposableParserImpl<ExeName> {
9344 std::shared_ptr<std::string> m_name;
9345 std::shared_ptr<BoundValueRefBase> m_ref;
9347 template <
typename LambdaT>
9348 static auto makeRef(LambdaT
const& lambda) -> std::shared_ptr<BoundValueRefBase> {
9349 return std::make_shared<BoundLambda<LambdaT>>(lambda);
9353 ExeName() : m_name(std::make_shared<std::
string>(
"<executable>")) {}
9355 explicit ExeName(std::string& ref) : ExeName() {
9356 m_ref = std::make_shared<BoundValueRef<std::string>>(ref);
9359 template <
typename LambdaT>
explicit ExeName(LambdaT
const& lambda) : ExeName() {
9360 m_ref = std::make_shared<BoundLambda<LambdaT>>(lambda);
9365 auto parse(std::string
const&, TokenStream
const& tokens)
const
9366 -> InternalParseResult
override {
9367 return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, tokens));
9370 auto name() const -> std::
string {
return *m_name; }
9371 auto set(std::string
const& newName) -> ParserResult {
9373 auto lastSlash = newName.find_last_of(
"\\/");
9374 auto filename = (lastSlash == std::string::npos) ? newName : newName.substr(lastSlash + 1);
9378 return m_ref->setValue(filename);
9380 return ParserResult::ok(ParseResultType::Matched);
9384class Arg :
public ParserRefImpl<Arg> {
9386 using ParserRefImpl::ParserRefImpl;
9388 auto parse(std::string
const&, TokenStream
const& tokens)
const
9389 -> InternalParseResult
override {
9390 auto validationResult = validate();
9391 if (!validationResult)
9392 return InternalParseResult(validationResult);
9394 auto remainingTokens = tokens;
9395 auto const& token = *remainingTokens;
9396 if (token.type != TokenType::Argument)
9397 return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, remainingTokens));
9399 assert(!m_ref->isFlag());
9400 auto valueRef =
static_cast<detail::BoundValueRefBase*
>(m_ref.get());
9402 auto result = valueRef->setValue(remainingTokens->token);
9404 return InternalParseResult(result);
9406 return InternalParseResult::ok(ParseState(ParseResultType::Matched, ++remainingTokens));
9410inline auto normaliseOpt(std::string
const& optName) -> std::string {
9411#ifdef CATCH_PLATFORM_WINDOWS
9412 if (optName[0] ==
'/')
9413 return "-" + optName.substr(1);
9419class Opt :
public ParserRefImpl<Opt> {
9421 std::vector<std::string> m_optNames;
9424 template <
typename LambdaT>
9425 explicit Opt(LambdaT
const& ref)
9426 : ParserRefImpl(std::make_shared<BoundFlagLambda<LambdaT>>(ref)) {}
9428 explicit Opt(
bool& ref) : ParserRefImpl(std::make_shared<BoundFlagRef>(ref)) {}
9430 template <
typename LambdaT>
9431 Opt(LambdaT
const& ref, std::string
const& hint) : ParserRefImpl(ref, hint) {}
9433 template <
typename T> Opt(T& ref, std::string
const& hint) : ParserRefImpl(ref, hint) {}
9435 auto operator[](std::string
const& optName) -> Opt& {
9436 m_optNames.push_back(optName);
9440 auto getHelpColumns() const -> std::vector<HelpColumns> {
9441 std::ostringstream oss;
9443 for (
auto const& opt : m_optNames) {
9450 if (!m_hint.empty())
9451 oss <<
" <" << m_hint <<
">";
9452 return {{oss.str(), m_description}};
9455 auto isMatch(std::string
const& optToken)
const ->
bool {
9456 auto normalisedToken = normaliseOpt(optToken);
9457 for (
auto const& name : m_optNames) {
9458 if (normaliseOpt(name) == normalisedToken)
9464 using ParserBase::parse;
9466 auto parse(std::string
const&, TokenStream
const& tokens)
const
9467 -> InternalParseResult
override {
9468 auto validationResult = validate();
9469 if (!validationResult)
9470 return InternalParseResult(validationResult);
9472 auto remainingTokens = tokens;
9473 if (remainingTokens && remainingTokens->type == TokenType::Option) {
9474 auto const& token = *remainingTokens;
9475 if (isMatch(token.token)) {
9476 if (m_ref->isFlag()) {
9477 auto flagRef =
static_cast<detail::BoundFlagRefBase*
>(m_ref.get());
9478 auto result = flagRef->setFlag(
true);
9480 return InternalParseResult(result);
9481 if (result.value() == ParseResultType::ShortCircuitAll)
9482 return InternalParseResult::ok(ParseState(result.value(), remainingTokens));
9484 auto valueRef =
static_cast<detail::BoundValueRefBase*
>(m_ref.get());
9486 if (!remainingTokens)
9487 return InternalParseResult::runtimeError(
"Expected argument following " +
9489 auto const& argToken = *remainingTokens;
9490 if (argToken.type != TokenType::Argument)
9491 return InternalParseResult::runtimeError(
"Expected argument following " +
9493 auto result = valueRef->setValue(argToken.token);
9495 return InternalParseResult(result);
9496 if (result.value() == ParseResultType::ShortCircuitAll)
9497 return InternalParseResult::ok(ParseState(result.value(), remainingTokens));
9499 return InternalParseResult::ok(
9500 ParseState(ParseResultType::Matched, ++remainingTokens));
9503 return InternalParseResult::ok(ParseState(ParseResultType::NoMatch, remainingTokens));
9506 auto validate() const -> Result
override {
9507 if (m_optNames.empty())
9508 return Result::logicError(
"No options supplied to Opt");
9509 for (
auto const& name : m_optNames) {
9511 return Result::logicError(
"Option name cannot be empty");
9512#ifdef CATCH_PLATFORM_WINDOWS
9513 if (name[0] !=
'-' && name[0] !=
'/')
9514 return Result::logicError(
"Option name must begin with '-' or '/'");
9517 return Result::logicError(
"Option name must begin with '-'");
9520 return ParserRefImpl::validate();
9525 Help(
bool& showHelpFlag)
9526 : Opt([&](bool flag) {
9527 showHelpFlag = flag;
9528 return ParserResult::ok(ParseResultType::ShortCircuitAll);
9530 static_cast<Opt&
>(*this)(
"display usage information")[
"-?"][
"-h"][
"--help"].optional();
9534struct Parser : ParserBase {
9536 mutable ExeName m_exeName;
9537 std::vector<Opt> m_options;
9538 std::vector<Arg> m_args;
9540 auto operator|=(ExeName
const& exeName) -> Parser& {
9541 m_exeName = exeName;
9545 auto operator|=(Arg
const& arg) -> Parser& {
9546 m_args.push_back(arg);
9550 auto operator|=(Opt
const& opt) -> Parser& {
9551 m_options.push_back(opt);
9555 auto operator|=(Parser
const& other) -> Parser& {
9556 m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
9557 m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9561 template <
typename T>
auto operator|(T
const& other)
const -> Parser {
9562 return Parser(*
this) |= other;
9566 template <
typename T>
auto operator+=(T
const& other) -> Parser& {
return operator|=(other); }
9567 template <
typename T>
auto operator+(T
const& other)
const -> Parser {
9568 return operator|(other);
9571 auto getHelpColumns() const -> std::vector<HelpColumns> {
9572 std::vector<HelpColumns> cols;
9573 for (
auto const& o : m_options) {
9574 auto childCols = o.getHelpColumns();
9575 cols.insert(cols.end(), childCols.begin(), childCols.end());
9580 void writeToStream(std::ostream& os)
const {
9581 if (!m_exeName.name().empty()) {
9582 os <<
"usage:\n" <<
" " << m_exeName.name() <<
" ";
9583 bool required =
true, first =
true;
9584 for (
auto const& arg : m_args) {
9589 if (arg.isOptional() && required) {
9593 os <<
"<" << arg.hint() <<
">";
9594 if (arg.cardinality() == 0)
9599 if (!m_options.empty())
9601 os <<
"\n\nwhere options are:" << std::endl;
9604 auto rows = getHelpColumns();
9605 size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
9606 size_t optWidth = 0;
9607 for (
auto const& cols : rows)
9608 optWidth = (std::max)(optWidth, cols.left.size() + 2);
9610 optWidth = (std::min)(optWidth, consoleWidth / 2);
9612 for (
auto const& cols : rows) {
9613 auto row = TextFlow::Column(cols.left).width(optWidth).indent(2) + TextFlow::Spacer(4) +
9614 TextFlow::Column(cols.right).width(consoleWidth - 7 - optWidth);
9615 os << row << std::endl;
9619 friend auto operator<<(std::ostream& os, Parser
const& parser) -> std::ostream& {
9620 parser.writeToStream(os);
9624 auto validate() const -> Result
override {
9625 for (
auto const& opt : m_options) {
9626 auto result = opt.validate();
9630 for (
auto const& arg : m_args) {
9631 auto result = arg.validate();
9635 return Result::ok();
9638 using ParserBase::parse;
9640 auto parse(std::string
const& exeName, TokenStream
const& tokens)
const
9641 -> InternalParseResult
override {
9644 ParserBase
const* parser =
nullptr;
9647 const size_t totalParsers = m_options.size() + m_args.size();
9648 assert(totalParsers < 512);
9651 ParserInfo parseInfos[512];
9655 for (
auto const& opt : m_options)
9656 parseInfos[i++].parser = &opt;
9657 for (
auto const& arg : m_args)
9658 parseInfos[i++].parser = &arg;
9661 m_exeName.set(exeName);
9663 auto result = InternalParseResult::ok(ParseState(ParseResultType::NoMatch, tokens));
9664 while (result.value().remainingTokens()) {
9665 bool tokenParsed =
false;
9667 for (
size_t i = 0; i < totalParsers; ++i) {
9668 auto& parseInfo = parseInfos[i];
9669 if (parseInfo.parser->cardinality() == 0 ||
9670 parseInfo.count < parseInfo.parser->cardinality()) {
9671 result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
9674 if (result.value().type() != ParseResultType::NoMatch) {
9682 if (result.value().type() == ParseResultType::ShortCircuitAll)
9685 return InternalParseResult::runtimeError(
"Unrecognised token: " +
9686 result.value().remainingTokens()->token);
9693template <
typename DerivedT>
9694template <
typename T>
9695auto ComposableParserImpl<DerivedT>::operator|(T
const& other)
const -> Parser {
9696 return Parser() |
static_cast<DerivedT const&
>(*this) | other;
9701using detail::Parser;
9713using detail::ExeName;
9719using detail::ParseResultType;
9722using detail::ParserResult;
9729#pragma clang diagnostic pop
9733#ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9734#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9735#undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9741clara::Parser makeCommandLineParser(ConfigData& config);
9751clara::Parser makeCommandLineParser(ConfigData& config) {
9753 using namespace clara;
9755 auto const setWarning = [&](std::string
const& warning) {
9756 auto warningSet = [&]() {
9757 if (warning ==
"NoAssertions")
9758 return WarnAbout::NoAssertions;
9760 if (warning ==
"NoTests")
9761 return WarnAbout::NoTests;
9763 return WarnAbout::Nothing;
9766 if (warningSet == WarnAbout::Nothing)
9767 return ParserResult::runtimeError(
"Unrecognised warning: '" + warning +
"'");
9768 config.warnings =
static_cast<WarnAbout::What
>(config.warnings | warningSet);
9769 return ParserResult::ok(ParseResultType::Matched);
9771 auto const loadTestNamesFromFile = [&](std::string
const& filename) {
9772 std::ifstream f(filename.c_str());
9774 return ParserResult::runtimeError(
"Unable to load input file: '" + filename +
"'");
9777 while (std::getline(f, line)) {
9779 if (!line.empty() && !startsWith(line,
'#')) {
9780 if (!startsWith(line,
'"'))
9781 line =
'"' + line + '"';
9782 config.testsOrTags.push_back(line);
9783 config.testsOrTags.emplace_back(
",");
9787 if (!config.testsOrTags.empty())
9788 config.testsOrTags.erase(config.testsOrTags.end() - 1);
9790 return ParserResult::ok(ParseResultType::Matched);
9792 auto const setTestOrder = [&](std::string
const& order) {
9793 if (startsWith(
"declared", order))
9794 config.runOrder = RunTests::InDeclarationOrder;
9795 else if (startsWith(
"lexical", order))
9796 config.runOrder = RunTests::InLexicographicalOrder;
9797 else if (startsWith(
"random", order))
9798 config.runOrder = RunTests::InRandomOrder;
9800 return clara::ParserResult::runtimeError(
"Unrecognised ordering: '" + order +
"'");
9801 return ParserResult::ok(ParseResultType::Matched);
9803 auto const setRngSeed = [&](std::string
const& seed) {
9805 return clara::detail::convertInto(seed, config.rngSeed);
9806 config.rngSeed =
static_cast<unsigned int>(std::time(
nullptr));
9807 return ParserResult::ok(ParseResultType::Matched);
9809 auto const setColourUsage = [&](std::string
const& useColour) {
9810 auto mode = toLower(useColour);
9813 config.useColour = UseColour::Yes;
9814 else if (mode ==
"no")
9815 config.useColour = UseColour::No;
9816 else if (mode ==
"auto")
9817 config.useColour = UseColour::Auto;
9819 return ParserResult::runtimeError(
"colour mode must be one of: auto, yes or no. '" +
9820 useColour +
"' not recognised");
9821 return ParserResult::ok(ParseResultType::Matched);
9823 auto const setWaitForKeypress = [&](std::string
const& keypress) {
9824 auto keypressLc = toLower(keypress);
9825 if (keypressLc ==
"never")
9826 config.waitForKeypress = WaitForKeypress::Never;
9827 else if (keypressLc ==
"start")
9828 config.waitForKeypress = WaitForKeypress::BeforeStart;
9829 else if (keypressLc ==
"exit")
9830 config.waitForKeypress = WaitForKeypress::BeforeExit;
9831 else if (keypressLc ==
"both")
9832 config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
9834 return ParserResult::runtimeError(
9835 "keypress argument must be one of: never, start, exit or both. '" + keypress +
9836 "' not recognised");
9837 return ParserResult::ok(ParseResultType::Matched);
9839 auto const setVerbosity = [&](std::string
const& verbosity) {
9840 auto lcVerbosity = toLower(verbosity);
9841 if (lcVerbosity ==
"quiet")
9842 config.verbosity = Verbosity::Quiet;
9843 else if (lcVerbosity ==
"normal")
9844 config.verbosity = Verbosity::Normal;
9845 else if (lcVerbosity ==
"high")
9846 config.verbosity = Verbosity::High;
9848 return ParserResult::runtimeError(
"Unrecognised verbosity, '" + verbosity +
"'");
9849 return ParserResult::ok(ParseResultType::Matched);
9851 auto const setReporter = [&](std::string
const& reporter) {
9852 IReporterRegistry::FactoryMap
const& factories =
9853 getRegistryHub().getReporterRegistry().getFactories();
9855 auto lcReporter = toLower(reporter);
9856 auto result = factories.find(lcReporter);
9858 if (factories.end() != result)
9859 config.reporterName = lcReporter;
9861 return ParserResult::runtimeError(
"Unrecognized reporter, '" + reporter +
9862 "'. Check available with --list-reporters");
9863 return ParserResult::ok(ParseResultType::Matched);
9867 ExeName(config.processName) | Help(config.showHelp) |
9868 Opt(config.listTests)["-l"]["--list-tests"](
"list all/matching test cases") |
9869 Opt(config.listTags)["-t"]["--list-tags"](
"list all/matching tags") |
9870 Opt(config.showSuccessfulTests)["-s"]["--success"](
"include successful tests in output") |
9871 Opt(config.shouldDebugBreak)["-b"]["--break"](
"break into debugger on failure") |
9872 Opt(config.noThrow)["-e"]["--nothrow"](
"skip exception tests") |
9873 Opt(config.showInvisibles)["-i"]["--invisibles"](
"show invisibles (tabs, newlines)") |
9874 Opt(config.outputFilename,
"filename")["-o"]["--out"](
"output filename") |
9875 Opt(setReporter,
"name")["-r"]["--reporter"](
"reporter to use (defaults to console)") |
9876 Opt(config.name,
"name")["-n"]["--name"](
"suite name") |
9877 Opt([&](
bool) { config.abortAfter = 1; })[
"-a"][
"--abort"](
"abort at first failure") |
9878 Opt([&](
int x) { config.abortAfter = x; },
9879 "no. failures")[
"-x"][
"--abortx"](
"abort after x failures") |
9880 Opt(setWarning,
"warning name")["-w"]["--warn"](
"enable warnings") |
9883 config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never;
9885 "yes|no")[
"-d"][
"--durations"](
"show test durations") |
9886 Opt(config.minDuration,
"seconds")["-D"]["--min-duration"](
9887 "show test durations for tests taking at least the given number of "
9889 Opt(loadTestNamesFromFile,
9890 "filename")["-f"]["--input-file"](
"load test names to run from a file") |
9891 Opt(config.filenamesAsTags)["-#"]["--filenames-as-tags"](
"adds a tag for the filename") |
9892 Opt(config.sectionsToRun,
"section name")["-c"]["--section"](
"specify section to run") |
9893 Opt(setVerbosity,
"quiet|normal|high")["-v"]["--verbosity"](
"set output verbosity") |
9894 Opt(config.listTestNamesOnly)["--list-test-names-only"](
9895 "list all/matching test cases names only") |
9896 Opt(config.listReporters)["--list-reporters"](
"list all reporters") |
9897 Opt(setTestOrder,
"decl|lex|rand")["--order"](
"test case order (defaults to decl)") |
9898 Opt(setRngSeed,
"'time'|number")["--rng-seed"](
"set a specific seed for random numbers") |
9899 Opt(setColourUsage,
"yes|no")["--use-colour"](
"should output be colourised") |
9900 Opt(config.libIdentify)["--libidentify"](
9901 "report name and version according to libidentify standard") |
9902 Opt(setWaitForKeypress,
9903 "never|start|exit|both")["--wait-for-keypress"](
"waits for a keypress before exiting") |
9904 Opt(config.benchmarkSamples,
9905 "samples")["--benchmark-samples"](
"number of samples to collect (default: 100)") |
9906 Opt(config.benchmarkResamples,
"resamples")["--benchmark-resamples"](
9907 "number of resamples for the bootstrap (default: 100000)") |
9908 Opt(config.benchmarkConfidenceInterval,
9909 "confidence interval")["--benchmark-confidence-interval"](
9910 "confidence interval for the bootstrap (between 0 and 1, default: "
9912 Opt(config.benchmarkNoAnalysis)["--benchmark-no-analysis"](
9913 "perform only measurements; do not perform any analysis") |
9914 Opt(config.benchmarkWarmupTime,
"benchmarkWarmupTime")["--benchmark-warmup-time"](
9915 "amount of time in milliseconds spent on warming up each test "
9917 Arg(config.testsOrTags,
"test name|pattern|tags")(
"which test or tests to use");
9931bool SourceLineInfo::operator==(
SourceLineInfo const& other)
const noexcept {
9932 return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
9934bool SourceLineInfo::operator<(
SourceLineInfo const& other)
const noexcept {
9937 return line < other.line ||
9938 (line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
9941std::ostream& operator<<(std::ostream& os,
SourceLineInfo const& info) {
9943 os << info.file <<
'(' << info.line <<
')';
9945 os << info.file <<
':' << info.line;
9950std::string StreamEndStop::operator+()
const {
9951 return std::string();
9954NonCopyable::NonCopyable() =
default;
9955NonCopyable::~NonCopyable() =
default;
9963Config::Config(ConfigData
const& data) : m_data(data), m_stream(openStream()) {
9968 for (
auto& elem : m_data.testsOrTags) {
9971 for (
auto& elem : m_data.sectionsToRun) {
9975 TestSpecParser parser(ITagAliasRegistry::get());
9976 if (!m_data.testsOrTags.empty()) {
9977 m_hasTestFilters = true;
9978 for (auto const& testOrTags : m_data.testsOrTags) {
9979 parser.parse(testOrTags);
9982 m_testSpec = parser.testSpec();
9985std::string
const& Config::getFilename()
const {
9986 return m_data.outputFilename;
9989bool Config::listTests()
const {
9990 return m_data.listTests;
9992bool Config::listTestNamesOnly()
const {
9993 return m_data.listTestNamesOnly;
9995bool Config::listTags()
const {
9996 return m_data.listTags;
9998bool Config::listReporters()
const {
9999 return m_data.listReporters;
10002std::string Config::getProcessName()
const {
10003 return m_data.processName;
10005std::string
const& Config::getReporterName()
const {
10006 return m_data.reporterName;
10009std::vector<std::string>
const& Config::getTestsOrTags()
const {
10010 return m_data.testsOrTags;
10012std::vector<std::string>
const& Config::getSectionsToRun()
const {
10013 return m_data.sectionsToRun;
10016TestSpec
const& Config::testSpec()
const {
10019bool Config::hasTestFilters()
const {
10020 return m_hasTestFilters;
10023bool Config::showHelp()
const {
10024 return m_data.showHelp;
10028bool Config::allowThrows()
const {
10029 return !m_data.noThrow;
10031std::ostream& Config::stream()
const {
10032 return m_stream->stream();
10034std::string Config::name()
const {
10035 return m_data.name.empty() ? m_data.processName : m_data.name;
10037bool Config::includeSuccessfulResults()
const {
10038 return m_data.showSuccessfulTests;
10040bool Config::warnAboutMissingAssertions()
const {
10041 return !!(m_data.warnings & WarnAbout::NoAssertions);
10043bool Config::warnAboutNoTests()
const {
10044 return !!(m_data.warnings & WarnAbout::NoTests);
10046ShowDurations::OrNot Config::showDurations()
const {
10047 return m_data.showDurations;
10049double Config::minDuration()
const {
10050 return m_data.minDuration;
10052RunTests::InWhatOrder Config::runOrder()
const {
10053 return m_data.runOrder;
10055unsigned int Config::rngSeed()
const {
10056 return m_data.rngSeed;
10058UseColour::YesOrNo Config::useColour()
const {
10059 return m_data.useColour;
10061bool Config::shouldDebugBreak()
const {
10062 return m_data.shouldDebugBreak;
10064int Config::abortAfter()
const {
10065 return m_data.abortAfter;
10067bool Config::showInvisibles()
const {
10068 return m_data.showInvisibles;
10070Verbosity Config::verbosity()
const {
10071 return m_data.verbosity;
10074bool Config::benchmarkNoAnalysis()
const {
10075 return m_data.benchmarkNoAnalysis;
10077int Config::benchmarkSamples()
const {
10078 return m_data.benchmarkSamples;
10080double Config::benchmarkConfidenceInterval()
const {
10081 return m_data.benchmarkConfidenceInterval;
10083unsigned int Config::benchmarkResamples()
const {
10084 return m_data.benchmarkResamples;
10086std::chrono::milliseconds Config::benchmarkWarmupTime()
const {
10087 return std::chrono::milliseconds(m_data.benchmarkWarmupTime);
10090IStream
const* Config::openStream() {
10091 return Catch::makeStream(m_data.outputFilename);
10098#if defined(__clang__)
10099#pragma clang diagnostic push
10100#pragma clang diagnostic ignored "-Wexit-time-destructors"
10121#if defined(CATCH_PLATFORM_WINDOWS)
10123#if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
10124#define CATCH_DEFINED_NOMINMAX
10127#if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
10128#define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10129#define WIN32_LEAN_AND_MEAN
10135#include <windows.h>
10138#ifdef CATCH_DEFINED_NOMINMAX
10141#ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10142#undef WIN32_LEAN_AND_MEAN
10153struct IColourImpl {
10154 virtual ~IColourImpl() =
default;
10155 virtual void use(Colour::Code _colourCode) = 0;
10158struct NoColourImpl : IColourImpl {
10159 void use(Colour::Code)
override {}
10161 static IColourImpl* instance() {
10162 static NoColourImpl s_instance;
10163 return &s_instance;
10170#if !defined(CATCH_CONFIG_COLOUR_NONE) && !defined(CATCH_CONFIG_COLOUR_WINDOWS) && \
10171 !defined(CATCH_CONFIG_COLOUR_ANSI)
10172#ifdef CATCH_PLATFORM_WINDOWS
10173#define CATCH_CONFIG_COLOUR_WINDOWS
10175#define CATCH_CONFIG_COLOUR_ANSI
10179#if defined(CATCH_CONFIG_COLOUR_WINDOWS)
10184class Win32ColourImpl :
public IColourImpl {
10186 Win32ColourImpl() : stdoutHandle(GetStdHandle(STD_OUTPUT_HANDLE)) {
10187 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
10188 GetConsoleScreenBufferInfo(stdoutHandle, &csbiInfo);
10189 originalForegroundAttributes =
10190 csbiInfo.wAttributes &
10191 ~(BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY);
10192 originalBackgroundAttributes =
10193 csbiInfo.wAttributes &
10194 ~(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY);
10197 void use(Colour::Code _colourCode)
override {
10198 switch (_colourCode) {
10200 return setTextAttribute(originalForegroundAttributes);
10201 case Colour::White:
10202 return setTextAttribute(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE);
10204 return setTextAttribute(FOREGROUND_RED);
10205 case Colour::Green:
10206 return setTextAttribute(FOREGROUND_GREEN);
10208 return setTextAttribute(FOREGROUND_BLUE);
10210 return setTextAttribute(FOREGROUND_BLUE | FOREGROUND_GREEN);
10211 case Colour::Yellow:
10212 return setTextAttribute(FOREGROUND_RED | FOREGROUND_GREEN);
10214 return setTextAttribute(0);
10216 case Colour::LightGrey:
10217 return setTextAttribute(FOREGROUND_INTENSITY);
10218 case Colour::BrightRed:
10219 return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_RED);
10220 case Colour::BrightGreen:
10221 return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_GREEN);
10222 case Colour::BrightWhite:
10223 return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED |
10225 case Colour::BrightYellow:
10226 return setTextAttribute(FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN);
10228 case Colour::Bright:
10229 CATCH_INTERNAL_ERROR(
"not a colour");
10232 CATCH_ERROR(
"Unknown colour requested");
10237 void setTextAttribute(WORD _textAttribute) {
10238 SetConsoleTextAttribute(stdoutHandle, _textAttribute | originalBackgroundAttributes);
10240 HANDLE stdoutHandle;
10241 WORD originalForegroundAttributes;
10242 WORD originalBackgroundAttributes;
10245IColourImpl* platformColourInstance() {
10246 static Win32ColourImpl s_instance;
10248 IConfigPtr config = getCurrentContext().getConfig();
10249 UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto;
10250 if (colourMode == UseColour::Auto)
10251 colourMode = UseColour::Yes;
10252 return colourMode == UseColour::Yes ? &s_instance : NoColourImpl::instance();
10258#elif defined(CATCH_CONFIG_COLOUR_ANSI)
10269class PosixColourImpl :
public IColourImpl {
10271 void use(Colour::Code _colourCode)
override {
10272 switch (_colourCode) {
10274 case Colour::White:
10275 return setColour(
"[0m");
10277 return setColour(
"[0;31m");
10278 case Colour::Green:
10279 return setColour(
"[0;32m");
10281 return setColour(
"[0;34m");
10283 return setColour(
"[0;36m");
10284 case Colour::Yellow:
10285 return setColour(
"[0;33m");
10287 return setColour(
"[1;30m");
10289 case Colour::LightGrey:
10290 return setColour(
"[0;37m");
10291 case Colour::BrightRed:
10292 return setColour(
"[1;31m");
10293 case Colour::BrightGreen:
10294 return setColour(
"[1;32m");
10295 case Colour::BrightWhite:
10296 return setColour(
"[1;37m");
10297 case Colour::BrightYellow:
10298 return setColour(
"[1;33m");
10300 case Colour::Bright:
10301 CATCH_INTERNAL_ERROR(
"not a colour");
10303 CATCH_INTERNAL_ERROR(
"Unknown colour requested");
10306 static IColourImpl* instance() {
10307 static PosixColourImpl s_instance;
10308 return &s_instance;
10312 void setColour(
const char* _escapeCode) {
10313 getCurrentContext().getConfig()->stream() <<
'\033' << _escapeCode;
10317bool useColourOnPlatform() {
10319#if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10320 !isDebuggerActive() &&
10322#if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
10323 isatty(STDOUT_FILENO)
10329IColourImpl* platformColourInstance() {
10331 IConfigPtr config = getCurrentContext().getConfig();
10332 UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto;
10333 if (colourMode == UseColour::Auto)
10334 colourMode = useColourOnPlatform() ? UseColour::Yes : UseColour::No;
10335 return colourMode == UseColour::Yes ? PosixColourImpl::instance() : NoColourImpl::instance();
10345static IColourImpl* platformColourInstance() {
10346 return NoColourImpl::instance();
10355Colour::Colour(Code _colourCode) {
10358Colour::Colour(Colour&& other)
noexcept {
10359 m_moved = other.m_moved;
10360 other.m_moved =
true;
10362Colour& Colour::operator=(Colour&& other)
noexcept {
10363 m_moved = other.m_moved;
10364 other.m_moved =
true;
10373void Colour::use(Code _colourCode) {
10374 static IColourImpl* impl = platformColourInstance();
10379 if (impl !=
nullptr) {
10380 impl->use(_colourCode);
10384std::ostream& operator<<(std::ostream& os, Colour
const&) {
10390#if defined(__clang__)
10391#pragma clang diagnostic pop
10402 IResultCapture* getResultCapture()
override {
return m_resultCapture; }
10403 IRunner* getRunner()
override {
return m_runner; }
10405 IConfigPtr
const& getConfig()
const override {
return m_config; }
10407 ~Context()
override;
10410 void setResultCapture(IResultCapture* resultCapture)
override {
10411 m_resultCapture = resultCapture;
10413 void setRunner(IRunner* runner)
override { m_runner = runner; }
10414 void setConfig(IConfigPtr
const& config)
override { m_config = config; }
10416 friend IMutableContext& getCurrentMutableContext();
10419 IConfigPtr m_config;
10420 IRunner* m_runner =
nullptr;
10421 IResultCapture* m_resultCapture =
nullptr;
10426void IMutableContext::createContext() {
10427 currentContext =
new Context();
10430void cleanUpContext() {
10431 delete IMutableContext::currentContext;
10432 IMutableContext::currentContext =
nullptr;
10434IContext::~IContext() =
default;
10435IMutableContext::~IMutableContext() =
default;
10436Context::~Context() =
default;
10452void writeToDebugConsole(std::string
const& text);
10456#if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
10457#include <android/log.h>
10460void writeToDebugConsole(std::string
const& text) {
10461 __android_log_write(ANDROID_LOG_DEBUG,
"Catch", text.c_str());
10465#elif defined(CATCH_PLATFORM_WINDOWS)
10468void writeToDebugConsole(std::string
const& text) {
10469 ::OutputDebugStringA(text.c_str());
10476void writeToDebugConsole(std::string
const& text) {
10478 Catch::cout() << text;
10486#if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10491#include <sys/types.h>
10494#ifdef __apple_build_version__
10497#include <sys/sysctl.h>
10501#ifdef __apple_build_version__
10507bool isDebuggerActive() {
10509 struct kinfo_proc info;
10515 info.kp_proc.p_flag = 0;
10521 mib[1] = KERN_PROC;
10522 mib[2] = KERN_PROC_PID;
10527 size =
sizeof(info);
10528 if (sysctl(mib,
sizeof(mib) /
sizeof(*mib), &info, &size,
nullptr, 0) != 0) {
10529 Catch::cerr() <<
"\n** Call to sysctl failed - unable to determine if "
10530 "debugger is active **\n"
10537 return ((info.kp_proc.p_flag & P_TRACED) != 0);
10540bool isDebuggerActive() {
10548#elif defined(CATCH_PLATFORM_LINUX)
10560bool isDebuggerActive() {
10564 std::ifstream in(
"/proc/self/status");
10565 for (std::string line; std::getline(in, line);) {
10566 static const int PREFIX_LEN = 11;
10567 if (line.compare(0, PREFIX_LEN,
"TracerPid:\t") == 0) {
10571 return line.length() > PREFIX_LEN && line[PREFIX_LEN] !=
'0';
10578#elif defined(_MSC_VER)
10579extern "C" __declspec(dllimport)
int __stdcall IsDebuggerPresent();
10581bool isDebuggerActive() {
10582 return IsDebuggerPresent() != 0;
10585#elif defined(__MINGW32__)
10586extern "C" __declspec(dllimport)
int __stdcall IsDebuggerPresent();
10588bool isDebuggerActive() {
10589 return IsDebuggerPresent() != 0;
10594bool isDebuggerActive() {
10604ITransientExpression::~ITransientExpression() =
default;
10606void formatReconstructedExpression(std::ostream& os, std::string
const& lhs,
StringRef op,
10607 std::string
const& rhs) {
10608 if (lhs.size() + rhs.size() < 40 && lhs.find(
'\n') == std::string::npos &&
10609 rhs.find(
'\n') == std::string::npos)
10610 os << lhs <<
" " << op <<
" " << rhs;
10612 os << lhs <<
"\n" << op <<
"\n" << rhs;
10618#include <stdexcept>
10621#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && \
10622 !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
10624void throw_exception(std::exception
const& e) {
10625 Catch::cerr() <<
"Catch will terminate because it needed to throw an exception.\n"
10626 <<
"The message was: " << e.what() <<
'\n';
10632void throw_logic_error(std::string
const& msg) {
10633 throw_exception(std::logic_error(msg));
10637void throw_domain_error(std::string
const& msg) {
10638 throw_exception(std::domain_error(msg));
10642void throw_runtime_error(std::string
const& msg) {
10643 throw_exception(std::runtime_error(msg));
10658std::unique_ptr<EnumInfo> makeEnumInfo(StringRef enumName, StringRef allValueNames,
10659 std::vector<int>
const& values);
10661class EnumValuesRegistry :
public IMutableEnumValuesRegistry {
10663 std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
10665 EnumInfo
const& registerEnum(StringRef enumName, StringRef allEnums,
10666 std::vector<int>
const& values)
override;
10669std::vector<StringRef> parseEnums(StringRef enums);
10682IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
10689StringRef extractInstanceName(StringRef enumInstance) {
10691 size_t name_start = enumInstance.size();
10692 while (name_start > 0 && enumInstance[name_start - 1] !=
':') {
10695 return enumInstance.substr(name_start, enumInstance.size() - name_start);
10699std::vector<StringRef> parseEnums(StringRef enums) {
10700 auto enumValues = splitStringRef(enums,
',');
10701 std::vector<StringRef> parsed;
10702 parsed.reserve(enumValues.size());
10703 for (
auto const& enumValue : enumValues) {
10704 parsed.push_back(trim(extractInstanceName(enumValue)));
10709EnumInfo::~EnumInfo() {}
10711StringRef EnumInfo::lookup(
int value)
const {
10712 for (
auto const& valueToName : m_values) {
10713 if (valueToName.first == value)
10714 return valueToName.second;
10716 return "{** unexpected enum value **}"_sr;
10719std::unique_ptr<EnumInfo> makeEnumInfo(StringRef enumName, StringRef allValueNames,
10720 std::vector<int>
const& values) {
10721 std::unique_ptr<EnumInfo> enumInfo(
new EnumInfo);
10722 enumInfo->m_name = enumName;
10723 enumInfo->m_values.reserve(values.size());
10725 const auto valueNames = Catch::Detail::parseEnums(allValueNames);
10726 assert(valueNames.size() == values.size());
10728 for (
auto value : values)
10729 enumInfo->m_values.emplace_back(value, valueNames[i++]);
10734EnumInfo const& EnumValuesRegistry::registerEnum(StringRef enumName, StringRef allValueNames,
10735 std::vector<int>
const& values) {
10736 m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
10737 return *m_enumInfos.back();
10749ErrnoGuard::ErrnoGuard() : m_oldErrno(errno) {}
10750ErrnoGuard::~ErrnoGuard() {
10751 errno = m_oldErrno;
10767 ~ExceptionTranslatorRegistry();
10768 virtual void registerTranslator(
const IExceptionTranslator* translator);
10769 std::string translateActiveException()
const override;
10770 std::string tryTranslators()
const;
10773 std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
10779#import "Foundation/Foundation.h"
10784ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {}
10787 m_translators.push_back(std::unique_ptr<const IExceptionTranslator>(translator));
10790#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
10791std::string ExceptionTranslatorRegistry::translateActiveException()
const {
10796 return tryTranslators();
10797 }
@catch (NSException* exception) {
10798 return Catch::Detail::stringify([exception description]);
10809 if (std::current_exception() ==
nullptr) {
10810 return "Non C++ exception. Possibly a CLR exception.";
10812 return tryTranslators();
10815 std::rethrow_exception(std::current_exception());
10816 }
catch (std::exception& ex) {
10818 }
catch (std::string& msg) {
10820 }
catch (
const char* msg) {
10823 return "Unknown exception";
10827std::string ExceptionTranslatorRegistry::tryTranslators()
const {
10828 if (m_translators.empty()) {
10829 std::rethrow_exception(std::current_exception());
10831 return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
10836std::string ExceptionTranslatorRegistry::translateActiveException()
const {
10837 CATCH_INTERNAL_ERROR(
"Attempted to translate active exception under "
10838 "CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10841std::string ExceptionTranslatorRegistry::tryTranslators()
const {
10842 CATCH_INTERNAL_ERROR(
"Attempted to use exception translators under "
10843 "CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10851#include <algorithm>
10853#if !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
10859void FatalConditionHandler::engage_platform() {}
10860void FatalConditionHandler::disengage_platform() {}
10861FatalConditionHandler::FatalConditionHandler() =
default;
10862FatalConditionHandler::~FatalConditionHandler() =
default;
10868#if defined(CATCH_CONFIG_WINDOWS_SEH) && defined(CATCH_CONFIG_POSIX_SIGNALS)
10870 "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time"
10873#if defined(CATCH_CONFIG_WINDOWS_SEH) || defined(CATCH_CONFIG_POSIX_SIGNALS)
10877void reportFatal(
char const*
const message) {
10878 Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition(message);
10884constexpr std::size_t minStackSizeForErrors = 32 * 1024;
10889#if defined(CATCH_CONFIG_WINDOWS_SEH)
10901static SignalDefs signalDefs[] = {
10902 {
static_cast<DWORD
>(EXCEPTION_ILLEGAL_INSTRUCTION),
"SIGILL - Illegal instruction signal"},
10903 {
static_cast<DWORD
>(EXCEPTION_STACK_OVERFLOW),
"SIGSEGV - Stack overflow"},
10904 {
static_cast<DWORD
>(EXCEPTION_ACCESS_VIOLATION),
"SIGSEGV - Segmentation violation signal"},
10905 {
static_cast<DWORD
>(EXCEPTION_INT_DIVIDE_BY_ZERO),
"Divide by zero error"},
10908static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
10909 for (
auto const& def : signalDefs) {
10910 if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
10911 reportFatal(def.name);
10916 return EXCEPTION_CONTINUE_SEARCH;
10922static PVOID exceptionHandlerHandle =
nullptr;
10926FatalConditionHandler::FatalConditionHandler() {
10927 ULONG guaranteeSize =
static_cast<ULONG
>(minStackSizeForErrors);
10928 if (!SetThreadStackGuarantee(&guaranteeSize)) {
10931 Catch::cerr() <<
"Failed to reserve piece of stack."
10932 <<
" Stack overflows will not be reported successfully.";
10938FatalConditionHandler::~FatalConditionHandler() =
default;
10940void FatalConditionHandler::engage_platform() {
10942 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
10943 if (!exceptionHandlerHandle) {
10944 CATCH_RUNTIME_ERROR(
"Could not register vectored exception handler");
10948void FatalConditionHandler::disengage_platform() {
10949 if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) {
10950 CATCH_RUNTIME_ERROR(
"Could not unregister vectored exception handler");
10952 exceptionHandlerHandle =
nullptr;
10959#if defined(CATCH_CONFIG_POSIX_SIGNALS)
10970static SignalDefs signalDefs[] = {{SIGINT,
"SIGINT - Terminal interrupt signal"},
10971 {SIGILL,
"SIGILL - Illegal instruction signal"},
10972 {SIGFPE,
"SIGFPE - Floating point error signal"},
10973 {SIGSEGV,
"SIGSEGV - Segmentation violation signal"},
10974 {SIGTERM,
"SIGTERM - Termination request signal"},
10975 {SIGABRT,
"SIGABRT - Abort (abnormal termination) signal"}};
10980#if defined(__GNUC__)
10981#pragma GCC diagnostic push
10982#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
10985static char* altStackMem =
nullptr;
10986static std::size_t altStackSize = 0;
10987static stack_t oldSigStack{};
10988static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
10990static void restorePreviousSignalHandlers() {
10995 for (std::size_t i = 0; i <
sizeof(signalDefs) /
sizeof(SignalDefs); ++i) {
10996 sigaction(signalDefs[i].
id, &oldSigActions[i],
nullptr);
10999 sigaltstack(&oldSigStack,
nullptr);
11002static void handleSignal(
int sig) {
11003 char const* name =
"<unknown signal>";
11004 for (
auto const& def : signalDefs) {
11005 if (sig == def.id) {
11013 restorePreviousSignalHandlers();
11018FatalConditionHandler::FatalConditionHandler() {
11019 assert(!altStackMem &&
"Cannot initialize POSIX signal handler when one already exists");
11020 if (altStackSize == 0) {
11021 altStackSize = std::max(
static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
11023 altStackMem =
new char[altStackSize]();
11026FatalConditionHandler::~FatalConditionHandler() {
11027 delete[] altStackMem;
11030 altStackMem =
nullptr;
11033void FatalConditionHandler::engage_platform() {
11035 sigStack.ss_sp = altStackMem;
11036 sigStack.ss_size = altStackSize;
11037 sigStack.ss_flags = 0;
11038 sigaltstack(&sigStack, &oldSigStack);
11039 struct sigaction sa = {};
11041 sa.sa_handler = handleSignal;
11042 sa.sa_flags = SA_ONSTACK;
11043 for (std::size_t i = 0; i <
sizeof(signalDefs) /
sizeof(SignalDefs); ++i) {
11044 sigaction(signalDefs[i].
id, &sa, &oldSigActions[i]);
11048#if defined(__GNUC__)
11049#pragma GCC diagnostic pop
11052void FatalConditionHandler::disengage_platform() {
11053 restorePreviousSignalHandlers();
11067IGeneratorTracker::~IGeneratorTracker() {}
11069const char* GeneratorException::what() const noexcept {
11073namespace Generators {
11075GeneratorUntypedBase::~GeneratorUntypedBase() {}
11077auto acquireGeneratorTracker(StringRef generatorName, SourceLineInfo
const& lineInfo)
11078 -> IGeneratorTracker& {
11079 return getResultCapture().acquireGeneratorTracker(generatorName, lineInfo);
11088IResultCapture::~IResultCapture() =
default;
11094IConfig::~IConfig() =
default;
11100IExceptionTranslator::~IExceptionTranslator() =
default;
11101IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() =
default;
11107IRegistryHub::~IRegistryHub() =
default;
11108IMutableRegistryHub::~IMutableRegistryHub() =
default;
11117class ListeningReporter :
public IStreamingReporter {
11118 using Reporters = std::vector<IStreamingReporterPtr>;
11119 Reporters m_listeners;
11120 IStreamingReporterPtr m_reporter =
nullptr;
11121 ReporterPreferences m_preferences;
11124 ListeningReporter();
11126 void addListener(IStreamingReporterPtr&& listener);
11127 void addReporter(IStreamingReporterPtr&& reporter);
11130 ReporterPreferences getPreferences()
const override;
11132 void noMatchingTestCases(std::string
const& spec)
override;
11134 void reportInvalidArguments(std::string
const& arg)
override;
11136 static std::set<Verbosity> getSupportedVerbosities();
11138#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
11139 void benchmarkPreparing(std::string
const& name)
override;
11140 void benchmarkStarting(BenchmarkInfo
const& benchmarkInfo)
override;
11141 void benchmarkEnded(BenchmarkStats<>
const& benchmarkStats)
override;
11142 void benchmarkFailed(std::string
const&)
override;
11145 void testRunStarting(TestRunInfo
const& testRunInfo)
override;
11146 void testGroupStarting(GroupInfo
const& groupInfo)
override;
11147 void testCaseStarting(TestCaseInfo
const& testInfo)
override;
11148 void sectionStarting(SectionInfo
const& sectionInfo)
override;
11149 void assertionStarting(AssertionInfo
const& assertionInfo)
override;
11152 bool assertionEnded(AssertionStats
const& assertionStats)
override;
11153 void sectionEnded(SectionStats
const& sectionStats)
override;
11154 void testCaseEnded(TestCaseStats
const& testCaseStats)
override;
11155 void testGroupEnded(TestGroupStats
const& testGroupStats)
override;
11156 void testRunEnded(TestRunStats
const& testRunStats)
override;
11158 void skipTest(TestCaseInfo
const& testInfo)
override;
11159 bool isMulti()
const override;
11167ReporterConfig::ReporterConfig(IConfigPtr
const& _fullConfig)
11168 : m_stream(&_fullConfig->stream()), m_fullConfig(_fullConfig) {}
11170ReporterConfig::ReporterConfig(IConfigPtr
const& _fullConfig, std::ostream& _stream)
11171 : m_stream(&_stream), m_fullConfig(_fullConfig) {}
11173std::ostream& ReporterConfig::stream()
const {
11176IConfigPtr ReporterConfig::fullConfig()
const {
11177 return m_fullConfig;
11180TestRunInfo::TestRunInfo(std::string
const& _name) : name(_name) {}
11182GroupInfo::GroupInfo(std::string
const& _name, std::size_t _groupIndex, std::size_t _groupsCount)
11183 : name(_name), groupIndex(_groupIndex), groupsCounts(_groupsCount) {}
11185AssertionStats::AssertionStats(AssertionResult
const& _assertionResult,
11186 std::vector<MessageInfo>
const& _infoMessages,
Totals const& _totals)
11187 : assertionResult(_assertionResult), infoMessages(_infoMessages), totals(_totals) {
11188 assertionResult.m_resultData.lazyExpression.m_transientExpression =
11189 _assertionResult.m_resultData.lazyExpression.m_transientExpression;
11191 if (assertionResult.hasMessage()) {
11194 MessageBuilder builder(assertionResult.getTestMacroName(), assertionResult.getSourceInfo(),
11195 assertionResult.getResultType());
11196 builder << assertionResult.getMessage();
11197 builder.m_info.message = builder.m_stream.str();
11199 infoMessages.push_back(builder.m_info);
11203AssertionStats::~AssertionStats() =
default;
11205SectionStats::SectionStats(
SectionInfo const& _sectionInfo,
Counts const& _assertions,
11206 double _durationInSeconds,
bool _missingAssertions)
11207 : sectionInfo(_sectionInfo), assertions(_assertions), durationInSeconds(_durationInSeconds),
11208 missingAssertions(_missingAssertions) {}
11210SectionStats::~SectionStats() =
default;
11213 std::string
const& _stdOut, std::string
const& _stdErr,
bool _aborting)
11214 : testInfo(_testInfo), totals(_totals), stdOut(_stdOut), stdErr(_stdErr), aborting(_aborting) {}
11216TestCaseStats::~TestCaseStats() =
default;
11218TestGroupStats::TestGroupStats(GroupInfo
const& _groupInfo,
Totals const& _totals,
bool _aborting)
11219 : groupInfo(_groupInfo), totals(_totals), aborting(_aborting) {}
11221TestGroupStats::TestGroupStats(GroupInfo
const& _groupInfo)
11222 : groupInfo(_groupInfo), aborting(false) {}
11224TestGroupStats::~TestGroupStats() =
default;
11226TestRunStats::TestRunStats(TestRunInfo
const& _runInfo,
Totals const& _totals,
bool _aborting)
11227 : runInfo(_runInfo), totals(_totals), aborting(_aborting) {}
11229TestRunStats::~TestRunStats() =
default;
11231void IStreamingReporter::fatalErrorEncountered(
StringRef) {}
11232bool IStreamingReporter::isMulti()
const {
11236IReporterFactory::~IReporterFactory() =
default;
11237IReporterRegistry::~IReporterRegistry() =
default;
11244IRunner::~IRunner() =
default;
11250ITestInvoker::~ITestInvoker() =
default;
11251ITestCaseRegistry::~ITestCaseRegistry() =
default;
11256#ifdef CATCH_CONFIG_WINDOWS_CRTDBG
11261LeakDetector::LeakDetector() {
11262 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
11263 flag |= _CRTDBG_LEAK_CHECK_DF;
11264 flag |= _CRTDBG_ALLOC_MEM_DF;
11265 _CrtSetDbgFlag(flag);
11266 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
11267 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
11269 _CrtSetBreakAlloc(-1);
11275Catch::LeakDetector::LeakDetector() {}
11279Catch::LeakDetector::~LeakDetector() {
11291std::size_t listTests(Config
const& config);
11293std::size_t listTestsNamesOnly(Config
const& config);
11296 void add(std::string
const& spelling);
11297 std::string all()
const;
11299 std::set<std::string> spellings;
11300 std::size_t count = 0;
11303std::size_t listTags(Config
const& config);
11305std::size_t listReporters();
11315using namespace clara::TextFlow;
11319#include <algorithm>
11325std::size_t listTests(Config
const& config) {
11326 TestSpec
const& testSpec = config.testSpec();
11327 if (config.hasTestFilters())
11328 Catch::cout() <<
"Matching test cases:\n";
11330 Catch::cout() <<
"All available test cases:\n";
11333 auto matchedTestCases = filterTests(getAllTestCasesSorted(config), testSpec, config);
11334 for (
auto const& testCaseInfo : matchedTestCases) {
11335 Colour::Code colour = testCaseInfo.isHidden() ? Colour::SecondaryText : Colour::None;
11336 Colour colourGuard(colour);
11338 Catch::cout() << Column(testCaseInfo.name).initialIndent(2).indent(4) <<
"\n";
11339 if (config.verbosity() >= Verbosity::High) {
11340 Catch::cout() << Column(Catch::Detail::stringify(testCaseInfo.lineInfo)).indent(4)
11342 std::string description = testCaseInfo.description;
11343 if (description.empty())
11344 description =
"(NO DESCRIPTION)";
11345 Catch::cout() << Column(description).indent(4) << std::endl;
11347 if (!testCaseInfo.tags.empty())
11348 Catch::cout() << Column(testCaseInfo.tagsAsString()).indent(6) <<
"\n";
11351 if (!config.hasTestFilters())
11352 Catch::cout() <<
pluralise(matchedTestCases.size(),
"test case") <<
'\n' << std::endl;
11354 Catch::cout() <<
pluralise(matchedTestCases.size(),
"matching test case") <<
'\n'
11356 return matchedTestCases.size();
11359std::size_t listTestsNamesOnly(Config
const& config) {
11360 TestSpec
const& testSpec = config.testSpec();
11361 std::size_t matchedTests = 0;
11362 std::vector<TestCase> matchedTestCases =
11363 filterTests(getAllTestCasesSorted(config), testSpec, config);
11364 for (
auto const& testCaseInfo : matchedTestCases) {
11366 if (startsWith(testCaseInfo.name,
'#'))
11367 Catch::cout() <<
'"' << testCaseInfo.name <<
'"';
11369 Catch::cout() << testCaseInfo.name;
11370 if (config.verbosity() >= Verbosity::High)
11371 Catch::cout() <<
"\t@" << testCaseInfo.lineInfo;
11372 Catch::cout() << std::endl;
11374 return matchedTests;
11377void TagInfo::add(std::string
const& spelling) {
11379 spellings.insert(spelling);
11382std::string TagInfo::all()
const {
11384 for (
auto const& spelling : spellings) {
11386 size += spelling.size() + 2;
11391 for (
auto const& spelling : spellings) {
11399std::size_t listTags(Config
const& config) {
11400 TestSpec
const& testSpec = config.testSpec();
11401 if (config.hasTestFilters())
11402 Catch::cout() <<
"Tags for matching test cases:\n";
11404 Catch::cout() <<
"All available tags:\n";
11407 std::map<std::string, TagInfo> tagCounts;
11409 std::vector<TestCase> matchedTestCases =
11410 filterTests(getAllTestCasesSorted(config), testSpec, config);
11411 for (
auto const& testCase : matchedTestCases) {
11412 for (
auto const& tagName : testCase.getTestCaseInfo().tags) {
11413 std::string lcaseTagName = toLower(tagName);
11414 auto countIt = tagCounts.find(lcaseTagName);
11415 if (countIt == tagCounts.end())
11416 countIt = tagCounts.insert(std::make_pair(lcaseTagName, TagInfo())).first;
11417 countIt->second.add(tagName);
11421 for (
auto const& tagCount : tagCounts) {
11423 rss <<
" " << std::setw(2) << tagCount.second.count <<
" ";
11424 auto str = rss.str();
11425 auto wrapper = Column(tagCount.second.all())
11427 .indent(str.size())
11428 .width(CATCH_CONFIG_CONSOLE_WIDTH - 10);
11429 Catch::cout() << str << wrapper <<
'\n';
11431 Catch::cout() <<
pluralise(tagCounts.size(),
"tag") <<
'\n' << std::endl;
11432 return tagCounts.size();
11435std::size_t listReporters() {
11436 Catch::cout() <<
"Available reporters:\n";
11437 IReporterRegistry::FactoryMap
const& factories =
11438 getRegistryHub().getReporterRegistry().getFactories();
11439 std::size_t maxNameLen = 0;
11440 for (
auto const& factoryKvp : factories)
11441 maxNameLen = (std::max)(maxNameLen, factoryKvp.first.size());
11443 for (
auto const& factoryKvp : factories) {
11444 Catch::cout() << Column(factoryKvp.first +
":").indent(2).width(5 + maxNameLen) +
11445 Column(factoryKvp.second->getDescription())
11448 .width(CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen - 8)
11451 Catch::cout() << std::endl;
11452 return factories.size();
11457 getCurrentMutableContext().setConfig(config);
11458 if (config->listTests())
11459 listedCount = listedCount.valueOr(0) + listTests(*config);
11460 if (config->listTestNamesOnly())
11461 listedCount = listedCount.valueOr(0) + listTestsNamesOnly(*config);
11462 if (config->listTags())
11463 listedCount = listedCount.valueOr(0) + listTags(*config);
11464 if (config->listReporters())
11465 listedCount = listedCount.valueOr(0) + listReporters();
11466 return listedCount;
11474namespace Matchers {
11477std::string MatcherUntypedBase::toString()
const {
11478 if (m_cachedToString.empty())
11479 m_cachedToString = describe();
11480 return m_cachedToString;
11483MatcherUntypedBase::~MatcherUntypedBase() =
default;
11488using namespace Matchers;
11496namespace Matchers {
11497namespace Exception {
11499bool ExceptionMessageMatcher::match(std::exception
const& ex)
const {
11500 return ex.what() == m_message;
11503std::string ExceptionMessageMatcher::describe()
const {
11504 return "exception message matches \"" + m_message + "\"";
11521bool isnan(
float f);
11522bool isnan(
double d);
11531template <
typename T> std::string to_string(T
const& t) {
11532#if defined(CATCH_CONFIG_CPP11_TO_STRING)
11533 return std::to_string(t);
11543#include <algorithm>
11551#include <type_traits>
11556int32_t convert(
float f) {
11557 static_assert(
sizeof(float) ==
sizeof(int32_t),
"Important ULP matcher assumption violated");
11559 std::memcpy(&i, &f,
sizeof(f));
11563int64_t convert(
double d) {
11564 static_assert(
sizeof(double) ==
sizeof(int64_t),
"Important ULP matcher assumption violated");
11566 std::memcpy(&i, &d,
sizeof(d));
11570template <
typename FP>
bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
11573 if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11577 auto lc = convert(lhs);
11578 auto rc = convert(rhs);
11580 if ((lc < 0) != (rc < 0)) {
11586 auto ulpDiff = std::abs(
static_cast<FP
>(lc - rc));
11587 return static_cast<uint64_t
>(ulpDiff) <= maxUlpDiff;
11590#if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11592float nextafter(
float x,
float y) {
11593 return ::nextafterf(x, y);
11596double nextafter(
double x,
double y) {
11597 return ::nextafter(x, y);
11602template <
typename FP> FP step(FP start, FP direction, uint64_t steps) {
11603 for (uint64_t i = 0; i < steps; ++i) {
11604#if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11605 start = Catch::nextafter(start, direction);
11607 start = std::nextafter(start, direction);
11615bool marginComparison(
double lhs,
double rhs,
double margin) {
11616 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
11619template <
typename FloatingPo
int>
void write(std::ostream& out, FloatingPoint num) {
11620 out << std::scientific
11621 << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1) << num;
11626namespace Matchers {
11627namespace Floating {
11629enum class FloatingPointKind : uint8_t { Float, Double };
11631WithinAbsMatcher::WithinAbsMatcher(
double target,
double margin)
11632 : m_target{target}, m_margin{margin} {
11633 CATCH_ENFORCE(margin >= 0,
11634 "Invalid margin: " << margin <<
'.' <<
" Margin has to be non-negative.");
11639bool WithinAbsMatcher::match(
double const& matchee)
const {
11640 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11643std::string WithinAbsMatcher::describe()
const {
11644 return "is within " + ::Catch::Detail::stringify(m_margin) + " of " +
11645 ::Catch::Detail::stringify(m_target);
11648WithinUlpsMatcher::WithinUlpsMatcher(
double target, uint64_t ulps, FloatingPointKind baseType)
11649 : m_target{target}, m_ulps{ulps}, m_type{baseType} {
11650 CATCH_ENFORCE(m_type == FloatingPointKind::Double ||
11651 m_ulps < (std::numeric_limits<uint32_t>::max)(),
11652 "Provided ULP is impossibly large for a float comparison.");
11655#if defined(__clang__)
11656#pragma clang diagnostic push
11658#pragma clang diagnostic ignored "-Wunreachable-code"
11661bool WithinUlpsMatcher::match(
double const& matchee)
const {
11663 case FloatingPointKind::Float:
11664 return almostEqualUlps<float>(
static_cast<float>(matchee),
static_cast<float>(m_target),
11666 case FloatingPointKind::Double:
11667 return almostEqualUlps<double>(matchee, m_target, m_ulps);
11669 CATCH_INTERNAL_ERROR(
"Unknown FloatingPointKind value");
11673#if defined(__clang__)
11674#pragma clang diagnostic pop
11677std::string WithinUlpsMatcher::describe()
const {
11678 std::stringstream ret;
11680 ret <<
"is within " << m_ulps <<
" ULPs of ";
11682 if (m_type == FloatingPointKind::Float) {
11683 write(ret,
static_cast<float>(m_target));
11686 write(ret, m_target);
11690 if (m_type == FloatingPointKind::Double) {
11691 write(ret, step(m_target,
static_cast<double>(-INFINITY), m_ulps));
11693 write(ret, step(m_target,
static_cast<double>(INFINITY), m_ulps));
11696 write(ret, step(
static_cast<float>(m_target),
static_cast<float>(-INFINITY), m_ulps));
11698 write(ret, step(
static_cast<float>(m_target),
static_cast<float>(INFINITY), m_ulps));
11705WithinRelMatcher::WithinRelMatcher(
double target,
double epsilon)
11706 : m_target(target), m_epsilon(epsilon) {
11707 CATCH_ENFORCE(m_epsilon >= 0.,
"Relative comparison with epsilon < 0 does not make sense.");
11708 CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.
");
11711bool WithinRelMatcher::match(double const& matchee) const {
11712 const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
11713 return marginComparison(matchee, m_target, std::isinf(relMargin) ? 0 : relMargin);
11716std::string WithinRelMatcher::describe() const {
11717 Catch::ReusableStringStream sstr;
11718 sstr << "and
" << m_target << " are within
" << m_epsilon * 100. << "% of each other
";
11722} // namespace Floating
11724Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
11725 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
11728Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
11729 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
11732Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
11733 return Floating::WithinAbsMatcher(target, margin);
11736Floating::WithinRelMatcher WithinRel(double target, double eps) {
11737 return Floating::WithinRelMatcher(target, eps);
11740Floating::WithinRelMatcher WithinRel(double target) {
11741 return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
11744Floating::WithinRelMatcher WithinRel(float target, float eps) {
11745 return Floating::WithinRelMatcher(target, eps);
11748Floating::WithinRelMatcher WithinRel(float target) {
11749 return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
11752} // namespace Matchers
11753} // namespace Catch
11754// end catch_matchers_floating.cpp
11755// start catch_matchers_generic.cpp
11757std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
11758 if (desc.empty()) {
11759 return "matches undescribed predicate
";
11761 return "matches predicate: \
"" + desc +
'"';
11770namespace Matchers {
11772namespace StdString {
11774CasedString::CasedString(std::string
const& str, CaseSensitive::Choice caseSensitivity)
11775 : m_caseSensitivity(caseSensitivity), m_str(adjustString(str)) {}
11776std::string CasedString::adjustString(std::string
const& str)
const {
11777 return m_caseSensitivity == CaseSensitive::No ? toLower(str) : str;
11779std::string CasedString::caseSensitivitySuffix()
const {
11780 return m_caseSensitivity == CaseSensitive::No ?
" (case insensitive)" : std::string();
11783StringMatcherBase::StringMatcherBase(std::string
const& operation, CasedString
const& comparator)
11784 : m_comparator(comparator), m_operation(operation) {}
11786std::string StringMatcherBase::describe()
const {
11787 std::string description;
11788 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
11789 m_comparator.caseSensitivitySuffix().size());
11790 description += m_operation;
11791 description += ": \"";
11792 description += m_comparator.m_str;
11793 description += "\"";
11794 description += m_comparator.caseSensitivitySuffix();
11795 return description;
11798EqualsMatcher::EqualsMatcher(CasedString
const& comparator)
11799 : StringMatcherBase(
"equals", comparator) {}
11801bool EqualsMatcher::match(std::string
const& source)
const {
11802 return m_comparator.adjustString(source) == m_comparator.m_str;
11805ContainsMatcher::ContainsMatcher(CasedString
const& comparator)
11806 : StringMatcherBase(
"contains", comparator) {}
11808bool ContainsMatcher::match(std::string
const& source)
const {
11809 return contains(m_comparator.adjustString(source), m_comparator.m_str);
11812StartsWithMatcher::StartsWithMatcher(CasedString
const& comparator)
11813 : StringMatcherBase(
"starts with", comparator) {}
11815bool StartsWithMatcher::match(std::string
const& source)
const {
11816 return startsWith(m_comparator.adjustString(source), m_comparator.m_str);
11819EndsWithMatcher::EndsWithMatcher(CasedString
const& comparator)
11820 : StringMatcherBase(
"ends with", comparator) {}
11822bool EndsWithMatcher::match(std::string
const& source)
const {
11823 return endsWith(m_comparator.adjustString(source), m_comparator.m_str);
11826RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity)
11827 : m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
11829bool RegexMatcher::match(std::string
const& matchee)
const {
11830 auto flags = std::regex::ECMAScript;
11831 if (m_caseSensitivity == CaseSensitive::Choice::No) {
11832 flags |= std::regex::icase;
11834 auto reg = std::regex(m_regex, flags);
11835 return std::regex_match(matchee, reg);
11838std::string RegexMatcher::describe()
const {
11839 return "matches " + ::Catch::Detail::stringify(m_regex) +
11840 ((m_caseSensitivity ==
CaseSensitive::Choice::Yes) ? " case sensitively"
11841 : " case insensitively");
11846StdString::EqualsMatcher Equals(std::string
const& str, CaseSensitive::Choice caseSensitivity) {
11847 return StdString::EqualsMatcher(StdString::CasedString(str, caseSensitivity));
11849StdString::ContainsMatcher Contains(std::string
const& str, CaseSensitive::Choice caseSensitivity) {
11850 return StdString::ContainsMatcher(StdString::CasedString(str, caseSensitivity));
11852StdString::EndsWithMatcher EndsWith(std::string
const& str, CaseSensitive::Choice caseSensitivity) {
11853 return StdString::EndsWithMatcher(StdString::CasedString(str, caseSensitivity));
11855StdString::StartsWithMatcher StartsWith(std::string
const& str,
11856 CaseSensitive::Choice caseSensitivity) {
11857 return StdString::StartsWithMatcher(StdString::CasedString(str, caseSensitivity));
11860StdString::RegexMatcher Matches(std::string
const& regex, CaseSensitive::Choice caseSensitivity) {
11861 return StdString::RegexMatcher(regex, caseSensitivity);
11872bool uncaught_exceptions();
11882 ResultWas::OfType _type)
11883 : macroName(_macroName), lineInfo(_lineInfo), type(_type), sequence(++globalCount) {}
11885bool MessageInfo::operator==(
MessageInfo const& other)
const {
11886 return sequence == other.sequence;
11889bool MessageInfo::operator<(
MessageInfo const& other)
const {
11890 return sequence < other.sequence;
11894unsigned int MessageInfo::globalCount = 0;
11899 ResultWas::OfType type)
11900 : m_info(macroName, lineInfo, type) {}
11904ScopedMessage::ScopedMessage(
MessageBuilder const& builder) : m_info(builder.m_info), m_moved() {
11905 m_info.message = builder.m_stream.str();
11906 getResultCapture().pushScopedMessage(m_info);
11909ScopedMessage::ScopedMessage(
ScopedMessage&& old) : m_info(old.m_info), m_moved() {
11910 old.m_moved =
true;
11913ScopedMessage::~ScopedMessage() {
11914 if (!uncaught_exceptions() && !m_moved) {
11915 getResultCapture().popScopedMessage(m_info);
11920 ResultWas::OfType resultType,
StringRef names) {
11921 auto trimmed = [&](
size_t start,
size_t end) {
11922 while (names[start] ==
',' || isspace(
static_cast<unsigned char>(names[start]))) {
11925 while (names[end] ==
',' || isspace(
static_cast<unsigned char>(names[end]))) {
11928 return names.substr(start, end - start + 1);
11930 auto skipq = [&](
size_t start,
char quote) {
11931 for (
auto i = start + 1; i < names.size(); ++i) {
11932 if (names[i] == quote)
11934 if (names[i] ==
'\\')
11937 CATCH_INTERNAL_ERROR(
"CAPTURE parsing encountered unmatched quote");
11941 std::stack<char> openings;
11942 for (
size_t pos = 0; pos < names.size(); ++pos) {
11943 char c = names[pos];
11961 pos = skipq(pos, c);
11964 if (start != pos && openings.empty()) {
11965 m_messages.emplace_back(macroName, lineInfo, resultType);
11966 m_messages.back().message =
static_cast<std::string
>(trimmed(start, pos));
11967 m_messages.back().message += " := ";
11972 assert(openings.empty() &&
"Mismatched openings");
11973 m_messages.emplace_back(macroName, lineInfo, resultType);
11974 m_messages.back().message =
static_cast<std::string
>(trimmed(start, names.size() - 1));
11975 m_messages.back().message += " := ";
11977Capturer::~Capturer() {
11978 if (!uncaught_exceptions()) {
11979 assert(m_captured == m_messages.size());
11980 for (
size_t i = 0; i < m_captured; ++i)
11981 m_resultCapture.popScopedMessage(m_messages[i]);
11985void Capturer::captureValue(
size_t index, std::string
const& value) {
11986 assert(index < m_messages.size());
11987 m_messages[index].message += value;
11988 m_resultCapture.pushScopedMessage(m_messages[index]);
11997#ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11998#define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
12006class RedirectedStream {
12007 std::ostream& m_originalStream;
12008 std::ostream& m_redirectionStream;
12009 std::streambuf* m_prevBuf;
12012 RedirectedStream(std::ostream& originalStream, std::ostream& redirectionStream);
12013 ~RedirectedStream();
12016class RedirectedStdOut {
12017 ReusableStringStream m_rss;
12018 RedirectedStream m_cout;
12021 RedirectedStdOut();
12022 auto str() const -> std::
string;
12028class RedirectedStdErr {
12029 ReusableStringStream m_rss;
12030 RedirectedStream m_cerr;
12031 RedirectedStream m_clog;
12034 RedirectedStdErr();
12035 auto str() const -> std::
string;
12038class RedirectedStreams {
12040 RedirectedStreams(RedirectedStreams
const&) =
delete;
12041 RedirectedStreams& operator=(RedirectedStreams
const&) =
delete;
12042 RedirectedStreams(RedirectedStreams&&) =
delete;
12043 RedirectedStreams& operator=(RedirectedStreams&&) =
delete;
12045 RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
12046 ~RedirectedStreams();
12049 std::string& m_redirectedCout;
12050 std::string& m_redirectedCerr;
12051 RedirectedStdOut m_redirectedStdOut;
12052 RedirectedStdErr m_redirectedStdErr;
12055#if defined(CATCH_CONFIG_NEW_CAPTURE)
12063 TempFile(TempFile
const&) =
delete;
12064 TempFile& operator=(TempFile
const&) =
delete;
12065 TempFile(TempFile&&) =
delete;
12066 TempFile& operator=(TempFile&&) =
delete;
12071 std::FILE* getFile();
12072 std::string getContents();
12075 std::FILE* m_file =
nullptr;
12076#if defined(_MSC_VER)
12077 char m_buffer[L_tmpnam] = {0};
12081class OutputRedirect {
12083 OutputRedirect(OutputRedirect
const&) =
delete;
12084 OutputRedirect& operator=(OutputRedirect
const&) =
delete;
12085 OutputRedirect(OutputRedirect&&) =
delete;
12086 OutputRedirect& operator=(OutputRedirect&&) =
delete;
12088 OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
12092 int m_originalStdout = -1;
12093 int m_originalStderr = -1;
12094 TempFile m_stdoutFile;
12095 TempFile m_stderrFile;
12096 std::string& m_stdoutDest;
12097 std::string& m_stderrDest;
12110#include <stdexcept>
12112#if defined(CATCH_CONFIG_NEW_CAPTURE)
12113#if defined(_MSC_VER)
12117#define fileno _fileno
12125RedirectedStream::RedirectedStream(std::ostream& originalStream, std::ostream& redirectionStream)
12126 : m_originalStream(originalStream), m_redirectionStream(redirectionStream),
12127 m_prevBuf(m_originalStream.rdbuf()) {
12128 m_originalStream.rdbuf(m_redirectionStream.rdbuf());
12131RedirectedStream::~RedirectedStream() {
12132 m_originalStream.rdbuf(m_prevBuf);
12135RedirectedStdOut::RedirectedStdOut() : m_cout(Catch::cout(), m_rss.get()) {}
12136auto RedirectedStdOut::str() const -> std::
string {
12137 return m_rss.str();
12140RedirectedStdErr::RedirectedStdErr()
12141 : m_cerr(Catch::cerr(), m_rss.get()), m_clog(Catch::clog(), m_rss.get()) {}
12142auto RedirectedStdErr::str() const -> std::
string {
12143 return m_rss.str();
12146RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
12147 : m_redirectedCout(redirectedCout), m_redirectedCerr(redirectedCerr) {}
12149RedirectedStreams::~RedirectedStreams() {
12150 m_redirectedCout += m_redirectedStdOut.str();
12151 m_redirectedCerr += m_redirectedStdErr.str();
12154#if defined(CATCH_CONFIG_NEW_CAPTURE)
12156#if defined(_MSC_VER)
12157TempFile::TempFile() {
12158 if (tmpnam_s(m_buffer)) {
12159 CATCH_RUNTIME_ERROR(
"Could not get a temp filename");
12161 if (fopen_s(&m_file, m_buffer,
"w+")) {
12163 if (strerror_s(buffer, errno)) {
12164 CATCH_RUNTIME_ERROR(
"Could not translate errno to a string");
12166 CATCH_RUNTIME_ERROR(
"Could not open the temp file: '" << m_buffer
12167 <<
"' because: " << buffer);
12171TempFile::TempFile() {
12172 m_file = std::tmpfile();
12174 CATCH_RUNTIME_ERROR(
"Could not create a temp file.");
12180TempFile::~TempFile() {
12182 std::fclose(m_file);
12185#if defined(_MSC_VER)
12186 std::remove(m_buffer);
12190FILE* TempFile::getFile() {
12194std::string TempFile::getContents() {
12195 std::stringstream sstr;
12196 char buffer[100] = {};
12197 std::rewind(m_file);
12198 while (std::fgets(buffer,
sizeof(buffer), m_file)) {
12204OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest)
12205 : m_originalStdout(dup(1)), m_originalStderr(dup(2)), m_stdoutDest(stdout_dest),
12206 m_stderrDest(stderr_dest) {
12207 dup2(fileno(m_stdoutFile.getFile()), 1);
12208 dup2(fileno(m_stderrFile.getFile()), 2);
12211OutputRedirect::~OutputRedirect() {
12212 Catch::cout() << std::flush;
12216 Catch::cerr() << std::flush;
12217 Catch::clog() << std::flush;
12220 dup2(m_originalStdout, 1);
12221 dup2(m_originalStderr, 2);
12223 m_stdoutDest += m_stdoutFile.getContents();
12224 m_stderrDest += m_stderrFile.getContents();
12231#if defined(CATCH_CONFIG_NEW_CAPTURE)
12232#if defined(_MSC_VER)
12245#if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
12246bool isnan(
float f) {
12247 return std::isnan(f);
12249bool isnan(
double d) {
12250 return std::isnan(d);
12254bool isnan(
float f) {
12255 return std::_isnan(f);
12257bool isnan(
double d) {
12258 return std::_isnan(d);
12270#if defined(_MSC_VER)
12271#pragma warning(push)
12272#pragma warning(disable : 4146)
12275uint32_t rotate_right(uint32_t val, uint32_t count) {
12276 const uint32_t mask = 31;
12278 return (val >> count) | (val << (-count & mask));
12281#if defined(_MSC_VER)
12282#pragma warning(pop)
12287SimplePcg32::SimplePcg32(result_type seed_) {
12291void SimplePcg32::seed(result_type seed_) {
12298void SimplePcg32::discard(uint64_t skip) {
12301 for (uint64_t s = 0; s < skip; ++s) {
12302 static_cast<void>((*this)());
12306SimplePcg32::result_type SimplePcg32::operator()() {
12308 const uint32_t xorshifted =
static_cast<uint32_t
>(((m_state >> 18u) ^ m_state) >> 27u);
12309 const auto output = rotate_right(xorshifted, m_state >> 59u);
12312 m_state = m_state * 6364136223846793005ULL + s_inc;
12317bool operator==(SimplePcg32
const& lhs, SimplePcg32
const& rhs) {
12318 return lhs.m_state == rhs.m_state;
12321bool operator!=(SimplePcg32
const& lhs, SimplePcg32
const& rhs) {
12322 return lhs.m_state != rhs.m_state;
12330#include <algorithm>
12340std::vector<TestCase> sortTests(
IConfig const& config,
12341 std::vector<TestCase>
const& unsortedTestCases);
12344bool matchTest(
TestCase const& testCase, TestSpec
const& testSpec,
IConfig const& config);
12346void enforceNoDuplicateTestCases(std::vector<TestCase>
const& functions);
12348std::vector<TestCase> filterTests(std::vector<TestCase>
const& testCases, TestSpec
const& testSpec,
12350std::vector<TestCase>
const& getAllTestCasesSorted(
IConfig const& config);
12354 virtual ~TestRegistry() =
default;
12356 virtual void registerTest(TestCase
const& testCase);
12358 std::vector<TestCase>
const& getAllTests()
const override;
12359 std::vector<TestCase>
const& getAllTestsSorted(IConfig
const& config)
const override;
12362 std::vector<TestCase> m_functions;
12363 mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
12364 mutable std::vector<TestCase> m_sortedFunctions;
12365 std::size_t m_unnamedCount = 0;
12366 std::ios_base::Init m_ostreamInit;
12372 void (*m_testAsFunction)();
12375 TestInvokerAsFunction(
void (*testAsFunction)()) noexcept;
12377 void invoke() const override;
12380std::
string extractClassName(StringRef const& classOrQualifiedMethodName);
12393class ReporterRegistry :
public IReporterRegistry {
12396 ~ReporterRegistry()
override;
12398 IStreamingReporterPtr create(std::string
const& name, IConfigPtr
const& config)
const override;
12400 void registerReporter(std::string
const& name, IReporterFactoryPtr
const& factory);
12401 void registerListener(IReporterFactoryPtr
const& factory);
12403 FactoryMap
const& getFactories()
const override;
12404 Listeners
const& getListeners()
const override;
12407 FactoryMap m_factories;
12408 Listeners m_listeners;
12422 TagAlias(std::string
const& _tag, SourceLineInfo _lineInfo);
12425 SourceLineInfo lineInfo;
12435class TagAliasRegistry :
public ITagAliasRegistry {
12437 ~TagAliasRegistry()
override;
12438 TagAlias
const* find(std::string
const& alias)
const override;
12439 std::string expandAliases(std::string
const& unexpandedTestSpec)
const override;
12440 void add(std::string
const& alias, std::string
const& tag, SourceLineInfo
const& lineInfo);
12443 std::map<std::string, TagAlias> m_registry;
12451#include <exception>
12456class StartupExceptionRegistry {
12457#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12459 void add(std::exception_ptr
const& exception)
noexcept;
12460 std::vector<std::exception_ptr>
const& getExceptions() const noexcept;
12463 std::vector<std::exception_ptr> m_exceptions;
12475 virtual ~ISingleton();
12478void addSingleton(ISingleton* singleton);
12479void cleanupSingletons();
12481template <
typename SingletonImplT,
typename InterfaceT = SingletonImplT,
12482 typename MutableInterfaceT = InterfaceT>
12483class Singleton : SingletonImplT,
public ISingleton {
12485 static auto getInternal() -> Singleton* {
12486 static Singleton* s_instance =
nullptr;
12488 s_instance =
new Singleton;
12489 addSingleton(s_instance);
12495 static auto get() -> InterfaceT
const& {
return *getInternal(); }
12496 static auto getMutable() -> MutableInterfaceT& {
return *getInternal(); }
12506class RegistryHub :
public IRegistryHub,
public IMutableRegistryHub,
private NonCopyable {
12509 RegistryHub() =
default;
12510 IReporterRegistry
const& getReporterRegistry()
const override {
return m_reporterRegistry; }
12511 ITestCaseRegistry
const& getTestCaseRegistry()
const override {
return m_testCaseRegistry; }
12512 IExceptionTranslatorRegistry
const& getExceptionTranslatorRegistry()
const override {
12513 return m_exceptionTranslatorRegistry;
12515 ITagAliasRegistry
const& getTagAliasRegistry()
const override {
return m_tagAliasRegistry; }
12516 StartupExceptionRegistry
const& getStartupExceptionRegistry()
const override {
12517 return m_exceptionRegistry;
12521 void registerReporter(std::string
const& name, IReporterFactoryPtr
const& factory)
override {
12522 m_reporterRegistry.registerReporter(name, factory);
12524 void registerListener(IReporterFactoryPtr
const& factory)
override {
12525 m_reporterRegistry.registerListener(factory);
12527 void registerTest(TestCase
const& testInfo)
override {
12528 m_testCaseRegistry.registerTest(testInfo);
12530 void registerTranslator(
const IExceptionTranslator* translator)
override {
12531 m_exceptionTranslatorRegistry.registerTranslator(translator);
12533 void registerTagAlias(std::string
const& alias, std::string
const& tag,
12534 SourceLineInfo
const& lineInfo)
override {
12535 m_tagAliasRegistry.add(alias, tag, lineInfo);
12537 void registerStartupException() noexcept
override {
12538#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12539 m_exceptionRegistry.add(std::current_exception());
12541 CATCH_INTERNAL_ERROR(
"Attempted to register active exception under "
12542 "CATCH_CONFIG_DISABLE_EXCEPTIONS!");
12545 IMutableEnumValuesRegistry& getMutableEnumValuesRegistry()
override {
12546 return m_enumValuesRegistry;
12550 TestRegistry m_testCaseRegistry;
12551 ReporterRegistry m_reporterRegistry;
12552 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
12553 TagAliasRegistry m_tagAliasRegistry;
12554 StartupExceptionRegistry m_exceptionRegistry;
12555 Detail::EnumValuesRegistry m_enumValuesRegistry;
12559using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
12561IRegistryHub
const& getRegistryHub() {
12562 return RegistryHubSingleton::get();
12564IMutableRegistryHub& getMutableRegistryHub() {
12565 return RegistryHubSingleton::getMutable();
12568 cleanupSingletons();
12571std::string translateActiveException() {
12572 return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
12581ReporterRegistry::~ReporterRegistry() =
default;
12583IStreamingReporterPtr ReporterRegistry::create(std::string
const& name,
12584 IConfigPtr
const& config)
const {
12585 auto it = m_factories.find(name);
12586 if (it == m_factories.end())
12588 return it->second->create(ReporterConfig(config));
12591void ReporterRegistry::registerReporter(std::string
const& name,
12592 IReporterFactoryPtr
const& factory) {
12593 m_factories.emplace(name, factory);
12595void ReporterRegistry::registerListener(IReporterFactoryPtr
const& factory) {
12596 m_listeners.push_back(factory);
12599IReporterRegistry::FactoryMap
const& ReporterRegistry::getFactories()
const {
12600 return m_factories;
12602IReporterRegistry::Listeners
const& ReporterRegistry::getListeners()
const {
12603 return m_listeners;
12612bool isOk(ResultWas::OfType resultType) {
12613 return (resultType & ResultWas::FailureBit) == 0;
12615bool isJustInfo(
int flags) {
12616 return flags == ResultWas::Info;
12619ResultDisposition::Flags operator|(ResultDisposition::Flags lhs, ResultDisposition::Flags rhs) {
12620 return static_cast<ResultDisposition::Flags
>(
static_cast<int>(lhs) |
static_cast<int>(rhs));
12623bool shouldContinueOnFailure(
int flags) {
12624 return (flags & ResultDisposition::ContinueOnFailure) != 0;
12626bool shouldSuppressFailure(
int flags) {
12627 return (flags & ResultDisposition::SuppressFail) != 0;
12634#include <algorithm>
12640namespace Generators {
12641struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
12642 GeneratorBasePtr m_generator;
12644 GeneratorTracker(TestCaseTracking::NameAndLocation
const& nameAndLocation, TrackerContext& ctx,
12646 : TrackerBase(nameAndLocation, ctx, parent) {}
12647 ~GeneratorTracker();
12649 static GeneratorTracker& acquire(TrackerContext& ctx,
12650 TestCaseTracking::NameAndLocation
const& nameAndLocation) {
12651 std::shared_ptr<GeneratorTracker> tracker;
12653 ITracker& currentTracker = ctx.currentTracker();
12665 if (currentTracker.nameAndLocation() == nameAndLocation) {
12666 auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
12667 assert(thisTracker);
12668 assert(thisTracker->isGeneratorTracker());
12669 tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
12670 }
else if (TestCaseTracking::ITrackerPtr childTracker =
12671 currentTracker.findChild(nameAndLocation)) {
12672 assert(childTracker);
12673 assert(childTracker->isGeneratorTracker());
12674 tracker = std::static_pointer_cast<GeneratorTracker>(childTracker);
12676 tracker = std::make_shared<GeneratorTracker>(nameAndLocation, ctx, ¤tTracker);
12677 currentTracker.addChild(tracker);
12680 if (!tracker->isComplete()) {
12688 bool isGeneratorTracker()
const override {
return true; }
12689 auto hasGenerator() const ->
bool override {
return !!m_generator; }
12690 void close()
override {
12691 TrackerBase::close();
12699 const bool should_wait_for_child = [&]() {
12701 if (m_children.empty()) {
12705 if (std::find_if(m_children.begin(), m_children.end(),
12706 [](TestCaseTracking::ITrackerPtr tracker) {
12707 return tracker->hasStarted();
12708 }) != m_children.end()) {
12715 auto* parent = m_parent;
12718 while (!parent->isSectionTracker()) {
12719 parent = &(parent->parent());
12721 assert(parent &&
"Missing root (test case) level section");
12723 auto const& parentSection =
static_cast<SectionTracker&
>(*parent);
12724 auto const& filters = parentSection.getFilters();
12726 if (filters.empty()) {
12730 for (
auto const& child : m_children) {
12731 if (child->isSectionTracker() &&
12732 std::find(filters.begin(), filters.end(),
12733 static_cast<SectionTracker&
>(*child).trimmedName()) !=
12745 if (should_wait_for_child || (m_runState == CompletedSuccessfully && m_generator->next())) {
12746 m_children.clear();
12747 m_runState = Executing;
12752 auto getGenerator() const -> GeneratorBasePtr const&
override {
return m_generator; }
12753 void setGenerator(GeneratorBasePtr&& generator)
override { m_generator = std::move(generator); }
12755GeneratorTracker::~GeneratorTracker() {}
12758RunContext::RunContext(IConfigPtr
const& _config, IStreamingReporterPtr&& reporter)
12759 : m_runInfo(_config->name()), m_context(getCurrentMutableContext()), m_config(_config),
12760 m_reporter(std::move(reporter)), m_lastAssertionInfo{StringRef(), SourceLineInfo(
"", 0),
12761 StringRef(), ResultDisposition::Normal},
12762 m_includeSuccessfulResults(m_config->includeSuccessfulResults() ||
12763 m_reporter->getPreferences().shouldReportAllAssertions) {
12764 m_context.setRunner(
this);
12765 m_context.setConfig(m_config);
12766 m_context.setResultCapture(
this);
12767 m_reporter->testRunStarting(m_runInfo);
12770RunContext::~RunContext() {
12771 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
12774void RunContext::testGroupStarting(std::string
const& testSpec, std::size_t groupIndex,
12775 std::size_t groupsCount) {
12776 m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
12779void RunContext::testGroupEnded(std::string
const& testSpec,
Totals const& totals,
12780 std::size_t groupIndex, std::size_t groupsCount) {
12781 m_reporter->testGroupEnded(
12782 TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
12786 Totals prevTotals = m_totals;
12788 std::string redirectedCout;
12789 std::string redirectedCerr;
12791 auto const& testInfo = testCase.getTestCaseInfo();
12793 m_reporter->testCaseStarting(testInfo);
12795 m_activeTestCase = &testCase;
12797 ITracker& rootTracker = m_trackerContext.startRun();
12798 assert(rootTracker.isSectionTracker());
12799 static_cast<SectionTracker&
>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
12801 m_trackerContext.startCycle();
12802 m_testCaseTracker = &SectionTracker::acquire(
12803 m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
12804 runCurrentTest(redirectedCout, redirectedCerr);
12805 }
while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
12807 Totals deltaTotals = m_totals.delta(prevTotals);
12808 if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
12809 deltaTotals.assertions.failed++;
12810 deltaTotals.testCases.passed--;
12811 deltaTotals.testCases.failed++;
12813 m_totals.testCases += deltaTotals.testCases;
12814 m_reporter->testCaseEnded(
12815 TestCaseStats(testInfo, deltaTotals, redirectedCout, redirectedCerr, aborting()));
12817 m_activeTestCase =
nullptr;
12818 m_testCaseTracker =
nullptr;
12820 return deltaTotals;
12823IConfigPtr RunContext::config()
const {
12827IStreamingReporter& RunContext::reporter()
const {
12828 return *m_reporter;
12831void RunContext::assertionEnded(AssertionResult
const& result) {
12832 if (result.getResultType() == ResultWas::Ok) {
12833 m_totals.assertions.passed++;
12834 m_lastAssertionPassed =
true;
12835 }
else if (!result.isOk()) {
12836 m_lastAssertionPassed =
false;
12837 if (m_activeTestCase->getTestCaseInfo().okToFail())
12838 m_totals.assertions.failedButOk++;
12840 m_totals.assertions.failed++;
12842 m_lastAssertionPassed =
true;
12848 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
12850 if (result.getResultType() != ResultWas::Warning)
12851 m_messageScopes.clear();
12854 resetAssertionInfo();
12855 m_lastResult = result;
12857void RunContext::resetAssertionInfo() {
12858 m_lastAssertionInfo.macroName =
StringRef();
12859 m_lastAssertionInfo.capturedExpression =
"{Unknown expression after the reported line}"_sr;
12862bool RunContext::sectionStarted(
SectionInfo const& sectionInfo,
Counts& assertions) {
12863 ITracker& sectionTracker = SectionTracker::acquire(
12865 TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
12866 if (!sectionTracker.isOpen())
12868 m_activeSections.push_back(§ionTracker);
12870 m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
12872 m_reporter->sectionStarting(sectionInfo);
12874 assertions = m_totals.assertions;
12880 using namespace Generators;
12881 GeneratorTracker& tracker = GeneratorTracker::acquire(
12883 TestCaseTracking::NameAndLocation(
static_cast<std::string
>(generatorName), lineInfo));
12884 m_lastAssertionInfo.lineInfo = lineInfo;
12888bool RunContext::testForMissingAssertions(
Counts& assertions) {
12889 if (assertions.total() != 0)
12891 if (!m_config->warnAboutMissingAssertions())
12893 if (m_trackerContext.currentTracker().hasChildren())
12895 m_totals.assertions.failed++;
12896 assertions.failed++;
12901 Counts assertions = m_totals.assertions - endInfo.prevAssertions;
12902 bool missingAssertions = testForMissingAssertions(assertions);
12904 if (!m_activeSections.empty()) {
12905 m_activeSections.back()->close();
12906 m_activeSections.pop_back();
12909 m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions,
12910 endInfo.durationInSeconds, missingAssertions));
12911 m_messages.clear();
12912 m_messageScopes.clear();
12915void RunContext::sectionEndedEarly(
SectionEndInfo const& endInfo) {
12916 if (m_unfinishedSections.empty())
12917 m_activeSections.back()->fail();
12919 m_activeSections.back()->close();
12920 m_activeSections.pop_back();
12922 m_unfinishedSections.push_back(endInfo);
12925#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
12926void RunContext::benchmarkPreparing(std::string
const& name) {
12927 m_reporter->benchmarkPreparing(name);
12929void RunContext::benchmarkStarting(BenchmarkInfo
const& info) {
12930 m_reporter->benchmarkStarting(info);
12932void RunContext::benchmarkEnded(BenchmarkStats<>
const& stats) {
12933 m_reporter->benchmarkEnded(stats);
12935void RunContext::benchmarkFailed(std::string
const& error) {
12936 m_reporter->benchmarkFailed(error);
12940void RunContext::pushScopedMessage(
MessageInfo const& message) {
12941 m_messages.push_back(message);
12944void RunContext::popScopedMessage(
MessageInfo const& message) {
12945 m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
12948void RunContext::emplaceUnscopedMessage(
MessageBuilder const& builder) {
12949 m_messageScopes.emplace_back(builder);
12952std::string RunContext::getCurrentTestName()
const {
12953 return m_activeTestCase ? m_activeTestCase->getTestCaseInfo().name : std::string();
12956const AssertionResult* RunContext::getLastResult()
const {
12957 return &(*m_lastResult);
12960void RunContext::exceptionEarlyReported() {
12961 m_shouldReportUnexpected =
false;
12964void RunContext::handleFatalErrorCondition(
StringRef message) {
12966 m_reporter->fatalErrorEncountered(message);
12970 AssertionResultData tempResult(ResultWas::FatalErrorCondition, {
false});
12971 tempResult.message =
static_cast<std::string
>(message);
12972 AssertionResult result(m_lastAssertionInfo, tempResult);
12974 assertionEnded(result);
12976 handleUnfinishedSections();
12979 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12980 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12983 assertions.failed = 1;
12984 SectionStats testCaseSectionStats(testCaseSection, assertions, 0,
false);
12985 m_reporter->sectionEnded(testCaseSectionStats);
12987 auto const& testInfo = m_activeTestCase->getTestCaseInfo();
12990 deltaTotals.testCases.failed = 1;
12991 deltaTotals.assertions.failed = 1;
12992 m_reporter->testCaseEnded(
12993 TestCaseStats(testInfo, deltaTotals, std::string(), std::string(),
false));
12994 m_totals.testCases.failed++;
12995 testGroupEnded(std::string(), m_totals, 1, 1);
12996 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals,
false));
12999bool RunContext::lastAssertionPassed() {
13000 return m_lastAssertionPassed;
13003void RunContext::assertionPassed() {
13004 m_lastAssertionPassed =
true;
13005 ++m_totals.assertions.passed;
13006 resetAssertionInfo();
13007 m_messageScopes.clear();
13010bool RunContext::aborting()
const {
13011 return m_totals.assertions.failed >=
static_cast<std::size_t
>(m_config->abortAfter());
13014void RunContext::runCurrentTest(std::string& redirectedCout, std::string& redirectedCerr) {
13015 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
13016 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
13017 m_reporter->sectionStarting(testCaseSection);
13018 Counts prevAssertions = m_totals.assertions;
13019 double duration = 0;
13020 m_shouldReportUnexpected =
true;
13021 m_lastAssertionInfo = {
"TEST_CASE"_sr, testCaseInfo.lineInfo,
StringRef(),
13022 ResultDisposition::Normal};
13024 seedRng(*m_config);
13028 if (m_reporter->getPreferences().shouldRedirectStdOut) {
13029#if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
13030 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
13033 invokeActiveTestCase();
13035 OutputRedirect r(redirectedCout, redirectedCerr);
13037 invokeActiveTestCase();
13041 invokeActiveTestCase();
13043 duration = timer.getElapsedSeconds();
13051 if (m_shouldReportUnexpected) {
13053 handleUnexpectedInflightException(m_lastAssertionInfo, translateActiveException(),
13057 Counts assertions = m_totals.assertions - prevAssertions;
13058 bool missingAssertions = testForMissingAssertions(assertions);
13060 m_testCaseTracker->close();
13061 handleUnfinishedSections();
13062 m_messages.clear();
13063 m_messageScopes.clear();
13065 SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
13066 m_reporter->sectionEnded(testCaseSectionStats);
13069void RunContext::invokeActiveTestCase() {
13070 FatalConditionHandlerGuard _(&m_fatalConditionhandler);
13071 m_activeTestCase->invoke();
13074void RunContext::handleUnfinishedSections() {
13077 for (
auto it = m_unfinishedSections.rbegin(), itEnd = m_unfinishedSections.rend(); it != itEnd;
13080 m_unfinishedSections.clear();
13085 m_reporter->assertionStarting(info);
13087 bool negated = isFalseTest(info.resultDisposition);
13088 bool result = expr.getResult() != negated;
13091 if (!m_includeSuccessfulResults) {
13094 reportExpr(info, ResultWas::Ok, &expr, negated);
13097 reportExpr(info, ResultWas::ExpressionFailed, &expr, negated);
13098 populateReaction(reaction);
13101void RunContext::reportExpr(
AssertionInfo const& info, ResultWas::OfType resultType,
13104 m_lastAssertionInfo = info;
13107 AssertionResult assertionResult{info, data};
13108 assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
13110 assertionEnded(assertionResult);
13113void RunContext::handleMessage(
AssertionInfo const& info, ResultWas::OfType resultType,
13115 m_reporter->assertionStarting(info);
13117 m_lastAssertionInfo = info;
13120 data.message =
static_cast<std::string
>(message);
13121 AssertionResult assertionResult{m_lastAssertionInfo, data};
13122 assertionEnded(assertionResult);
13123 if (!assertionResult.isOk())
13124 populateReaction(reaction);
13126void RunContext::handleUnexpectedExceptionNotThrown(
AssertionInfo const& info,
13128 handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
13131void RunContext::handleUnexpectedInflightException(
AssertionInfo const& info,
13132 std::string
const& message,
13134 m_lastAssertionInfo = info;
13136 AssertionResultData data(ResultWas::ThrewException,
LazyExpression(
false));
13137 data.message = message;
13138 AssertionResult assertionResult{info, data};
13139 assertionEnded(assertionResult);
13140 populateReaction(reaction);
13144 reaction.shouldDebugBreak = m_config->shouldDebugBreak();
13145 reaction.shouldThrow =
13146 aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
13149void RunContext::handleIncomplete(
AssertionInfo const& info) {
13150 m_lastAssertionInfo = info;
13152 AssertionResultData data(ResultWas::ThrewException,
LazyExpression(
false));
13153 data.message =
"Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
13154 AssertionResult assertionResult{info, data};
13155 assertionEnded(assertionResult);
13157void RunContext::handleNonExpr(
AssertionInfo const& info, ResultWas::OfType resultType,
13159 m_lastAssertionInfo = info;
13162 AssertionResult assertionResult{info, data};
13163 assertionEnded(assertionResult);
13165 if (!assertionResult.isOk())
13166 populateReaction(reaction);
13170 if (
auto* capture = getCurrentContext().getResultCapture())
13173 CATCH_INTERNAL_ERROR(
"No result capture instance");
13176void seedRng(
IConfig const& config) {
13177 if (config.rngSeed() != 0) {
13178 std::srand(config.rngSeed());
13179 rng().seed(config.rngSeed());
13183unsigned int rngSeed() {
13184 return getCurrentContext().getConfig()->rngSeed();
13194 : m_info(info), m_sectionIncluded(getResultCapture().sectionStarted(m_info, m_assertions)) {
13198Section::~Section() {
13199 if (m_sectionIncluded) {
13200 SectionEndInfo endInfo{m_info, m_assertions, m_timer.getElapsedSeconds()};
13201 if (uncaught_exceptions())
13202 getResultCapture().sectionEndedEarly(endInfo);
13204 getResultCapture().sectionEnded(endInfo);
13209Section::operator bool()
const {
13210 return m_sectionIncluded;
13219SectionInfo::SectionInfo(
SourceLineInfo const& _lineInfo, std::string
const& _name)
13220 : name(_name), lineInfo(_lineInfo) {}
13235 ~Session()
override;
13237 void showHelp()
const;
13238 void libIdentify();
13240 int applyCommandLine(
int argc,
char const*
const* argv);
13241#if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13242 int applyCommandLine(
int argc,
wchar_t const*
const* argv);
13245 void useConfigData(ConfigData
const& configData);
13247 template <
typename CharT>
int run(
int argc, CharT
const*
const argv[]) {
13248 if (m_startupExceptions)
13250 int returnCode = applyCommandLine(argc, argv);
13251 if (returnCode == 0)
13252 returnCode = run();
13258 clara::Parser
const& cli()
const;
13259 void cli(clara::Parser
const& newParser);
13260 ConfigData& configData();
13266 clara::Parser m_cli;
13267 ConfigData m_configData;
13268 std::shared_ptr<Config> m_config;
13269 bool m_startupExceptions =
false;
13283 Version(Version
const&) =
delete;
13284 Version& operator=(Version
const&) =
delete;
13285 Version(
unsigned int _majorVersion,
unsigned int _minorVersion,
unsigned int _patchNumber,
13286 char const*
const _branchName,
unsigned int _buildNumber);
13288 unsigned int const majorVersion;
13289 unsigned int const minorVersion;
13290 unsigned int const patchNumber;
13293 char const*
const branchName;
13294 unsigned int const buildNumber;
13296 friend std::ostream& operator<<(std::ostream& os, Version
const& version);
13299Version
const& libraryVersion();
13311const int MaxExitCode = 255;
13313IStreamingReporterPtr createReporter(std::string
const& reporterName, IConfigPtr
const& config) {
13314 auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
13315 CATCH_ENFORCE(reporter,
"No reporter registered with name: '" << reporterName <<
"'");
13320IStreamingReporterPtr makeReporter(std::shared_ptr<Config>
const& config) {
13321 if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
13322 return createReporter(config->getReporterName(), config);
13330 auto ret = std::unique_ptr<IStreamingReporter>(
new ListeningReporter);
13331 auto& multi =
static_cast<ListeningReporter&
>(*ret);
13332 auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
13333 for (
auto const& listener : listeners) {
13334 multi.addListener(listener->create(Catch::ReporterConfig(config)));
13336 multi.addReporter(createReporter(config->getReporterName(), config));
13342 explicit TestGroup(std::shared_ptr<Config>
const& config)
13343 : m_config{config}, m_context{config, makeReporter(config)} {
13344 auto const& allTestCases = getAllTestCasesSorted(*m_config);
13345 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
13346 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13348 if (m_matches.empty() && invalidArgs.empty()) {
13349 for (
auto const& test : allTestCases)
13350 if (!test.isHidden())
13351 m_tests.emplace(&test);
13353 for (
auto const& match : m_matches)
13354 m_tests.insert(match.tests.begin(), match.tests.end());
13359 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13361 m_context.testGroupStarting(m_config->name(), 1, 1);
13362 for (
auto const& testCase : m_tests) {
13363 if (!m_context.aborting())
13364 totals += m_context.runTest(*testCase);
13366 m_context.reporter().skipTest(*testCase);
13369 for (
auto const& match : m_matches) {
13370 if (match.tests.empty()) {
13371 m_context.reporter().noMatchingTestCases(match.name);
13376 if (!invalidArgs.empty()) {
13377 for (
auto const& invalidArg : invalidArgs)
13378 m_context.reporter().reportInvalidArguments(invalidArg);
13381 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
13386 using Tests = std::set<TestCase const*>;
13388 std::shared_ptr<Config> m_config;
13389 RunContext m_context;
13391 TestSpec::Matches m_matches;
13394void applyFilenamesAsTags(Catch::IConfig
const& config) {
13395 auto& tests =
const_cast<std::vector<TestCase>&
>(getAllTestCasesSorted(config));
13396 for (
auto& testCase : tests) {
13397 auto tags = testCase.tags;
13399 std::string filename = testCase.lineInfo.file;
13400 auto lastSlash = filename.find_last_of(
"\\/");
13401 if (lastSlash != std::string::npos) {
13402 filename.erase(0, lastSlash);
13405 filename.insert(0,
"#");
13408 auto lastDot = filename.find_last_of(
'.');
13409 if (lastDot != std::string::npos) {
13410 filename.erase(lastDot);
13413 tags.push_back(std::move(filename));
13414 setTags(testCase, tags);
13420Session::Session() {
13421 static bool alreadyInstantiated =
false;
13422 if (alreadyInstantiated) {
13424 CATCH_INTERNAL_ERROR(
"Only one instance of Catch::Session can ever be used");
13427 getMutableRegistryHub().registerStartupException();
13432#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13433 const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
13434 if (!exceptions.empty()) {
13436 getCurrentMutableContext().setConfig(m_config);
13438 m_startupExceptions =
true;
13439 Colour colourGuard(Colour::Red);
13440 Catch::cerr() <<
"Errors occurred during startup!" <<
'\n';
13442 for (
const auto& ex_ptr : exceptions) {
13444 std::rethrow_exception(ex_ptr);
13445 }
catch (std::exception
const& ex) {
13446 Catch::cerr() << Column(ex.what()).indent(2) <<
'\n';
13452 alreadyInstantiated =
true;
13453 m_cli = makeCommandLineParser(m_configData);
13455Session::~Session() {
13459void Session::showHelp()
const {
13460 Catch::cout() <<
"\nCatch v" << libraryVersion() <<
"\n"
13461 << m_cli << std::endl
13462 <<
"For more detailed usage please see the project docs\n"
13465void Session::libIdentify() {
13466 Catch::cout() << std::left << std::setw(16) <<
"description: " <<
"A Catch2 test executable\n"
13467 << std::left << std::setw(16) <<
"category: " <<
"testframework\n"
13468 << std::left << std::setw(16) <<
"framework: " <<
"Catch Test\n"
13469 << std::left << std::setw(16) <<
"version: " << libraryVersion() << std::endl;
13472int Session::applyCommandLine(
int argc,
char const*
const* argv) {
13473 if (m_startupExceptions)
13476 auto result = m_cli.parse(clara::Args(argc, argv));
13479 getCurrentMutableContext().setConfig(m_config);
13480 Catch::cerr() << Colour(Colour::Red) <<
"\nError(s) in input:\n"
13481 << Column(result.errorMessage()).indent(2) <<
"\n\n";
13482 Catch::cerr() <<
"Run with -? for usage\n" << std::endl;
13483 return MaxExitCode;
13486 if (m_configData.showHelp)
13488 if (m_configData.libIdentify)
13494#if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13495int Session::applyCommandLine(
int argc,
wchar_t const*
const* argv) {
13497 char** utf8Argv =
new char*[argc];
13499 for (
int i = 0; i < argc; ++i) {
13500 int bufSize = WideCharToMultiByte(CP_UTF8, 0, argv[i], -1,
nullptr, 0,
nullptr,
nullptr);
13502 utf8Argv[i] =
new char[bufSize];
13504 WideCharToMultiByte(CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize,
nullptr,
nullptr);
13507 int returnCode = applyCommandLine(argc, utf8Argv);
13509 for (
int i = 0; i < argc; ++i)
13510 delete[] utf8Argv[i];
13518void Session::useConfigData(ConfigData
const& configData) {
13519 m_configData = configData;
13523int Session::run() {
13524 if ((m_configData.waitForKeypress & WaitForKeypress::BeforeStart) != 0) {
13525 Catch::cout() <<
"...waiting for enter/ return before starting" << std::endl;
13526 static_cast<void>(std::getchar());
13528 int exitCode = runInternal();
13529 if ((m_configData.waitForKeypress & WaitForKeypress::BeforeExit) != 0) {
13530 Catch::cout() <<
"...waiting for enter/ return before exiting, with code: " << exitCode
13532 static_cast<void>(std::getchar());
13537clara::Parser
const& Session::cli()
const {
13540void Session::cli(clara::Parser
const& newParser) {
13543ConfigData& Session::configData() {
13544 return m_configData;
13546Config& Session::config() {
13548 m_config = std::make_shared<Config>(m_configData);
13552int Session::runInternal() {
13553 if (m_startupExceptions)
13556 if (m_configData.showHelp || m_configData.libIdentify) {
13563 seedRng(*m_config);
13565 if (m_configData.filenamesAsTags)
13566 applyFilenamesAsTags(*m_config);
13569 if (Option<std::size_t> listed = list(m_config))
13570 return static_cast<int>(*listed);
13572 TestGroup tests{m_config};
13573 auto const totals = tests.execute();
13575 if (m_config->warnAboutNoTests() && totals.error == -1)
13581 return (std::min)(MaxExitCode,
13582 (std::max)(totals.error,
static_cast<int>(totals.assertions.failed)));
13584#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13585 catch (std::exception& ex) {
13586 Catch::cerr() << ex.what() << std::endl;
13587 return MaxExitCode;
13601static auto getSingletons() -> std::vector<ISingleton*>*& {
13602 static std::vector<ISingleton*>* g_singletons =
nullptr;
13604 g_singletons =
new std::vector<ISingleton*>();
13605 return g_singletons;
13609ISingleton::~ISingleton() {}
13611void addSingleton(ISingleton* singleton) {
13612 getSingletons()->push_back(singleton);
13614void cleanupSingletons() {
13615 auto& singletons = getSingletons();
13616 for (
auto singleton : *singletons)
13619 singletons =
nullptr;
13626#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13628void StartupExceptionRegistry::add(std::exception_ptr
const& exception)
noexcept {
13630 m_exceptions.push_back(exception);
13639std::vector<std::exception_ptr>
const& StartupExceptionRegistry::getExceptions() const noexcept {
13640 return m_exceptions;
13657Catch::IStream::~IStream() =
default;
13661template <
typename WriterF, std::
size_t bufferSize = 256>
13662class StreamBufImpl :
public std::streambuf {
13663 char data[bufferSize];
13667 StreamBufImpl() { setp(data, data +
sizeof(data)); }
13669 ~StreamBufImpl() noexcept { StreamBufImpl::sync(); }
13672 int overflow(
int c)
override {
13676 if (pbase() == epptr())
13677 m_writer(std::string(1,
static_cast<char>(c)));
13679 sputc(
static_cast<char>(c));
13684 int sync()
override {
13685 if (pbase() != pptr()) {
13686 m_writer(std::string(pbase(),
static_cast<std::string::size_type
>(pptr() - pbase())));
13687 setp(pbase(), epptr());
13695struct OutputDebugWriter {
13697 void operator()(std::string
const& str) { writeToDebugConsole(str); }
13702class FileStream :
public IStream {
13703 mutable std::ofstream m_ofs;
13706 FileStream(StringRef filename) {
13707 m_ofs.open(filename.c_str());
13708 CATCH_ENFORCE(!m_ofs.fail(),
"Unable to open file: '" << filename <<
"'");
13710 ~FileStream()
override =
default;
13713 std::ostream& stream()
const override {
return m_ofs; }
13718class CoutStream :
public IStream {
13719 mutable std::ostream m_os;
13724 CoutStream() : m_os(Catch::cout().rdbuf()) {}
13725 ~CoutStream()
override =
default;
13728 std::ostream& stream()
const override {
return m_os; }
13733class DebugOutStream :
public IStream {
13734 std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
13735 mutable std::ostream m_os;
13739 : m_streamBuf(new StreamBufImpl<OutputDebugWriter>()), m_os(m_streamBuf.get()) {}
13741 ~DebugOutStream()
override =
default;
13744 std::ostream& stream()
const override {
return m_os; }
13753 if (filename.empty())
13754 return new Detail::CoutStream();
13755 else if (filename[0] ==
'%') {
13756 if (filename ==
"%debug")
13757 return new Detail::DebugOutStream();
13759 CATCH_ERROR(
"Unrecognised stream: '" << filename <<
"'");
13761 return new Detail::FileStream(filename);
13766struct StringStreams {
13767 std::vector<std::unique_ptr<std::ostringstream>> m_streams;
13768 std::vector<std::size_t> m_unused;
13769 std::ostringstream m_referenceStream;
13771 auto add() -> std::size_t {
13772 if (m_unused.empty()) {
13773 m_streams.push_back(std::unique_ptr<std::ostringstream>(
new std::ostringstream));
13774 return m_streams.size() - 1;
13776 auto index = m_unused.back();
13777 m_unused.pop_back();
13782 void release(std::size_t index) {
13783 m_streams[index]->copyfmt(m_referenceStream);
13784 m_unused.push_back(index);
13788ReusableStringStream::ReusableStringStream()
13789 : m_index(Singleton<StringStreams>::getMutable().add()),
13790 m_oss(Singleton<StringStreams>::getMutable().m_streams[m_index].get()) {}
13792ReusableStringStream::~ReusableStringStream() {
13793 static_cast<std::ostringstream*
>(m_oss)->str(
"");
13795 Singleton<StringStreams>::getMutable().release(m_index);
13798auto ReusableStringStream::str() const -> std::
string {
13799 return static_cast<std::ostringstream*
>(m_oss)->str();
13804#ifndef CATCH_CONFIG_NOSTDOUT
13806std::ostream& cout() {
13809std::ostream& cerr() {
13812std::ostream& clog() {
13820#include <algorithm>
13829char toLowerCh(
char c) {
13830 return static_cast<char>(std::tolower(
static_cast<unsigned char>(c)));
13834bool startsWith(std::string
const& s, std::string
const& prefix) {
13835 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
13837bool startsWith(std::string
const& s,
char prefix) {
13838 return !s.empty() && s[0] == prefix;
13840bool endsWith(std::string
const& s, std::string
const& suffix) {
13841 return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
13843bool endsWith(std::string
const& s,
char suffix) {
13844 return !s.empty() && s[s.size() - 1] == suffix;
13846bool contains(std::string
const& s, std::string
const& infix) {
13847 return s.find(infix) != std::string::npos;
13849void toLowerInPlace(std::string& s) {
13850 std::transform(s.begin(), s.end(), s.begin(), toLowerCh);
13852std::string toLower(std::string
const& s) {
13853 std::string lc = s;
13854 toLowerInPlace(lc);
13857std::string trim(std::string
const& str) {
13858 static char const* whitespaceChars =
"\n\r\t ";
13859 std::string::size_type start = str.find_first_not_of(whitespaceChars);
13860 std::string::size_type end = str.find_last_not_of(whitespaceChars);
13862 return start != std::string::npos ? str.substr(start, 1 + end - start) : std::string();
13866 const auto is_ws = [](
char c) {
return c ==
' ' || c ==
'\t' || c ==
'\n' || c ==
'\r'; };
13867 size_t real_begin = 0;
13868 while (real_begin < ref.size() && is_ws(ref[real_begin])) {
13871 size_t real_end = ref.size();
13872 while (real_end > real_begin && is_ws(ref[real_end - 1])) {
13876 return ref.substr(real_begin, real_end - real_begin);
13879bool replaceInPlace(std::string& str, std::string
const& replaceThis, std::string
const& withThis) {
13880 bool replaced =
false;
13881 std::size_t i = str.find(replaceThis);
13882 while (i != std::string::npos) {
13884 str = str.substr(0, i) + withThis + str.substr(i + replaceThis.size());
13885 if (i < str.size() - withThis.size())
13886 i = str.find(replaceThis, i + withThis.size());
13888 i = std::string::npos;
13893std::vector<StringRef> splitStringRef(
StringRef str,
char delimiter) {
13894 std::vector<StringRef> subStrings;
13895 std::size_t start = 0;
13896 for (std::size_t pos = 0; pos < str.size(); ++pos) {
13897 if (str[pos] == delimiter) {
13898 if (pos - start > 1)
13899 subStrings.push_back(str.substr(start, pos - start));
13903 if (start < str.size())
13904 subStrings.push_back(str.substr(start, str.size() - start));
13908pluralise::pluralise(std::size_t count, std::string
const& label)
13909 : m_count(count), m_label(label) {}
13911std::ostream& operator<<(std::ostream& os,
pluralise const& pluraliser) {
13912 os << pluraliser.m_count <<
' ' << pluraliser.m_label;
13913 if (pluraliser.m_count != 1)
13922#include <algorithm>
13928StringRef::StringRef(
char const* rawChars) noexcept
13929 :
StringRef(rawChars,
static_cast<StringRef::size_type
>(std::strlen(rawChars))) {}
13931auto StringRef::c_str() const ->
char const* {
13932 CATCH_ENFORCE(isNullTerminated(),
13933 "Called StringRef::c_str() on a non-null-terminated instance");
13936auto StringRef::data() const noexcept ->
char const* {
13940auto StringRef::substr(size_type start, size_type size)
const noexcept ->
StringRef {
13941 if (start < m_size) {
13942 return StringRef(m_start + start, (std::min)(m_size - start, size));
13947auto StringRef::operator==(
StringRef const& other)
const noexcept ->
bool {
13948 return m_size == other.m_size && (std::memcmp(m_start, other.m_start, m_size) == 0);
13951auto operator<<(std::ostream& os,
StringRef const& str) -> std::ostream& {
13952 return os.write(str.data(), str.size());
13955auto operator+=(std::string& lhs,
StringRef const& rhs) -> std::string& {
13956 lhs.append(rhs.data(), rhs.size());
13965TagAlias::TagAlias(std::string
const& _tag,
SourceLineInfo _lineInfo)
13966 : tag(_tag), lineInfo(_lineInfo) {}
13973RegistrarForTagAliases::RegistrarForTagAliases(
char const* alias,
char const* tag,
13976 getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
13981 getMutableRegistryHub().registerStartupException();
13993TagAliasRegistry::~TagAliasRegistry() {}
13995TagAlias
const* TagAliasRegistry::find(std::string
const& alias)
const {
13996 auto it = m_registry.find(alias);
13997 if (it != m_registry.end())
13998 return &(it->second);
14003std::string TagAliasRegistry::expandAliases(std::string
const& unexpandedTestSpec)
const {
14004 std::string expandedTestSpec = unexpandedTestSpec;
14005 for (
auto const& registryKvp : m_registry) {
14006 std::size_t pos = expandedTestSpec.find(registryKvp.first);
14007 if (pos != std::string::npos) {
14008 expandedTestSpec = expandedTestSpec.substr(0, pos) + registryKvp.second.tag +
14009 expandedTestSpec.substr(pos + registryKvp.first.size());
14012 return expandedTestSpec;
14015void TagAliasRegistry::add(std::string
const& alias, std::string
const& tag,
14017 CATCH_ENFORCE(startsWith(alias,
"[@") && endsWith(alias,
']'),
14018 "error: tag alias, '" << alias <<
"' is not of the form [@alias name].\n"
14021 CATCH_ENFORCE(m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
14022 "error: tag alias, '" << alias <<
"' already registered.\n"
14023 <<
"\tFirst seen at: " << find(alias)->lineInfo <<
"\n"
14024 <<
"\tRedefined at: " << lineInfo);
14027ITagAliasRegistry::~ITagAliasRegistry() {}
14029ITagAliasRegistry
const& ITagAliasRegistry::get() {
14030 return getRegistryHub().getTagAliasRegistry();
14037#include <algorithm>
14039#include <exception>
14045TestCaseInfo::SpecialProperties parseSpecialTag(std::string
const& tag) {
14046 if (startsWith(tag,
'.') || tag ==
"!hide")
14047 return TestCaseInfo::IsHidden;
14048 else if (tag ==
"!throws")
14049 return TestCaseInfo::Throws;
14050 else if (tag ==
"!shouldfail")
14051 return TestCaseInfo::ShouldFail;
14052 else if (tag ==
"!mayfail")
14053 return TestCaseInfo::MayFail;
14054 else if (tag ==
"!nonportable")
14055 return TestCaseInfo::NonPortable;
14056 else if (tag ==
"!benchmark")
14057 return static_cast<TestCaseInfo::SpecialProperties
>(TestCaseInfo::Benchmark |
14058 TestCaseInfo::IsHidden);
14060 return TestCaseInfo::None;
14062bool isReservedTag(std::string
const& tag) {
14063 return parseSpecialTag(tag) == TestCaseInfo::None && tag.size() > 0 &&
14064 !std::isalnum(
static_cast<unsigned char>(tag[0]));
14066void enforceNotReservedTag(std::string
const& tag,
SourceLineInfo const& _lineInfo) {
14067 CATCH_ENFORCE(!isReservedTag(tag),
"Tag name: [" << tag <<
"] is not allowed.\n"
14068 <<
"Tag names starting with non alphanumeric "
14069 "characters are reserved\n"
14076 bool isHidden =
false;
14079 std::vector<std::string> tags;
14080 std::string desc, tag;
14081 bool inTag =
false;
14082 for (
char c : nameAndTags.tags) {
14090 TestCaseInfo::SpecialProperties prop = parseSpecialTag(tag);
14091 if ((prop & TestCaseInfo::IsHidden) != 0)
14093 else if (prop == TestCaseInfo::None)
14094 enforceNotReservedTag(tag, _lineInfo);
14099 if (startsWith(tag,
'.') && tag.size() > 1) {
14102 tags.push_back(tag);
14111 tags.insert(tags.end(), {
".",
"!hide"});
14114 TestCaseInfo info(
static_cast<std::string
>(nameAndTags.name), _className, desc, tags,
14116 return TestCase(_testCase, std::move(info));
14119void setTags(
TestCaseInfo& testCaseInfo, std::vector<std::string> tags) {
14120 std::sort(begin(tags), end(tags));
14121 tags.erase(std::unique(begin(tags), end(tags)), end(tags));
14122 testCaseInfo.lcaseTags.clear();
14124 for (
auto const& tag : tags) {
14125 std::string lcaseTag = toLower(tag);
14126 testCaseInfo.properties =
static_cast<TestCaseInfo::SpecialProperties
>(
14127 testCaseInfo.properties | parseSpecialTag(lcaseTag));
14128 testCaseInfo.lcaseTags.push_back(lcaseTag);
14130 testCaseInfo.tags = std::move(tags);
14133TestCaseInfo::TestCaseInfo(std::string
const& _name, std::string
const& _className,
14134 std::string
const& _description, std::vector<std::string>
const& _tags,
14136 : name(_name), className(_className), description(_description), lineInfo(_lineInfo),
14138 setTags(*
this, _tags);
14141bool TestCaseInfo::isHidden()
const {
14142 return (properties & IsHidden) != 0;
14144bool TestCaseInfo::throws()
const {
14145 return (properties & Throws) != 0;
14147bool TestCaseInfo::okToFail()
const {
14148 return (properties & (ShouldFail | MayFail)) != 0;
14150bool TestCaseInfo::expectedToFail()
const {
14151 return (properties & (ShouldFail)) != 0;
14154std::string TestCaseInfo::tagsAsString()
const {
14157 std::size_t full_size = 2 * tags.size();
14158 for (
const auto& tag : tags) {
14159 full_size += tag.size();
14161 ret.reserve(full_size);
14162 for (
const auto& tag : tags) {
14163 ret.push_back(
'[');
14165 ret.push_back(
']');
14174TestCase TestCase::withName(std::string
const& _newName)
const {
14175 TestCase other(*
this);
14176 other.name = _newName;
14180void TestCase::invoke()
const {
14184bool TestCase::operator==(
TestCase const& other)
const {
14185 return test.get() == other.test.get() && name == other.name && className == other.className;
14188bool TestCase::operator<(
TestCase const& other)
const {
14189 return name < other.name;
14192TestCaseInfo const& TestCase::getTestCaseInfo()
const {
14200#include <algorithm>
14207 using hash_t = uint64_t;
14209 explicit TestHasher(hash_t hashSuffix) : m_hashSuffix{hashSuffix} {}
14211 uint32_t operator()(TestCase
const& t)
const {
14213 const hash_t prime = 1099511628211u;
14214 hash_t
hash = 14695981039346656037u;
14215 for (
const char c : t.name) {
14219 hash ^= m_hashSuffix;
14221 const uint32_t low{
static_cast<uint32_t
>(
hash)};
14222 const uint32_t high{
static_cast<uint32_t
>(
hash >> 32)};
14227 hash_t m_hashSuffix;
14231std::vector<TestCase> sortTests(
IConfig const& config,
14232 std::vector<TestCase>
const& unsortedTestCases) {
14233 switch (config.runOrder()) {
14234 case RunTests::InDeclarationOrder:
14238 case RunTests::InLexicographicalOrder: {
14239 std::vector<TestCase> sorted = unsortedTestCases;
14240 std::sort(sorted.begin(), sorted.end());
14244 case RunTests::InRandomOrder: {
14246 TestHasher h{config.rngSeed()};
14248 using hashedTest = std::pair<TestHasher::hash_t, TestCase const*>;
14249 std::vector<hashedTest> indexed_tests;
14250 indexed_tests.reserve(unsortedTestCases.size());
14252 for (
auto const& testCase : unsortedTestCases) {
14253 indexed_tests.emplace_back(h(testCase), &testCase);
14256 std::sort(indexed_tests.begin(), indexed_tests.end(),
14257 [](hashedTest
const& lhs, hashedTest
const& rhs) {
14258 if (lhs.first == rhs.first) {
14259 return lhs.second->name < rhs.second->name;
14261 return lhs.first < rhs.first;
14264 std::vector<TestCase> sorted;
14265 sorted.reserve(indexed_tests.size());
14267 for (
auto const& hashed : indexed_tests) {
14268 sorted.emplace_back(*hashed.second);
14274 return unsortedTestCases;
14277bool isThrowSafe(TestCase
const& testCase, IConfig
const& config) {
14278 return !testCase.throws() || config.allowThrows();
14281bool matchTest(TestCase
const& testCase, TestSpec
const& testSpec, IConfig
const& config) {
14282 return testSpec.matches(testCase) && isThrowSafe(testCase, config);
14285void enforceNoDuplicateTestCases(std::vector<TestCase>
const& functions) {
14286 std::set<TestCase> seenFunctions;
14287 for (
auto const& function : functions) {
14288 auto prev = seenFunctions.insert(function);
14289 CATCH_ENFORCE(prev.second,
"error: TEST_CASE( \""
14290 << function.name <<
"\" ) already defined.\n"
14291 <<
"\tFirst seen at "
14292 << prev.first->getTestCaseInfo().lineInfo <<
"\n"
14293 <<
"\tRedefined at " << function.getTestCaseInfo().lineInfo);
14297std::vector<TestCase> filterTests(std::vector<TestCase>
const& testCases, TestSpec
const& testSpec,
14298 IConfig
const& config) {
14299 std::vector<TestCase> filtered;
14300 filtered.reserve(testCases.size());
14301 for (
auto const& testCase : testCases) {
14302 if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
14303 (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
14304 filtered.push_back(testCase);
14309std::vector<TestCase>
const& getAllTestCasesSorted(IConfig
const& config) {
14310 return getRegistryHub().getTestCaseRegistry().getAllTestsSorted(config);
14313void TestRegistry::registerTest(TestCase
const& testCase) {
14314 std::string name = testCase.getTestCaseInfo().name;
14315 if (name.empty()) {
14316 ReusableStringStream rss;
14317 rss <<
"Anonymous test case " << ++m_unnamedCount;
14318 return registerTest(testCase.withName(rss.str()));
14320 m_functions.push_back(testCase);
14323std::vector<TestCase>
const& TestRegistry::getAllTests()
const {
14324 return m_functions;
14326std::vector<TestCase>
const& TestRegistry::getAllTestsSorted(IConfig
const& config)
const {
14327 if (m_sortedFunctions.empty())
14328 enforceNoDuplicateTestCases(m_functions);
14330 if (m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty()) {
14331 m_sortedFunctions = sortTests(config, m_functions);
14332 m_currentSortOrder = config.runOrder();
14334 return m_sortedFunctions;
14338TestInvokerAsFunction::TestInvokerAsFunction(
void (*testAsFunction)()) noexcept
14339 : m_testAsFunction(testAsFunction) {}
14341void TestInvokerAsFunction::invoke()
const {
14342 m_testAsFunction();
14345std::string extractClassName(StringRef
const& classOrQualifiedMethodName) {
14346 std::string className(classOrQualifiedMethodName);
14347 if (startsWith(className,
'&')) {
14348 std::size_t lastColons = className.rfind(
"::");
14349 std::size_t penultimateColons = className.rfind(
"::", lastColons - 1);
14350 if (penultimateColons == std::string::npos)
14351 penultimateColons = 1;
14352 className = className.substr(penultimateColons, lastColons - penultimateColons);
14361#include <algorithm>
14365#include <stdexcept>
14367#if defined(__clang__)
14368#pragma clang diagnostic push
14369#pragma clang diagnostic ignored "-Wexit-time-destructors"
14373namespace TestCaseTracking {
14375NameAndLocation::NameAndLocation(std::string
const& _name, SourceLineInfo
const& _location)
14376 : name(_name), location(_location) {}
14378ITracker::~ITracker() =
default;
14380ITracker& TrackerContext::startRun() {
14381 m_rootTracker = std::make_shared<SectionTracker>(
14382 NameAndLocation(
"{root}", CATCH_INTERNAL_LINEINFO), *
this,
nullptr);
14383 m_currentTracker =
nullptr;
14384 m_runState = Executing;
14385 return *m_rootTracker;
14388void TrackerContext::endRun() {
14389 m_rootTracker.reset();
14390 m_currentTracker =
nullptr;
14391 m_runState = NotStarted;
14394void TrackerContext::startCycle() {
14395 m_currentTracker = m_rootTracker.get();
14396 m_runState = Executing;
14398void TrackerContext::completeCycle() {
14399 m_runState = CompletedCycle;
14402bool TrackerContext::completedCycle()
const {
14403 return m_runState == CompletedCycle;
14405ITracker& TrackerContext::currentTracker() {
14406 return *m_currentTracker;
14408void TrackerContext::setCurrentTracker(ITracker* tracker) {
14409 m_currentTracker = tracker;
14412TrackerBase::TrackerBase(NameAndLocation
const& nameAndLocation, TrackerContext& ctx,
14414 : ITracker(nameAndLocation), m_ctx(ctx), m_parent(parent) {}
14416bool TrackerBase::isComplete()
const {
14417 return m_runState == CompletedSuccessfully || m_runState == Failed;
14419bool TrackerBase::isSuccessfullyCompleted()
const {
14420 return m_runState == CompletedSuccessfully;
14422bool TrackerBase::isOpen()
const {
14423 return m_runState != NotStarted && !isComplete();
14425bool TrackerBase::hasChildren()
const {
14426 return !m_children.empty();
14429void TrackerBase::addChild(ITrackerPtr
const& child) {
14430 m_children.push_back(child);
14433ITrackerPtr TrackerBase::findChild(NameAndLocation
const& nameAndLocation) {
14434 auto it = std::find_if(
14435 m_children.begin(), m_children.end(), [&nameAndLocation](ITrackerPtr
const& tracker) {
14436 return tracker->nameAndLocation().location == nameAndLocation.location &&
14437 tracker->nameAndLocation().name == nameAndLocation.name;
14439 return (it != m_children.end()) ? *it :
nullptr;
14441ITracker& TrackerBase::parent() {
14446void TrackerBase::openChild() {
14447 if (m_runState != ExecutingChildren) {
14448 m_runState = ExecutingChildren;
14450 m_parent->openChild();
14454bool TrackerBase::isSectionTracker()
const {
14457bool TrackerBase::isGeneratorTracker()
const {
14461void TrackerBase::open() {
14462 m_runState = Executing;
14465 m_parent->openChild();
14468void TrackerBase::close() {
14471 while (&m_ctx.currentTracker() !=
this)
14472 m_ctx.currentTracker().close();
14474 switch (m_runState) {
14475 case NeedsAnotherRun:
14479 m_runState = CompletedSuccessfully;
14481 case ExecutingChildren:
14482 if (std::all_of(m_children.begin(), m_children.end(),
14483 [](ITrackerPtr
const& t) { return t->isComplete(); }))
14484 m_runState = CompletedSuccessfully;
14488 case CompletedSuccessfully:
14490 CATCH_INTERNAL_ERROR(
"Illogical state: " << m_runState);
14493 CATCH_INTERNAL_ERROR(
"Unknown state: " << m_runState);
14496 m_ctx.completeCycle();
14498void TrackerBase::fail() {
14499 m_runState = Failed;
14501 m_parent->markAsNeedingAnotherRun();
14503 m_ctx.completeCycle();
14505void TrackerBase::markAsNeedingAnotherRun() {
14506 m_runState = NeedsAnotherRun;
14509void TrackerBase::moveToParent() {
14511 m_ctx.setCurrentTracker(m_parent);
14513void TrackerBase::moveToThis() {
14514 m_ctx.setCurrentTracker(
this);
14517SectionTracker::SectionTracker(NameAndLocation
const& nameAndLocation, TrackerContext& ctx,
14519 : TrackerBase(nameAndLocation, ctx, parent), m_trimmed_name(trim(nameAndLocation.name)) {
14521 while (!parent->isSectionTracker())
14522 parent = &parent->parent();
14524 SectionTracker& parentSection =
static_cast<SectionTracker&
>(*parent);
14525 addNextFilters(parentSection.m_filters);
14529bool SectionTracker::isComplete()
const {
14530 bool complete =
true;
14532 if (m_filters.empty() || m_filters[0] ==
"" ||
14533 std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
14534 complete = TrackerBase::isComplete();
14539bool SectionTracker::isSectionTracker()
const {
14543SectionTracker& SectionTracker::acquire(TrackerContext& ctx,
14544 NameAndLocation
const& nameAndLocation) {
14545 std::shared_ptr<SectionTracker> section;
14547 ITracker& currentTracker = ctx.currentTracker();
14548 if (ITrackerPtr childTracker = currentTracker.findChild(nameAndLocation)) {
14549 assert(childTracker);
14550 assert(childTracker->isSectionTracker());
14551 section = std::static_pointer_cast<SectionTracker>(childTracker);
14553 section = std::make_shared<SectionTracker>(nameAndLocation, ctx, ¤tTracker);
14554 currentTracker.addChild(section);
14556 if (!ctx.completedCycle())
14557 section->tryOpen();
14561void SectionTracker::tryOpen() {
14566void SectionTracker::addInitialFilters(std::vector<std::string>
const& filters) {
14567 if (!filters.empty()) {
14568 m_filters.reserve(m_filters.size() + filters.size() + 2);
14569 m_filters.emplace_back(
"");
14570 m_filters.emplace_back(
"");
14571 m_filters.insert(m_filters.end(), filters.begin(), filters.end());
14574void SectionTracker::addNextFilters(std::vector<std::string>
const& filters) {
14575 if (filters.size() > 1)
14576 m_filters.insert(m_filters.end(), filters.begin() + 1, filters.end());
14579std::vector<std::string>
const& SectionTracker::getFilters()
const {
14583std::string
const& SectionTracker::trimmedName()
const {
14584 return m_trimmed_name;
14589using TestCaseTracking::ITracker;
14590using TestCaseTracking::SectionTracker;
14591using TestCaseTracking::TrackerContext;
14595#if defined(__clang__)
14596#pragma clang diagnostic pop
14603auto makeTestInvoker(
void (*testAsFunction)()) noexcept ->
ITestInvoker* {
14604 return new (std::nothrow) TestInvokerAsFunction(testAsFunction);
14608 : name(name_), tags(tags_) {}
14613 getMutableRegistryHub().registerTest(
14614 makeTestCase(invoker, extractClassName(classOrMethod), nameAndTags, lineInfo));
14619 getMutableRegistryHub().registerStartupException();
14623AutoReg::~AutoReg() =
default;
14628#include <algorithm>
14635TestSpec::Pattern::Pattern(std::string
const& name) : m_name(name) {}
14637TestSpec::Pattern::~Pattern() =
default;
14639std::string
const& TestSpec::Pattern::name()
const {
14643TestSpec::NamePattern::NamePattern(std::string
const& name, std::string
const& filterString)
14644 : Pattern(filterString), m_wildcardPattern(toLower(name),
CaseSensitive::No) {}
14646bool TestSpec::NamePattern::matches(
TestCaseInfo const& testCase)
const {
14647 return m_wildcardPattern.matches(testCase.name);
14650TestSpec::TagPattern::TagPattern(std::string
const& tag, std::string
const& filterString)
14651 : Pattern(filterString), m_tag(toLower(tag)) {}
14653bool TestSpec::TagPattern::matches(
TestCaseInfo const& testCase)
const {
14654 return std::find(begin(testCase.lcaseTags), end(testCase.lcaseTags), m_tag) !=
14655 end(testCase.lcaseTags);
14658TestSpec::ExcludedPattern::ExcludedPattern(PatternPtr
const& underlyingPattern)
14659 : Pattern(underlyingPattern->name()), m_underlyingPattern(underlyingPattern) {}
14661bool TestSpec::ExcludedPattern::matches(
TestCaseInfo const& testCase)
const {
14662 return !m_underlyingPattern->matches(testCase);
14665bool TestSpec::Filter::matches(
TestCaseInfo const& testCase)
const {
14666 return std::all_of(m_patterns.begin(), m_patterns.end(),
14667 [&](PatternPtr
const& p) { return p->matches(testCase); });
14670std::string TestSpec::Filter::name()
const {
14672 for (
auto const& p : m_patterns)
14677bool TestSpec::hasFilters()
const {
14678 return !m_filters.empty();
14681bool TestSpec::matches(
TestCaseInfo const& testCase)
const {
14682 return std::any_of(m_filters.begin(), m_filters.end(),
14683 [&](Filter
const& f) { return f.matches(testCase); });
14686TestSpec::Matches TestSpec::matchesByFilter(std::vector<TestCase>
const& testCases,
14687 IConfig const& config)
const {
14688 Matches matches(m_filters.size());
14689 std::transform(m_filters.begin(), m_filters.end(), matches.begin(), [&](Filter
const& filter) {
14690 std::vector<TestCase const*> currentMatches;
14691 for (auto const& test : testCases)
14692 if (isThrowSafe(test, config) && filter.matches(test))
14693 currentMatches.emplace_back(&test);
14694 return FilterMatch{filter.name(), currentMatches};
14699const TestSpec::vectorStrings& TestSpec::getInvalidArgs()
const {
14700 return (m_invalidArgs);
14709TestSpecParser::TestSpecParser(ITagAliasRegistry
const& tagAliases) : m_tagAliases(&tagAliases) {}
14711TestSpecParser& TestSpecParser::parse(std::string
const& arg) {
14713 m_exclusion =
false;
14714 m_arg = m_tagAliases->expandAliases(arg);
14715 m_escapeChars.clear();
14716 m_substring.reserve(m_arg.size());
14717 m_patternName.reserve(m_arg.size());
14718 m_realPatternPos = 0;
14720 for (m_pos = 0; m_pos < m_arg.size(); ++m_pos)
14722 if (!visitChar(m_arg[m_pos])) {
14723 m_testSpec.m_invalidArgs.push_back(arg);
14729TestSpec TestSpecParser::testSpec() {
14733bool TestSpecParser::visitChar(
char c) {
14734 if ((m_mode != EscapedName) && (c ==
'\\')) {
14736 addCharToPattern(c);
14738 }
else if ((m_mode != EscapedName) && (c ==
',')) {
14744 if (processNoneChar(c))
14748 processNameChar(c);
14752 addCharToPattern(c);
14757 if (processOtherChar(c))
14763 if (!isControlChar(c)) {
14764 m_patternName += c;
14765 m_realPatternPos++;
14771bool TestSpecParser::processNoneChar(
char c) {
14776 m_exclusion =
true;
14782 startNewMode(QuotedName);
14785 startNewMode(Name);
14789void TestSpecParser::processNameChar(
char c) {
14791 if (m_substring ==
"exclude:")
14792 m_exclusion =
true;
14798bool TestSpecParser::processOtherChar(
char c) {
14799 if (!isControlChar(c))
14805void TestSpecParser::startNewMode(Mode mode) {
14808void TestSpecParser::endMode() {
14812 return addNamePattern();
14814 return addTagPattern();
14816 revertBackToLastMode();
14820 return startNewMode(None);
14823void TestSpecParser::escape() {
14825 m_mode = EscapedName;
14826 m_escapeChars.push_back(m_realPatternPos);
14828bool TestSpecParser::isControlChar(
char c)
const {
14841 return c ==
'[' || c ==
']';
14845void TestSpecParser::addFilter() {
14846 if (!m_currentFilter.m_patterns.empty()) {
14847 m_testSpec.m_filters.push_back(m_currentFilter);
14848 m_currentFilter = TestSpec::Filter();
14852void TestSpecParser::saveLastMode() {
14856void TestSpecParser::revertBackToLastMode() {
14860bool TestSpecParser::separate() {
14861 if ((m_mode == QuotedName) || (m_mode == Tag)) {
14864 m_pos = m_arg.size();
14865 m_substring.clear();
14866 m_patternName.clear();
14867 m_realPatternPos = 0;
14875std::string TestSpecParser::preprocessPattern() {
14876 std::string token = m_patternName;
14877 for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
14878 token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
14879 m_escapeChars.clear();
14880 if (startsWith(token,
"exclude:")) {
14881 m_exclusion =
true;
14882 token = token.substr(8);
14885 m_patternName.clear();
14886 m_realPatternPos = 0;
14891void TestSpecParser::addNamePattern() {
14892 auto token = preprocessPattern();
14894 if (!token.empty()) {
14895 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
14897 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14898 m_currentFilter.m_patterns.push_back(pattern);
14900 m_substring.clear();
14901 m_exclusion =
false;
14905void TestSpecParser::addTagPattern() {
14906 auto token = preprocessPattern();
14908 if (!token.empty()) {
14911 if (token.size() > 1 && token[0] ==
'.') {
14912 token.erase(token.begin());
14913 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(
".", m_substring);
14915 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14917 m_currentFilter.m_patterns.push_back(pattern);
14920 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
14923 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14925 m_currentFilter.m_patterns.push_back(pattern);
14927 m_substring.clear();
14928 m_exclusion =
false;
14932TestSpec parseTestSpec(std::string
const& arg) {
14933 return TestSpecParser(ITagAliasRegistry::get()).parse(arg).testSpec();
14942static const uint64_t nanosecondsInSecond = 1000000000;
14946auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
14947 return std::chrono::duration_cast<std::chrono::nanoseconds>(
14948 std::chrono::high_resolution_clock::now().time_since_epoch())
14953auto estimateClockResolution() -> uint64_t {
14955 static const uint64_t iterations = 1000000;
14957 auto startTime = getCurrentNanosecondsSinceEpoch();
14959 for (std::size_t i = 0; i < iterations; ++i) {
14962 uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
14964 ticks = getCurrentNanosecondsSinceEpoch();
14965 }
while (ticks == baseTicks);
14967 auto delta = ticks - baseTicks;
14973 if (ticks > startTime + 3 * nanosecondsInSecond) {
14974 return sum / (i + 1u);
14981 return sum / iterations;
14984auto getEstimatedClockResolution() -> uint64_t {
14985 static auto s_resolution = estimateClockResolution();
14986 return s_resolution;
14989void Timer::start() {
14990 m_nanoseconds = getCurrentNanosecondsSinceEpoch();
14992auto Timer::getElapsedNanoseconds() const -> uint64_t {
14993 return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
14995auto Timer::getElapsedMicroseconds() const -> uint64_t {
14996 return getElapsedNanoseconds() / 1000;
14998auto Timer::getElapsedMilliseconds() const ->
unsigned int {
14999 return static_cast<unsigned int>(getElapsedMicroseconds() / 1000);
15001auto Timer::getElapsedSeconds() const ->
double {
15002 return getElapsedMicroseconds() / 1000000.0;
15009#if defined(__clang__)
15010#pragma clang diagnostic push
15011#pragma clang diagnostic ignored "-Wexit-time-destructors"
15012#pragma clang diagnostic ignored "-Wglobal-constructors"
15016#if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
15017#define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
15027const std::string unprintableString =
"{?}";
15030const int hexThreshold = 255;
15033 enum Arch { Big, Little };
15035 static Arch which() {
15039 auto value = *
reinterpret_cast<char*
>(&one);
15040 return value ? Little : Big;
15045std::string rawMemoryToString(
const void*
object, std::size_t size) {
15047 int i = 0, end =
static_cast<int>(size), inc = 1;
15048 if (Endianness::which() == Endianness::Little) {
15053 unsigned char const* bytes =
static_cast<unsigned char const*
>(
object);
15054 ReusableStringStream rss;
15055 rss <<
"0x" << std::setfill(
'0') << std::hex;
15056 for (; i != end; i += inc)
15057 rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
15062template <
typename T> std::string fpToString(T value,
int precision) {
15063 if (Catch::isnan(value)) {
15068 rss << std::setprecision(precision) << std::fixed << value;
15069 std::string d = rss.str();
15070 std::size_t i = d.find_last_not_of(
'0');
15071 if (i != std::string::npos && i != d.size() - 1) {
15074 d = d.substr(0, i + 1);
15085std::string StringMaker<std::string>::convert(
const std::string& str) {
15086 if (!getCurrentContext().getConfig()->showInvisibles()) {
15087 return '"' + str + '"';
15090 std::string s(
"\"");
15091 for (
char c : str) {
15108#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15109std::string StringMaker<std::string_view>::convert(std::string_view str) {
15110 return ::Catch::Detail::stringify(std::string{str});
15114std::string StringMaker<char const*>::convert(
char const* str) {
15116 return ::Catch::Detail::stringify(std::string{str});
15118 return {
"{null string}"};
15121std::string StringMaker<char*>::convert(
char* str) {
15123 return ::Catch::Detail::stringify(std::string{str});
15125 return {
"{null string}"};
15129#ifdef CATCH_CONFIG_WCHAR
15130std::string StringMaker<std::wstring>::convert(
const std::wstring& wstr) {
15132 s.reserve(wstr.size());
15133 for (
auto c : wstr) {
15134 s += (c <= 0xff) ? static_cast<char>(c) : '?';
15136 return ::Catch::Detail::stringify(s);
15139#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15140std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
15141 return StringMaker<std::wstring>::convert(std::wstring(str));
15145std::string StringMaker<wchar_t const*>::convert(
wchar_t const* str) {
15147 return ::Catch::Detail::stringify(std::wstring{str});
15149 return {
"{null string}"};
15152std::string StringMaker<wchar_t*>::convert(
wchar_t* str) {
15154 return ::Catch::Detail::stringify(std::wstring{str});
15156 return {
"{null string}"};
15161#if defined(CATCH_CONFIG_CPP17_BYTE)
15163std::string StringMaker<std::byte>::convert(std::byte value) {
15164 return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
15168std::string StringMaker<int>::convert(
int value) {
15169 return ::Catch::Detail::stringify(
static_cast<long long>(value));
15171std::string StringMaker<long>::convert(
long value) {
15172 return ::Catch::Detail::stringify(
static_cast<long long>(value));
15174std::string StringMaker<long long>::convert(
long long value) {
15177 if (value > Detail::hexThreshold) {
15178 rss <<
" (0x" << std::hex << value <<
')';
15183std::string StringMaker<unsigned int>::convert(
unsigned int value) {
15184 return ::Catch::Detail::stringify(
static_cast<unsigned long long>(value));
15186std::string StringMaker<unsigned long>::convert(
unsigned long value) {
15187 return ::Catch::Detail::stringify(
static_cast<unsigned long long>(value));
15189std::string StringMaker<unsigned long long>::convert(
unsigned long long value) {
15192 if (value > Detail::hexThreshold) {
15193 rss <<
" (0x" << std::hex << value <<
')';
15198std::string StringMaker<bool>::convert(
bool b) {
15199 return b ?
"true" :
"false";
15202std::string StringMaker<signed char>::convert(
signed char value) {
15203 if (value ==
'\r') {
15205 }
else if (value ==
'\f') {
15207 }
else if (value ==
'\n') {
15209 }
else if (value ==
'\t') {
15211 }
else if (
'\0' <= value && value <
' ') {
15212 return ::Catch::Detail::stringify(
static_cast<unsigned int>(value));
15214 char chstr[] =
"' '";
15219std::string StringMaker<char>::convert(
char c) {
15220 return ::Catch::Detail::stringify(
static_cast<signed char>(c));
15222std::string StringMaker<unsigned char>::convert(
unsigned char c) {
15223 return ::Catch::Detail::stringify(
static_cast<char>(c));
15226std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
15232std::string StringMaker<float>::convert(
float value) {
15233 return fpToString(value, precision) + 'f';
15238std::string StringMaker<double>::convert(
double value) {
15239 return fpToString(value, precision);
15242std::string ratio_string<std::atto>::symbol() {
15245std::string ratio_string<std::femto>::symbol() {
15248std::string ratio_string<std::pico>::symbol() {
15251std::string ratio_string<std::nano>::symbol() {
15254std::string ratio_string<std::micro>::symbol() {
15257std::string ratio_string<std::milli>::symbol() {
15263#if defined(__clang__)
15264#pragma clang diagnostic pop
15274 diff.passed = passed - other.passed;
15275 diff.failed = failed - other.failed;
15276 diff.failedButOk = failedButOk - other.failedButOk;
15281 passed += other.passed;
15282 failed += other.failed;
15283 failedButOk += other.failedButOk;
15287std::size_t Counts::total()
const {
15288 return passed + failed + failedButOk;
15290bool Counts::allPassed()
const {
15291 return failed == 0 && failedButOk == 0;
15293bool Counts::allOk()
const {
15294 return failed == 0;
15299 diff.assertions = assertions - other.assertions;
15300 diff.testCases = testCases - other.testCases;
15305 assertions += other.assertions;
15306 testCases += other.testCases;
15311 Totals diff = *
this - prevTotals;
15312 if (diff.assertions.failed > 0)
15313 ++diff.testCases.failed;
15314 else if (diff.assertions.failedButOk > 0)
15315 ++diff.testCases.failedButOk;
15317 ++diff.testCases.passed;
15334#ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15335#define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15337#if defined(_MSC_VER)
15338#if _MSC_VER >= 1900
15339#define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15343#include <exception>
15345#if defined(__cpp_lib_uncaught_exceptions) && \
15346 !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15348#define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15351#if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && \
15352 !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && \
15353 !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15355#define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15360#include <exception>
15363bool uncaught_exceptions() {
15364#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
15366#elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15367 return std::uncaught_exceptions() > 0;
15369 return std::uncaught_exception();
15380Version::Version(
unsigned int _majorVersion,
unsigned int _minorVersion,
unsigned int _patchNumber,
15381 char const*
const _branchName,
unsigned int _buildNumber)
15382 : majorVersion(_majorVersion), minorVersion(_minorVersion), patchNumber(_patchNumber),
15383 branchName(_branchName), buildNumber(_buildNumber) {}
15385std::ostream& operator<<(std::ostream& os, Version
const& version) {
15386 os << version.majorVersion <<
'.' << version.minorVersion <<
'.' << version.patchNumber;
15388 if (version.branchName[0]) {
15389 os <<
'-' << version.branchName <<
'.' << version.buildNumber;
15394Version
const& libraryVersion() {
15395 static Version version(2, 13, 9,
"", 0);
15405WildcardPattern::WildcardPattern(std::string
const& pattern, CaseSensitive::Choice caseSensitivity)
15406 : m_caseSensitivity(caseSensitivity), m_pattern(normaliseString(pattern)) {
15407 if (startsWith(m_pattern,
'*')) {
15408 m_pattern = m_pattern.substr(1);
15409 m_wildcard = WildcardAtStart;
15411 if (endsWith(m_pattern,
'*')) {
15412 m_pattern = m_pattern.substr(0, m_pattern.size() - 1);
15413 m_wildcard =
static_cast<WildcardPosition
>(m_wildcard | WildcardAtEnd);
15417bool WildcardPattern::matches(std::string
const& str)
const {
15418 switch (m_wildcard) {
15420 return m_pattern == normaliseString(str);
15421 case WildcardAtStart:
15422 return endsWith(normaliseString(str), m_pattern);
15423 case WildcardAtEnd:
15424 return startsWith(normaliseString(str), m_pattern);
15425 case WildcardAtBothEnds:
15426 return contains(normaliseString(str), m_pattern);
15428 CATCH_INTERNAL_ERROR(
"Unknown enum");
15432std::string WildcardPattern::normaliseString(std::string
const& str)
const {
15433 return trim(m_caseSensitivity == CaseSensitive::No ? toLower(str) : str);
15440#include <type_traits>
15446size_t trailingBytes(
unsigned char c) {
15447 if ((c & 0xE0) == 0xC0) {
15450 if ((c & 0xF0) == 0xE0) {
15453 if ((c & 0xF8) == 0xF0) {
15456 CATCH_INTERNAL_ERROR(
"Invalid multibyte utf-8 start byte encountered");
15459uint32_t headerValue(
unsigned char c) {
15460 if ((c & 0xE0) == 0xC0) {
15463 if ((c & 0xF0) == 0xE0) {
15466 if ((c & 0xF8) == 0xF0) {
15469 CATCH_INTERNAL_ERROR(
"Invalid multibyte utf-8 start byte encountered");
15472void hexEscapeChar(std::ostream& os,
unsigned char c) {
15473 std::ios_base::fmtflags f(os.flags());
15474 os <<
"\\x" << std::uppercase << std::hex << std::setfill(
'0') << std::setw(2)
15475 <<
static_cast<int>(c);
15479bool shouldNewline(XmlFormatting fmt) {
15480 return !!(
static_cast<std::underlying_type<XmlFormatting>::type
>(fmt & XmlFormatting::Newline));
15483bool shouldIndent(XmlFormatting fmt) {
15484 return !!(
static_cast<std::underlying_type<XmlFormatting>::type
>(fmt & XmlFormatting::Indent));
15489XmlFormatting operator|(XmlFormatting lhs, XmlFormatting rhs) {
15490 return static_cast<XmlFormatting
>(
static_cast<std::underlying_type<XmlFormatting>::type
>(lhs) |
15491 static_cast<std::underlying_type<XmlFormatting>::type
>(rhs));
15494XmlFormatting operator&(XmlFormatting lhs, XmlFormatting rhs) {
15495 return static_cast<XmlFormatting
>(
static_cast<std::underlying_type<XmlFormatting>::type
>(lhs) &
15496 static_cast<std::underlying_type<XmlFormatting>::type
>(rhs));
15499XmlEncode::XmlEncode(std::string
const& str, ForWhat forWhat) : m_str(str), m_forWhat(forWhat) {}
15501void XmlEncode::encodeTo(std::ostream& os)
const {
15505 for (std::size_t idx = 0; idx < m_str.size(); ++idx) {
15506 unsigned char c = m_str[idx];
15517 if (idx > 2 && m_str[idx - 1] ==
']' && m_str[idx - 2] ==
']')
15524 if (m_forWhat == ForAttributes)
15536 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
15537 hexEscapeChar(os, c);
15553 if (c < 0xC0 || c >= 0xF8) {
15554 hexEscapeChar(os, c);
15558 auto encBytes = trailingBytes(c);
15560 if (idx + encBytes - 1 >= m_str.size()) {
15561 hexEscapeChar(os, c);
15568 uint32_t value = headerValue(c);
15569 for (std::size_t n = 1; n < encBytes; ++n) {
15570 unsigned char nc = m_str[idx + n];
15571 valid &= ((nc & 0xC0) == 0x80);
15572 value = (value << 6) | (nc & 0x3F);
15579 (value < 0x80) || (0x80 <= value && value < 0x800 && encBytes > 2) ||
15580 (0x800 < value && value < 0x10000 && encBytes > 3) ||
15582 (value >= 0x110000)) {
15583 hexEscapeChar(os, c);
15588 for (std::size_t n = 0; n < encBytes; ++n) {
15589 os << m_str[idx + n];
15591 idx += encBytes - 1;
15597std::ostream& operator<<(std::ostream& os, XmlEncode
const& xmlEncode) {
15598 xmlEncode.encodeTo(os);
15602XmlWriter::ScopedElement::ScopedElement(XmlWriter* writer, XmlFormatting fmt)
15603 : m_writer(writer), m_fmt(fmt) {}
15605XmlWriter::ScopedElement::ScopedElement(ScopedElement&& other) noexcept
15606 : m_writer(other.m_writer), m_fmt(other.m_fmt) {
15607 other.m_writer =
nullptr;
15608 other.m_fmt = XmlFormatting::None;
15610XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=(ScopedElement&& other)
noexcept {
15612 m_writer->endElement();
15614 m_writer = other.m_writer;
15615 other.m_writer =
nullptr;
15616 m_fmt = other.m_fmt;
15617 other.m_fmt = XmlFormatting::None;
15621XmlWriter::ScopedElement::~ScopedElement() {
15623 m_writer->endElement(m_fmt);
15627XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText(std::string
const& text,
15628 XmlFormatting fmt) {
15629 m_writer->writeText(text, fmt);
15633XmlWriter::XmlWriter(std::ostream& os) : m_os(os) {
15634 writeDeclaration();
15637XmlWriter::~XmlWriter() {
15638 while (!m_tags.empty()) {
15641 newlineIfNecessary();
15644XmlWriter& XmlWriter::startElement(std::string
const& name, XmlFormatting fmt) {
15646 newlineIfNecessary();
15647 if (shouldIndent(fmt)) {
15651 m_os <<
'<' << name;
15652 m_tags.push_back(name);
15653 m_tagIsOpen =
true;
15654 applyFormatting(fmt);
15658XmlWriter::ScopedElement XmlWriter::scopedElement(std::string
const& name, XmlFormatting fmt) {
15659 ScopedElement scoped(
this, fmt);
15660 startElement(name, fmt);
15664XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
15665 m_indent = m_indent.substr(0, m_indent.size() - 2);
15669 m_tagIsOpen =
false;
15671 newlineIfNecessary();
15672 if (shouldIndent(fmt)) {
15675 m_os <<
"</" << m_tags.back() <<
">";
15677 m_os << std::flush;
15678 applyFormatting(fmt);
15683XmlWriter& XmlWriter::writeAttribute(std::string
const& name, std::string
const& attribute) {
15684 if (!name.empty() && !attribute.empty())
15685 m_os <<
' ' << name <<
"=\"" << XmlEncode(attribute, XmlEncode::ForAttributes) <<
'"';
15689XmlWriter& XmlWriter::writeAttribute(std::string
const& name,
bool attribute) {
15690 m_os <<
' ' << name <<
"=\"" << (attribute ?
"true" :
"false") <<
'"';
15694XmlWriter& XmlWriter::writeText(std::string
const& text, XmlFormatting fmt) {
15695 if (!text.empty()) {
15696 bool tagWasOpen = m_tagIsOpen;
15698 if (tagWasOpen && shouldIndent(fmt)) {
15701 m_os << XmlEncode(text);
15702 applyFormatting(fmt);
15707XmlWriter& XmlWriter::writeComment(std::string
const& text, XmlFormatting fmt) {
15709 if (shouldIndent(fmt)) {
15712 m_os <<
"<!--" << text <<
"-->";
15713 applyFormatting(fmt);
15717void XmlWriter::writeStylesheetRef(std::string
const& url) {
15718 m_os <<
"<?xml-stylesheet type=\"text/xsl\" href=\"" << url <<
"\"?>\n";
15721XmlWriter& XmlWriter::writeBlankLine() {
15727void XmlWriter::ensureTagClosed() {
15729 m_os <<
'>' << std::flush;
15730 newlineIfNecessary();
15731 m_tagIsOpen =
false;
15735void XmlWriter::applyFormatting(XmlFormatting fmt) {
15736 m_needsNewline = shouldNewline(fmt);
15739void XmlWriter::writeDeclaration() {
15740 m_os <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
15743void XmlWriter::newlineIfNecessary() {
15744 if (m_needsNewline) {
15746 m_needsNewline =
false;
15760void prepareExpandedExpression(AssertionResult& result) {
15761 result.getExpandedExpression();
15766std::string getFormattedDuration(
double duration) {
15771 const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
15772 char buffer[maxDoubleSize];
15777 sprintf_s(buffer,
"%.3f", duration);
15779 std::sprintf(buffer,
"%.3f", duration);
15781 return std::string(buffer);
15784bool shouldShowDuration(
IConfig const& config,
double duration) {
15785 if (config.showDurations() == ShowDurations::Always) {
15788 if (config.showDurations() == ShowDurations::Never) {
15791 const double min = config.minDuration();
15792 return min >= 0 && duration >= min;
15795std::string serializeFilters(std::vector<std::string>
const& container) {
15798 for (
auto&& filter : container) {
15809TestEventListenerBase::TestEventListenerBase(ReporterConfig
const& _config)
15810 : StreamingReporterBase(_config) {}
15812std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
15813 return {Verbosity::Quiet, Verbosity::Normal, Verbosity::High};
15816void TestEventListenerBase::assertionStarting(
AssertionInfo const&) {}
15818bool TestEventListenerBase::assertionEnded(AssertionStats
const&) {
15828#ifdef CATCH_PLATFORM_MAC
15829const char* failedString() {
15832const char* passedString() {
15836const char* failedString() {
15839const char* passedString() {
15845Catch::Colour::Code dimColour() {
15846 return Catch::Colour::FileName;
15849std::string bothOrAll(std::size_t count) {
15850 return count == 1 ? std::string() : count == 2 ?
"both " :
"all ";
15863void printTotals(std::ostream& out,
const Totals& totals) {
15864 if (totals.testCases.total() == 0) {
15865 out <<
"No tests ran.";
15866 }
else if (totals.testCases.failed == totals.testCases.total()) {
15867 Colour colour(Colour::ResultError);
15868 const std::string qualify_assertions_failed =
15869 totals.assertions.failed == totals.assertions.total()
15870 ? bothOrAll(totals.assertions.failed)
15872 out <<
"Failed " << bothOrAll(totals.testCases.failed)
15873 <<
pluralise(totals.testCases.failed,
"test case")
15876 << qualify_assertions_failed <<
pluralise(totals.assertions.failed,
"assertion") <<
'.';
15877 }
else if (totals.assertions.total() == 0) {
15878 out <<
"Passed " << bothOrAll(totals.testCases.total())
15879 <<
pluralise(totals.testCases.total(),
"test case") <<
" (no assertions).";
15880 }
else if (totals.assertions.failed) {
15881 Colour colour(Colour::ResultError);
15882 out <<
"Failed " <<
pluralise(totals.testCases.failed,
"test case")
15885 <<
pluralise(totals.assertions.failed,
"assertion") <<
'.';
15887 Colour colour(Colour::ResultSuccess);
15888 out <<
"Passed " << bothOrAll(totals.testCases.passed)
15889 <<
pluralise(totals.testCases.passed,
"test case") <<
" with "
15890 <<
pluralise(totals.assertions.passed,
"assertion") <<
'.';
15895class AssertionPrinter {
15897 AssertionPrinter& operator=(AssertionPrinter
const&) =
delete;
15898 AssertionPrinter(AssertionPrinter
const&) =
delete;
15899 AssertionPrinter(std::ostream& _stream, AssertionStats
const& _stats,
bool _printInfoMessages)
15900 : stream(_stream), result(_stats.assertionResult), messages(_stats.infoMessages),
15901 itMessage(_stats.infoMessages.begin()), printInfoMessages(_printInfoMessages) {}
15906 itMessage = messages.begin();
15908 switch (result.getResultType()) {
15909 case ResultWas::Ok:
15910 printResultType(Colour::ResultSuccess, passedString());
15911 printOriginalExpression();
15912 printReconstructedExpression();
15913 if (!result.hasExpression())
15914 printRemainingMessages(Colour::None);
15916 printRemainingMessages();
15918 case ResultWas::ExpressionFailed:
15920 printResultType(Colour::ResultSuccess,
15921 failedString() + std::string(
" - but was ok"));
15923 printResultType(Colour::Error, failedString());
15924 printOriginalExpression();
15925 printReconstructedExpression();
15926 printRemainingMessages();
15928 case ResultWas::ThrewException:
15929 printResultType(Colour::Error, failedString());
15930 printIssue(
"unexpected exception with message:");
15932 printExpressionWas();
15933 printRemainingMessages();
15935 case ResultWas::FatalErrorCondition:
15936 printResultType(Colour::Error, failedString());
15937 printIssue(
"fatal error condition with message:");
15939 printExpressionWas();
15940 printRemainingMessages();
15942 case ResultWas::DidntThrowException:
15943 printResultType(Colour::Error, failedString());
15944 printIssue(
"expected exception, got none");
15945 printExpressionWas();
15946 printRemainingMessages();
15948 case ResultWas::Info:
15949 printResultType(Colour::None,
"info");
15951 printRemainingMessages();
15953 case ResultWas::Warning:
15954 printResultType(Colour::None,
"warning");
15956 printRemainingMessages();
15958 case ResultWas::ExplicitFailure:
15959 printResultType(Colour::Error, failedString());
15960 printIssue(
"explicitly");
15961 printRemainingMessages(Colour::None);
15964 case ResultWas::Unknown:
15965 case ResultWas::FailureBit:
15966 case ResultWas::Exception:
15967 printResultType(Colour::Error,
"** internal error **");
15973 void printSourceInfo()
const {
15974 Colour colourGuard(Colour::FileName);
15975 stream << result.getSourceInfo() <<
':';
15978 void printResultType(Colour::Code colour, std::string
const& passOrFail)
const {
15979 if (!passOrFail.empty()) {
15981 Colour colourGuard(colour);
15982 stream <<
' ' << passOrFail;
15988 void printIssue(std::string
const& issue)
const { stream <<
' ' << issue; }
15990 void printExpressionWas() {
15991 if (result.hasExpression()) {
15994 Colour colour(dimColour());
15995 stream <<
" expression was:";
15997 printOriginalExpression();
16001 void printOriginalExpression()
const {
16002 if (result.hasExpression()) {
16003 stream <<
' ' << result.getExpression();
16007 void printReconstructedExpression()
const {
16008 if (result.hasExpandedExpression()) {
16010 Colour colour(dimColour());
16011 stream <<
" for: ";
16013 stream << result.getExpandedExpression();
16017 void printMessage() {
16018 if (itMessage != messages.end()) {
16019 stream <<
" '" << itMessage->message <<
'\'';
16024 void printRemainingMessages(Colour::Code colour = dimColour()) {
16025 if (itMessage == messages.end())
16028 const auto itEnd = messages.cend();
16029 const auto N =
static_cast<std::size_t
>(std::distance(itMessage, itEnd));
16032 Colour colourGuard(colour);
16033 stream <<
" with " << pluralise(N,
"message") <<
':';
16036 while (itMessage != itEnd) {
16038 if (printInfoMessages || itMessage->type != ResultWas::Info) {
16040 if (itMessage != itEnd) {
16041 Colour colourGuard(dimColour());
16051 std::ostream& stream;
16052 AssertionResult
const& result;
16053 std::vector<MessageInfo> messages;
16054 std::vector<MessageInfo>::const_iterator itMessage;
16055 bool printInfoMessages;
16060std::string CompactReporter::getDescription() {
16061 return "Reports test results on a single line, suitable for IDEs";
16064void CompactReporter::noMatchingTestCases(std::string
const& spec) {
16065 stream <<
"No test cases matched '" << spec <<
'\'' << std::endl;
16068void CompactReporter::assertionStarting(
AssertionInfo const&) {}
16070bool CompactReporter::assertionEnded(AssertionStats
const& _assertionStats) {
16071 AssertionResult
const& result = _assertionStats.assertionResult;
16073 bool printInfoMessages =
true;
16076 if (!m_config->includeSuccessfulResults() && result.isOk()) {
16077 if (result.getResultType() != ResultWas::Warning)
16079 printInfoMessages =
false;
16082 AssertionPrinter printer(stream, _assertionStats, printInfoMessages);
16085 stream << std::endl;
16089void CompactReporter::sectionEnded(SectionStats
const& _sectionStats) {
16090 double dur = _sectionStats.durationInSeconds;
16091 if (shouldShowDuration(*m_config, dur)) {
16092 stream << getFormattedDuration(dur) <<
" s: " << _sectionStats.sectionInfo.name
16097void CompactReporter::testRunEnded(TestRunStats
const& _testRunStats) {
16098 printTotals(stream, _testRunStats.totals);
16099 stream <<
'\n' << std::endl;
16100 StreamingReporterBase::testRunEnded(_testRunStats);
16103CompactReporter::~CompactReporter() {}
16105CATCH_REGISTER_REPORTER(
"compact", CompactReporter)
16114#if defined(_MSC_VER)
16115#pragma warning(push)
16116#pragma warning(disable : 4061)
16121#if defined(__clang__)
16122#pragma clang diagnostic push
16124#pragma clang diagnostic ignored "-Wunused-function"
16132class ConsoleAssertionPrinter {
16134 ConsoleAssertionPrinter& operator=(ConsoleAssertionPrinter
const&) =
delete;
16135 ConsoleAssertionPrinter(ConsoleAssertionPrinter
const&) =
delete;
16136 ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats
const& _stats,
16137 bool _printInfoMessages)
16138 : stream(_stream), stats(_stats), result(_stats.assertionResult), colour(Colour::None),
16139 message(result.getMessage()), messages(_stats.infoMessages),
16140 printInfoMessages(_printInfoMessages) {
16141 switch (result.getResultType()) {
16142 case ResultWas::Ok:
16143 colour = Colour::Success;
16144 passOrFail =
"PASSED";
16146 if (_stats.infoMessages.size() == 1)
16147 messageLabel =
"with message";
16148 if (_stats.infoMessages.size() > 1)
16149 messageLabel =
"with messages";
16151 case ResultWas::ExpressionFailed:
16152 if (result.isOk()) {
16153 colour = Colour::Success;
16154 passOrFail =
"FAILED - but was ok";
16156 colour = Colour::Error;
16157 passOrFail =
"FAILED";
16159 if (_stats.infoMessages.size() == 1)
16160 messageLabel =
"with message";
16161 if (_stats.infoMessages.size() > 1)
16162 messageLabel =
"with messages";
16164 case ResultWas::ThrewException:
16165 colour = Colour::Error;
16166 passOrFail =
"FAILED";
16167 messageLabel =
"due to unexpected exception with ";
16168 if (_stats.infoMessages.size() == 1)
16169 messageLabel +=
"message";
16170 if (_stats.infoMessages.size() > 1)
16171 messageLabel +=
"messages";
16173 case ResultWas::FatalErrorCondition:
16174 colour = Colour::Error;
16175 passOrFail =
"FAILED";
16176 messageLabel =
"due to a fatal error condition";
16178 case ResultWas::DidntThrowException:
16179 colour = Colour::Error;
16180 passOrFail =
"FAILED";
16181 messageLabel =
"because no exception was thrown where one was expected";
16183 case ResultWas::Info:
16184 messageLabel =
"info";
16186 case ResultWas::Warning:
16187 messageLabel =
"warning";
16189 case ResultWas::ExplicitFailure:
16190 passOrFail =
"FAILED";
16191 colour = Colour::Error;
16192 if (_stats.infoMessages.size() == 1)
16193 messageLabel =
"explicitly with message";
16194 if (_stats.infoMessages.size() > 1)
16195 messageLabel =
"explicitly with messages";
16198 case ResultWas::Unknown:
16199 case ResultWas::FailureBit:
16200 case ResultWas::Exception:
16201 passOrFail =
"** internal error **";
16202 colour = Colour::Error;
16207 void print()
const {
16209 if (stats.totals.assertions.total() > 0) {
16211 printOriginalExpression();
16212 printReconstructedExpression();
16220 void printResultType()
const {
16221 if (!passOrFail.empty()) {
16222 Colour colourGuard(colour);
16223 stream << passOrFail <<
":\n";
16226 void printOriginalExpression()
const {
16227 if (result.hasExpression()) {
16228 Colour colourGuard(Colour::OriginalExpression);
16230 stream << result.getExpressionInMacro();
16234 void printReconstructedExpression()
const {
16235 if (result.hasExpandedExpression()) {
16236 stream <<
"with expansion:\n";
16237 Colour colourGuard(Colour::ReconstructedExpression);
16238 stream << Column(result.getExpandedExpression()).indent(2) <<
'\n';
16241 void printMessage()
const {
16242 if (!messageLabel.empty())
16243 stream << messageLabel <<
':' <<
'\n';
16244 for (
auto const& msg : messages) {
16246 if (printInfoMessages || msg.type != ResultWas::Info)
16247 stream << Column(msg.message).indent(2) <<
'\n';
16250 void printSourceInfo()
const {
16251 Colour colourGuard(Colour::FileName);
16252 stream << result.getSourceInfo() <<
": ";
16255 std::ostream& stream;
16256 AssertionStats
const& stats;
16257 AssertionResult
const& result;
16258 Colour::Code colour;
16259 std::string passOrFail;
16260 std::string messageLabel;
16261 std::string message;
16262 std::vector<MessageInfo> messages;
16263 bool printInfoMessages;
16266std::size_t makeRatio(std::size_t number, std::size_t total) {
16267 std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
16268 return (ratio == 0 && number > 0) ? 1 : ratio;
16271std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
16272 if (i > j && i > k)
16281 enum Justification { Left, Right };
16284 Justification justification;
16286struct ColumnBreak {};
16290 enum class Unit { Auto, Nanoseconds, Microseconds, Milliseconds, Seconds, Minutes };
16291 static const uint64_t s_nanosecondsInAMicrosecond = 1000;
16292 static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
16293 static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
16294 static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
16296 double m_inNanoseconds;
16300 explicit Duration(
double inNanoseconds, Unit units = Unit::Auto)
16301 : m_inNanoseconds(inNanoseconds), m_units(units) {
16302 if (m_units == Unit::Auto) {
16303 if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
16304 m_units = Unit::Nanoseconds;
16305 else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
16306 m_units = Unit::Microseconds;
16307 else if (m_inNanoseconds < s_nanosecondsInASecond)
16308 m_units = Unit::Milliseconds;
16309 else if (m_inNanoseconds < s_nanosecondsInAMinute)
16310 m_units = Unit::Seconds;
16312 m_units = Unit::Minutes;
16316 auto value() const ->
double {
16318 case Unit::Microseconds:
16319 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMicrosecond);
16320 case Unit::Milliseconds:
16321 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMillisecond);
16322 case Unit::Seconds:
16323 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInASecond);
16324 case Unit::Minutes:
16325 return m_inNanoseconds /
static_cast<double>(s_nanosecondsInAMinute);
16327 return m_inNanoseconds;
16330 auto unitsAsString() const -> std::
string {
16332 case Unit::Nanoseconds:
16334 case Unit::Microseconds:
16336 case Unit::Milliseconds:
16338 case Unit::Seconds:
16340 case Unit::Minutes:
16343 return "** internal error **";
16346 friend auto operator<<(std::ostream& os, Duration
const& duration) -> std::ostream& {
16347 return os << duration.value() <<
' ' << duration.unitsAsString();
16352class TablePrinter {
16353 std::ostream& m_os;
16354 std::vector<ColumnInfo> m_columnInfos;
16355 std::ostringstream m_oss;
16356 int m_currentColumn = -1;
16357 bool m_isOpen =
false;
16360 TablePrinter(std::ostream& os, std::vector<ColumnInfo> columnInfos)
16361 : m_os(os), m_columnInfos(std::move(columnInfos)) {}
16363 auto columnInfos() const -> std::vector<ColumnInfo> const& {
return m_columnInfos; }
16368 *
this << RowBreak();
16370 Columns headerCols;
16372 for (
auto const& info : m_columnInfos) {
16373 headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
16374 headerCols += spacer;
16376 m_os << headerCols <<
'\n';
16378 m_os << Catch::getLineOfChars<
'-'>() <<
'\n';
16383 *
this << RowBreak();
16389 template <
typename T>
friend TablePrinter& operator<<(TablePrinter& tp, T
const& value) {
16394 friend TablePrinter& operator<<(TablePrinter& tp, ColumnBreak) {
16395 auto colStr = tp.m_oss.str();
16396 const auto strSize = colStr.size();
16399 if (tp.m_currentColumn ==
static_cast<int>(tp.m_columnInfos.size() - 1)) {
16400 tp.m_currentColumn = -1;
16403 tp.m_currentColumn++;
16405 auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
16406 auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
16407 ? std::string(colInfo.width - (strSize + 1), ' ')
16409 if (colInfo.justification == ColumnInfo::Left)
16410 tp.m_os << colStr << padding <<
' ';
16412 tp.m_os << padding << colStr <<
' ';
16416 friend TablePrinter& operator<<(TablePrinter& tp, RowBreak) {
16417 if (tp.m_currentColumn > 0) {
16419 tp.m_currentColumn = -1;
16425ConsoleReporter::ConsoleReporter(ReporterConfig
const& config)
16426 : StreamingReporterBase(config),
16427 m_tablePrinter(new TablePrinter(config.stream(), [&config]() -> std::vector<ColumnInfo> {
16428 if (config.fullConfig()->benchmarkNoAnalysis()) {
16429 return {{
"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left},
16430 {
" samples", 14, ColumnInfo::Right},
16431 {
" iterations", 14, ColumnInfo::Right},
16432 {
" mean", 14, ColumnInfo::Right}};
16434 return {{
"benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left},
16435 {
"samples mean std dev", 14, ColumnInfo::Right},
16436 {
"iterations low mean low std dev", 14, ColumnInfo::Right},
16437 {
"estimated high mean high std dev", 14, ColumnInfo::Right}};
16440ConsoleReporter::~ConsoleReporter() =
default;
16442std::string ConsoleReporter::getDescription() {
16443 return "Reports test results as plain lines of text";
16446void ConsoleReporter::noMatchingTestCases(std::string
const& spec) {
16447 stream <<
"No test cases matched '" << spec <<
'\'' << std::endl;
16450void ConsoleReporter::reportInvalidArguments(std::string
const& arg) {
16451 stream <<
"Invalid Filter: " << arg << std::endl;
16454void ConsoleReporter::assertionStarting(
AssertionInfo const&) {}
16456bool ConsoleReporter::assertionEnded(AssertionStats
const& _assertionStats) {
16457 AssertionResult
const& result = _assertionStats.assertionResult;
16459 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
16462 if (!includeResults && result.getResultType() != ResultWas::Warning)
16467 ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
16469 stream << std::endl;
16473void ConsoleReporter::sectionStarting(
SectionInfo const& _sectionInfo) {
16474 m_tablePrinter->close();
16475 m_headerPrinted =
false;
16476 StreamingReporterBase::sectionStarting(_sectionInfo);
16478void ConsoleReporter::sectionEnded(SectionStats
const& _sectionStats) {
16479 m_tablePrinter->close();
16480 if (_sectionStats.missingAssertions) {
16482 Colour colour(Colour::ResultError);
16483 if (m_sectionStack.size() > 1)
16484 stream <<
"\nNo assertions in section";
16486 stream <<
"\nNo assertions in test case";
16487 stream <<
" '" << _sectionStats.sectionInfo.name <<
"'\n" << std::endl;
16489 double dur = _sectionStats.durationInSeconds;
16490 if (shouldShowDuration(*m_config, dur)) {
16491 stream << getFormattedDuration(dur) <<
" s: " << _sectionStats.sectionInfo.name
16494 if (m_headerPrinted) {
16495 m_headerPrinted =
false;
16497 StreamingReporterBase::sectionEnded(_sectionStats);
16500#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
16501void ConsoleReporter::benchmarkPreparing(std::string
const& name) {
16502 lazyPrintWithoutClosingBenchmarkTable();
16505 Column(name).width(
static_cast<std::size_t
>(m_tablePrinter->columnInfos()[0].width - 2));
16507 bool firstLine =
true;
16508 for (
auto line : nameCol) {
16510 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
16514 (*m_tablePrinter) << line << ColumnBreak();
16518void ConsoleReporter::benchmarkStarting(BenchmarkInfo
const& info) {
16519 (*m_tablePrinter) << info.samples << ColumnBreak() << info.iterations << ColumnBreak();
16520 if (!m_config->benchmarkNoAnalysis())
16521 (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
16523void ConsoleReporter::benchmarkEnded(BenchmarkStats<>
const& stats) {
16524 if (m_config->benchmarkNoAnalysis()) {
16525 (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
16527 (*m_tablePrinter) << ColumnBreak() << Duration(stats.mean.point.count()) << ColumnBreak()
16528 << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
16529 << Duration(stats.mean.upper_bound.count()) << ColumnBreak()
16530 << ColumnBreak() << Duration(stats.standardDeviation.point.count())
16531 << ColumnBreak() << Duration(stats.standardDeviation.lower_bound.count())
16532 << ColumnBreak() << Duration(stats.standardDeviation.upper_bound.count())
16533 << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak()
16538void ConsoleReporter::benchmarkFailed(std::string
const& error) {
16539 Colour colour(Colour::Red);
16540 (*m_tablePrinter) <<
"Benchmark failed (" <<
error <<
')' << ColumnBreak() << RowBreak();
16544void ConsoleReporter::testCaseEnded(TestCaseStats
const& _testCaseStats) {
16545 m_tablePrinter->close();
16546 StreamingReporterBase::testCaseEnded(_testCaseStats);
16547 m_headerPrinted =
false;
16549void ConsoleReporter::testGroupEnded(TestGroupStats
const& _testGroupStats) {
16550 if (currentGroupInfo.used) {
16551 printSummaryDivider();
16552 stream <<
"Summary for group '" << _testGroupStats.groupInfo.name <<
"':\n";
16553 printTotals(_testGroupStats.totals);
16554 stream <<
'\n' << std::endl;
16556 StreamingReporterBase::testGroupEnded(_testGroupStats);
16558void ConsoleReporter::testRunEnded(TestRunStats
const& _testRunStats) {
16559 printTotalsDivider(_testRunStats.totals);
16560 printTotals(_testRunStats.totals);
16561 stream << std::endl;
16562 StreamingReporterBase::testRunEnded(_testRunStats);
16564void ConsoleReporter::testRunStarting(TestRunInfo
const& _testInfo) {
16565 StreamingReporterBase::testRunStarting(_testInfo);
16566 printTestFilters();
16569void ConsoleReporter::lazyPrint() {
16571 m_tablePrinter->close();
16572 lazyPrintWithoutClosingBenchmarkTable();
16575void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
16577 if (!currentTestRunInfo.used)
16578 lazyPrintRunInfo();
16579 if (!currentGroupInfo.used)
16580 lazyPrintGroupInfo();
16582 if (!m_headerPrinted) {
16583 printTestCaseAndSectionHeader();
16584 m_headerPrinted =
true;
16587void ConsoleReporter::lazyPrintRunInfo() {
16588 stream << '\n' << getLineOfChars<'~'>() <<
'\n';
16589 Colour colour(Colour::SecondaryText);
16590 stream << currentTestRunInfo->name <<
" is a Catch v" << libraryVersion()
16591 <<
" host application.\n"
16592 <<
"Run with -? for options\n\n";
16594 if (m_config->rngSeed() != 0)
16595 stream <<
"Randomness seeded to: " << m_config->rngSeed() <<
"\n\n";
16597 currentTestRunInfo.used =
true;
16599void ConsoleReporter::lazyPrintGroupInfo() {
16600 if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
16601 printClosedHeader(
"Group: " + currentGroupInfo->name);
16602 currentGroupInfo.used =
true;
16605void ConsoleReporter::printTestCaseAndSectionHeader() {
16606 assert(!m_sectionStack.empty());
16607 printOpenHeader(currentTestCaseInfo->name);
16609 if (m_sectionStack.size() > 1) {
16610 Colour colourGuard(Colour::Headers);
16612 auto it = m_sectionStack.begin() + 1,
16613 itEnd = m_sectionStack.end();
16614 for (; it != itEnd; ++it)
16615 printHeaderString(it->name, 2);
16620 stream << getLineOfChars<
'-'>() <<
'\n';
16621 Colour colourGuard(Colour::FileName);
16622 stream << lineInfo <<
'\n';
16623 stream << getLineOfChars<
'.'>() <<
'\n' << std::endl;
16626void ConsoleReporter::printClosedHeader(std::string
const& _name) {
16627 printOpenHeader(_name);
16628 stream << getLineOfChars<
'.'>() <<
'\n';
16630void ConsoleReporter::printOpenHeader(std::string
const& _name) {
16631 stream << getLineOfChars<
'-'>() <<
'\n';
16633 Colour colourGuard(Colour::Headers);
16634 printHeaderString(_name);
16640void ConsoleReporter::printHeaderString(std::string
const& _string, std::size_t indent) {
16641 std::size_t i = _string.find(
": ");
16642 if (i != std::string::npos)
16646 stream << Column(_string).indent(indent + i).initialIndent(indent) <<
'\n';
16649struct SummaryColumn {
16651 SummaryColumn(std::string _label, Colour::Code _colour)
16652 : label(std::move(_label)), colour(_colour) {}
16653 SummaryColumn addRow(std::size_t count) {
16654 ReusableStringStream rss;
16656 std::string row = rss.str();
16657 for (
auto& oldRow : rows) {
16658 while (oldRow.size() < row.size())
16659 oldRow =
' ' + oldRow;
16660 while (oldRow.size() > row.size())
16663 rows.push_back(row);
16668 Colour::Code colour;
16669 std::vector<std::string> rows;
16672void ConsoleReporter::printTotals(
Totals const& totals) {
16673 if (totals.testCases.total() == 0) {
16674 stream << Colour(Colour::Warning) <<
"No tests ran\n";
16675 }
else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
16676 stream << Colour(Colour::ResultSuccess) <<
"All tests passed";
16677 stream <<
" (" <<
pluralise(totals.assertions.passed,
"assertion") <<
" in "
16678 <<
pluralise(totals.testCases.passed,
"test case") <<
')' <<
'\n';
16681 std::vector<SummaryColumn> columns;
16682 columns.push_back(SummaryColumn(
"", Colour::None)
16683 .addRow(totals.testCases.total())
16684 .addRow(totals.assertions.total()));
16685 columns.push_back(SummaryColumn(
"passed", Colour::Success)
16686 .addRow(totals.testCases.passed)
16687 .addRow(totals.assertions.passed));
16688 columns.push_back(SummaryColumn(
"failed", Colour::ResultError)
16689 .addRow(totals.testCases.failed)
16690 .addRow(totals.assertions.failed));
16691 columns.push_back(SummaryColumn(
"failed as expected", Colour::ResultExpectedFailure)
16692 .addRow(totals.testCases.failedButOk)
16693 .addRow(totals.assertions.failedButOk));
16695 printSummaryRow(
"test cases", columns, 0);
16696 printSummaryRow(
"assertions", columns, 1);
16699void ConsoleReporter::printSummaryRow(std::string
const& label,
16700 std::vector<SummaryColumn>
const& cols, std::size_t row) {
16701 for (
auto col : cols) {
16702 std::string value = col.rows[row];
16703 if (col.label.empty()) {
16704 stream << label <<
": ";
16708 stream << Colour(Colour::Warning) <<
"- none -";
16709 }
else if (value !=
"0") {
16710 stream << Colour(Colour::LightGrey) <<
" | ";
16711 stream << Colour(col.colour) << value <<
' ' << col.label;
16717void ConsoleReporter::printTotalsDivider(
Totals const& totals) {
16718 if (totals.testCases.total() > 0) {
16719 std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
16720 std::size_t failedButOkRatio =
16721 makeRatio(totals.testCases.failedButOk, totals.testCases.total());
16722 std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
16723 while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
16724 findMax(failedRatio, failedButOkRatio, passedRatio)++;
16725 while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
16726 findMax(failedRatio, failedButOkRatio, passedRatio)--;
16728 stream << Colour(Colour::Error) << std::string(failedRatio,
'=');
16729 stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio,
'=');
16730 if (totals.testCases.allPassed())
16731 stream << Colour(Colour::ResultSuccess) << std::string(passedRatio,
'=');
16733 stream << Colour(Colour::Success) << std::string(passedRatio,
'=');
16735 stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1,
'=');
16739void ConsoleReporter::printSummaryDivider() {
16740 stream << getLineOfChars<
'-'>() <<
'\n';
16743void ConsoleReporter::printTestFilters() {
16744 if (m_config->testSpec().hasFilters()) {
16745 Colour guard(Colour::BrightYellow);
16746 stream <<
"Filters: " << serializeFilters(m_config->getTestsOrTags()) <<
'\n';
16750CATCH_REGISTER_REPORTER(
"console", ConsoleReporter)
16754#if defined(_MSC_VER)
16755#pragma warning(pop)
16758#if defined(__clang__)
16759#pragma clang diagnostic pop
16764#include <algorithm>
16773std::string getCurrentTimestamp() {
16777 std::time(&rawtime);
16778 auto const timeStampSize =
sizeof(
"2017-01-16T17:06:45Z");
16781 std::tm timeInfo = {};
16782 gmtime_s(&timeInfo, &rawtime);
16785 timeInfo = std::gmtime(&rawtime);
16788 char timeStamp[timeStampSize];
16789 const char*
const fmt =
"%Y-%m-%dT%H:%M:%SZ";
16792 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
16794 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
16796 return std::string(timeStamp, timeStampSize - 1);
16799std::string fileNameTag(
const std::vector<std::string>& tags) {
16800 auto it = std::find_if(begin(tags), end(tags),
16801 [](std::string
const& tag) {
return tag.front() ==
'#'; });
16802 if (it != tags.end())
16803 return it->substr(1);
16804 return std::string();
16811std::string formatDuration(
double seconds) {
16813 rss << std::fixed << std::setprecision(3) << seconds;
16819JunitReporter::JunitReporter(ReporterConfig
const& _config)
16820 : CumulativeReporterBase(_config), xml(_config.stream()) {
16821 m_reporterPrefs.shouldRedirectStdOut =
true;
16822 m_reporterPrefs.shouldReportAllAssertions =
true;
16825JunitReporter::~JunitReporter() {}
16827std::string JunitReporter::getDescription() {
16828 return "Reports test results in an XML format that looks like Ant's "
16829 "junitreport target";
16832void JunitReporter::noMatchingTestCases(std::string
const& ) {}
16834void JunitReporter::testRunStarting(TestRunInfo
const& runInfo) {
16835 CumulativeReporterBase::testRunStarting(runInfo);
16836 xml.startElement(
"testsuites");
16839void JunitReporter::testGroupStarting(GroupInfo
const& groupInfo) {
16840 suiteTimer.start();
16841 stdOutForSuite.clear();
16842 stdErrForSuite.clear();
16843 unexpectedExceptions = 0;
16844 CumulativeReporterBase::testGroupStarting(groupInfo);
16847void JunitReporter::testCaseStarting(
TestCaseInfo const& testCaseInfo) {
16848 m_okToFail = testCaseInfo.okToFail();
16851bool JunitReporter::assertionEnded(AssertionStats
const& assertionStats) {
16852 if (assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail)
16853 unexpectedExceptions++;
16854 return CumulativeReporterBase::assertionEnded(assertionStats);
16857void JunitReporter::testCaseEnded(TestCaseStats
const& testCaseStats) {
16858 stdOutForSuite += testCaseStats.stdOut;
16859 stdErrForSuite += testCaseStats.stdErr;
16860 CumulativeReporterBase::testCaseEnded(testCaseStats);
16863void JunitReporter::testGroupEnded(TestGroupStats
const& testGroupStats) {
16864 double suiteTime = suiteTimer.getElapsedSeconds();
16865 CumulativeReporterBase::testGroupEnded(testGroupStats);
16866 writeGroup(*m_testGroups.back(), suiteTime);
16869void JunitReporter::testRunEndedCumulative() {
16873void JunitReporter::writeGroup(TestGroupNode
const& groupNode,
double suiteTime) {
16874 XmlWriter::ScopedElement e = xml.scopedElement(
"testsuite");
16876 TestGroupStats
const& stats = groupNode.value;
16877 xml.writeAttribute(
"name", stats.groupInfo.name);
16878 xml.writeAttribute(
"errors", unexpectedExceptions);
16879 xml.writeAttribute(
"failures", stats.totals.assertions.failed - unexpectedExceptions);
16880 xml.writeAttribute(
"tests", stats.totals.assertions.total());
16881 xml.writeAttribute(
"hostname",
"tbd");
16882 if (m_config->showDurations() == ShowDurations::Never)
16883 xml.writeAttribute(
"time",
"");
16885 xml.writeAttribute(
"time", formatDuration(suiteTime));
16886 xml.writeAttribute(
"timestamp", getCurrentTimestamp());
16889 if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
16890 auto properties = xml.scopedElement(
"properties");
16891 if (m_config->hasTestFilters()) {
16892 xml.scopedElement(
"property")
16893 .writeAttribute(
"name",
"filters")
16894 .writeAttribute(
"value", serializeFilters(m_config->getTestsOrTags()));
16896 if (m_config->rngSeed() != 0) {
16897 xml.scopedElement(
"property")
16898 .writeAttribute(
"name",
"random-seed")
16899 .writeAttribute(
"value", m_config->rngSeed());
16904 for (
auto const& child : groupNode.children)
16905 writeTestCase(*child);
16907 xml.scopedElement(
"system-out").writeText(trim(stdOutForSuite), XmlFormatting::Newline);
16908 xml.scopedElement(
"system-err").writeText(trim(stdErrForSuite), XmlFormatting::Newline);
16911void JunitReporter::writeTestCase(TestCaseNode
const& testCaseNode) {
16912 TestCaseStats
const& stats = testCaseNode.value;
16916 assert(testCaseNode.children.size() == 1);
16917 SectionNode
const& rootSection = *testCaseNode.children.front();
16919 std::string className = stats.testInfo.className;
16921 if (className.empty()) {
16922 className = fileNameTag(stats.testInfo.tags);
16923 if (className.empty())
16924 className =
"global";
16927 if (!m_config->name().empty())
16928 className = m_config->name() + "." + className;
16930 writeSection(className,
"", rootSection, stats.testInfo.okToFail());
16933void JunitReporter::writeSection(std::string
const& className, std::string
const& rootName,
16934 SectionNode
const& sectionNode,
bool testOkToFail) {
16935 std::string name = trim(sectionNode.stats.sectionInfo.name);
16936 if (!rootName.empty())
16937 name = rootName + '/' + name;
16939 if (!sectionNode.assertions.empty() || !sectionNode.stdOut.empty() ||
16940 !sectionNode.stdErr.empty()) {
16941 XmlWriter::ScopedElement e = xml.scopedElement(
"testcase");
16942 if (className.empty()) {
16943 xml.writeAttribute(
"classname", name);
16944 xml.writeAttribute(
"name",
"root");
16946 xml.writeAttribute(
"classname", className);
16947 xml.writeAttribute(
"name", name);
16949 xml.writeAttribute(
"time", formatDuration(sectionNode.stats.durationInSeconds));
16954 xml.writeAttribute(
"status",
"run");
16956 if (sectionNode.stats.assertions.failedButOk) {
16957 xml.scopedElement(
"skipped").writeAttribute(
"message",
16958 "TEST_CASE tagged with !mayfail");
16961 writeAssertions(sectionNode);
16963 if (!sectionNode.stdOut.empty())
16964 xml.scopedElement(
"system-out")
16965 .writeText(trim(sectionNode.stdOut), XmlFormatting::Newline);
16966 if (!sectionNode.stdErr.empty())
16967 xml.scopedElement(
"system-err")
16968 .writeText(trim(sectionNode.stdErr), XmlFormatting::Newline);
16970 for (
auto const& childNode : sectionNode.childSections)
16971 if (className.empty())
16972 writeSection(name,
"", *childNode, testOkToFail);
16974 writeSection(className, name, *childNode, testOkToFail);
16977void JunitReporter::writeAssertions(SectionNode
const& sectionNode) {
16978 for (
auto const& assertion : sectionNode.assertions)
16979 writeAssertion(assertion);
16982void JunitReporter::writeAssertion(AssertionStats
const& stats) {
16983 AssertionResult
const& result = stats.assertionResult;
16984 if (!result.isOk()) {
16985 std::string elementName;
16986 switch (result.getResultType()) {
16987 case ResultWas::ThrewException:
16988 case ResultWas::FatalErrorCondition:
16989 elementName =
"error";
16991 case ResultWas::ExplicitFailure:
16992 case ResultWas::ExpressionFailed:
16993 case ResultWas::DidntThrowException:
16994 elementName =
"failure";
16998 case ResultWas::Info:
16999 case ResultWas::Warning:
17000 case ResultWas::Ok:
17001 case ResultWas::Unknown:
17002 case ResultWas::FailureBit:
17003 case ResultWas::Exception:
17004 elementName =
"internalError";
17008 XmlWriter::ScopedElement e = xml.scopedElement(elementName);
17010 xml.writeAttribute(
"message", result.getExpression());
17011 xml.writeAttribute(
"type", result.getTestMacroName());
17014 if (stats.totals.assertions.total() > 0) {
17015 rss <<
"FAILED" <<
":\n";
17016 if (result.hasExpression()) {
17018 rss << result.getExpressionInMacro();
17021 if (result.hasExpandedExpression()) {
17022 rss <<
"with expansion:\n";
17023 rss << Column(result.getExpandedExpression()).indent(2) <<
'\n';
17029 if (!result.getMessage().empty())
17030 rss << result.getMessage() <<
'\n';
17031 for (
auto const& msg : stats.infoMessages)
17032 if (msg.type == ResultWas::Info)
17033 rss << msg.message <<
'\n';
17035 rss <<
"at " << result.getSourceInfo();
17036 xml.writeText(rss.str(), XmlFormatting::Newline);
17040CATCH_REGISTER_REPORTER(
"junit", JunitReporter)
17050ListeningReporter::ListeningReporter() {
17052 m_preferences.shouldReportAllAssertions =
true;
17055void ListeningReporter::addListener(IStreamingReporterPtr&& listener) {
17056 m_listeners.push_back(std::move(listener));
17059void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
17060 assert(!m_reporter &&
"Listening reporter can wrap only 1 real reporter");
17061 m_reporter = std::move(reporter);
17062 m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
17065ReporterPreferences ListeningReporter::getPreferences()
const {
17066 return m_preferences;
17069std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
17070 return std::set<Verbosity>{};
17073void ListeningReporter::noMatchingTestCases(std::string
const& spec) {
17074 for (
auto const& listener : m_listeners) {
17075 listener->noMatchingTestCases(spec);
17077 m_reporter->noMatchingTestCases(spec);
17080void ListeningReporter::reportInvalidArguments(std::string
const& arg) {
17081 for (
auto const& listener : m_listeners) {
17082 listener->reportInvalidArguments(arg);
17084 m_reporter->reportInvalidArguments(arg);
17087#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17088void ListeningReporter::benchmarkPreparing(std::string
const& name) {
17089 for (
auto const& listener : m_listeners) {
17090 listener->benchmarkPreparing(name);
17092 m_reporter->benchmarkPreparing(name);
17094void ListeningReporter::benchmarkStarting(BenchmarkInfo
const& benchmarkInfo) {
17095 for (
auto const& listener : m_listeners) {
17096 listener->benchmarkStarting(benchmarkInfo);
17098 m_reporter->benchmarkStarting(benchmarkInfo);
17100void ListeningReporter::benchmarkEnded(BenchmarkStats<>
const& benchmarkStats) {
17101 for (
auto const& listener : m_listeners) {
17102 listener->benchmarkEnded(benchmarkStats);
17104 m_reporter->benchmarkEnded(benchmarkStats);
17107void ListeningReporter::benchmarkFailed(std::string
const& error) {
17108 for (
auto const& listener : m_listeners) {
17109 listener->benchmarkFailed(error);
17111 m_reporter->benchmarkFailed(error);
17115void ListeningReporter::testRunStarting(TestRunInfo
const& testRunInfo) {
17116 for (
auto const& listener : m_listeners) {
17117 listener->testRunStarting(testRunInfo);
17119 m_reporter->testRunStarting(testRunInfo);
17122void ListeningReporter::testGroupStarting(GroupInfo
const& groupInfo) {
17123 for (
auto const& listener : m_listeners) {
17124 listener->testGroupStarting(groupInfo);
17126 m_reporter->testGroupStarting(groupInfo);
17129void ListeningReporter::testCaseStarting(
TestCaseInfo const& testInfo) {
17130 for (
auto const& listener : m_listeners) {
17131 listener->testCaseStarting(testInfo);
17133 m_reporter->testCaseStarting(testInfo);
17136void ListeningReporter::sectionStarting(
SectionInfo const& sectionInfo) {
17137 for (
auto const& listener : m_listeners) {
17138 listener->sectionStarting(sectionInfo);
17140 m_reporter->sectionStarting(sectionInfo);
17143void ListeningReporter::assertionStarting(
AssertionInfo const& assertionInfo) {
17144 for (
auto const& listener : m_listeners) {
17145 listener->assertionStarting(assertionInfo);
17147 m_reporter->assertionStarting(assertionInfo);
17151bool ListeningReporter::assertionEnded(AssertionStats
const& assertionStats) {
17152 for (
auto const& listener : m_listeners) {
17153 static_cast<void>(listener->assertionEnded(assertionStats));
17155 return m_reporter->assertionEnded(assertionStats);
17158void ListeningReporter::sectionEnded(SectionStats
const& sectionStats) {
17159 for (
auto const& listener : m_listeners) {
17160 listener->sectionEnded(sectionStats);
17162 m_reporter->sectionEnded(sectionStats);
17165void ListeningReporter::testCaseEnded(TestCaseStats
const& testCaseStats) {
17166 for (
auto const& listener : m_listeners) {
17167 listener->testCaseEnded(testCaseStats);
17169 m_reporter->testCaseEnded(testCaseStats);
17172void ListeningReporter::testGroupEnded(TestGroupStats
const& testGroupStats) {
17173 for (
auto const& listener : m_listeners) {
17174 listener->testGroupEnded(testGroupStats);
17176 m_reporter->testGroupEnded(testGroupStats);
17179void ListeningReporter::testRunEnded(TestRunStats
const& testRunStats) {
17180 for (
auto const& listener : m_listeners) {
17181 listener->testRunEnded(testRunStats);
17183 m_reporter->testRunEnded(testRunStats);
17186void ListeningReporter::skipTest(
TestCaseInfo const& testInfo) {
17187 for (
auto const& listener : m_listeners) {
17188 listener->skipTest(testInfo);
17190 m_reporter->skipTest(testInfo);
17193bool ListeningReporter::isMulti()
const {
17201#if defined(_MSC_VER)
17202#pragma warning(push)
17203#pragma warning(disable : 4061)
17209XmlReporter::XmlReporter(ReporterConfig
const& _config)
17210 : StreamingReporterBase(_config), m_xml(_config.stream()) {
17211 m_reporterPrefs.shouldRedirectStdOut =
true;
17212 m_reporterPrefs.shouldReportAllAssertions =
true;
17215XmlReporter::~XmlReporter() =
default;
17217std::string XmlReporter::getDescription() {
17218 return "Reports test results as an XML document";
17221std::string XmlReporter::getStylesheetRef()
const {
17222 return std::string();
17225void XmlReporter::writeSourceInfo(
SourceLineInfo const& sourceInfo) {
17226 m_xml.writeAttribute(
"filename", sourceInfo.file).writeAttribute(
"line", sourceInfo.line);
17229void XmlReporter::noMatchingTestCases(std::string
const& s) {
17230 StreamingReporterBase::noMatchingTestCases(s);
17233void XmlReporter::testRunStarting(TestRunInfo
const& testInfo) {
17234 StreamingReporterBase::testRunStarting(testInfo);
17235 std::string stylesheetRef = getStylesheetRef();
17236 if (!stylesheetRef.empty())
17237 m_xml.writeStylesheetRef(stylesheetRef);
17238 m_xml.startElement(
"Catch");
17239 if (!m_config->name().empty())
17240 m_xml.writeAttribute(
"name", m_config->name());
17241 if (m_config->testSpec().hasFilters())
17242 m_xml.writeAttribute(
"filters", serializeFilters(m_config->getTestsOrTags()));
17243 if (m_config->rngSeed() != 0)
17244 m_xml.scopedElement(
"Randomness").writeAttribute(
"seed", m_config->rngSeed());
17247void XmlReporter::testGroupStarting(GroupInfo
const& groupInfo) {
17248 StreamingReporterBase::testGroupStarting(groupInfo);
17249 m_xml.startElement(
"Group").writeAttribute(
"name", groupInfo.name);
17252void XmlReporter::testCaseStarting(
TestCaseInfo const& testInfo) {
17253 StreamingReporterBase::testCaseStarting(testInfo);
17254 m_xml.startElement(
"TestCase")
17255 .writeAttribute(
"name", trim(testInfo.name))
17256 .writeAttribute(
"description", testInfo.description)
17257 .writeAttribute(
"tags", testInfo.tagsAsString());
17259 writeSourceInfo(testInfo.lineInfo);
17261 if (m_config->showDurations() == ShowDurations::Always)
17262 m_testCaseTimer.start();
17263 m_xml.ensureTagClosed();
17266void XmlReporter::sectionStarting(
SectionInfo const& sectionInfo) {
17267 StreamingReporterBase::sectionStarting(sectionInfo);
17268 if (m_sectionDepth++ > 0) {
17269 m_xml.startElement(
"Section").writeAttribute(
"name", trim(sectionInfo.name));
17270 writeSourceInfo(sectionInfo.lineInfo);
17271 m_xml.ensureTagClosed();
17275void XmlReporter::assertionStarting(
AssertionInfo const&) {}
17277bool XmlReporter::assertionEnded(AssertionStats
const& assertionStats) {
17279 AssertionResult
const& result = assertionStats.assertionResult;
17281 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
17283 if (includeResults || result.getResultType() == ResultWas::Warning) {
17285 for (
auto const& msg : assertionStats.infoMessages) {
17286 if (msg.type == ResultWas::Info && includeResults) {
17287 m_xml.scopedElement(
"Info").writeText(msg.message);
17288 }
else if (msg.type == ResultWas::Warning) {
17289 m_xml.scopedElement(
"Warning").writeText(msg.message);
17295 if (!includeResults && result.getResultType() != ResultWas::Warning)
17299 if (result.hasExpression()) {
17300 m_xml.startElement(
"Expression")
17301 .writeAttribute(
"success", result.succeeded())
17302 .writeAttribute(
"type", result.getTestMacroName());
17304 writeSourceInfo(result.getSourceInfo());
17306 m_xml.scopedElement(
"Original").writeText(result.getExpression());
17307 m_xml.scopedElement(
"Expanded").writeText(result.getExpandedExpression());
17311 switch (result.getResultType()) {
17312 case ResultWas::ThrewException:
17313 m_xml.startElement(
"Exception");
17314 writeSourceInfo(result.getSourceInfo());
17315 m_xml.writeText(result.getMessage());
17316 m_xml.endElement();
17318 case ResultWas::FatalErrorCondition:
17319 m_xml.startElement(
"FatalErrorCondition");
17320 writeSourceInfo(result.getSourceInfo());
17321 m_xml.writeText(result.getMessage());
17322 m_xml.endElement();
17324 case ResultWas::Info:
17325 m_xml.scopedElement(
"Info").writeText(result.getMessage());
17327 case ResultWas::Warning:
17330 case ResultWas::ExplicitFailure:
17331 m_xml.startElement(
"Failure");
17332 writeSourceInfo(result.getSourceInfo());
17333 m_xml.writeText(result.getMessage());
17334 m_xml.endElement();
17340 if (result.hasExpression())
17341 m_xml.endElement();
17346void XmlReporter::sectionEnded(SectionStats
const& sectionStats) {
17347 StreamingReporterBase::sectionEnded(sectionStats);
17348 if (--m_sectionDepth > 0) {
17349 XmlWriter::ScopedElement e = m_xml.scopedElement(
"OverallResults");
17350 e.writeAttribute(
"successes", sectionStats.assertions.passed);
17351 e.writeAttribute(
"failures", sectionStats.assertions.failed);
17352 e.writeAttribute(
"expectedFailures", sectionStats.assertions.failedButOk);
17354 if (m_config->showDurations() == ShowDurations::Always)
17355 e.writeAttribute(
"durationInSeconds", sectionStats.durationInSeconds);
17357 m_xml.endElement();
17361void XmlReporter::testCaseEnded(TestCaseStats
const& testCaseStats) {
17362 StreamingReporterBase::testCaseEnded(testCaseStats);
17363 XmlWriter::ScopedElement e = m_xml.scopedElement(
"OverallResult");
17364 e.writeAttribute(
"success", testCaseStats.totals.assertions.allOk());
17366 if (m_config->showDurations() == ShowDurations::Always)
17367 e.writeAttribute(
"durationInSeconds", m_testCaseTimer.getElapsedSeconds());
17369 if (!testCaseStats.stdOut.empty())
17370 m_xml.scopedElement(
"StdOut").writeText(trim(testCaseStats.stdOut), XmlFormatting::Newline);
17371 if (!testCaseStats.stdErr.empty())
17372 m_xml.scopedElement(
"StdErr").writeText(trim(testCaseStats.stdErr), XmlFormatting::Newline);
17374 m_xml.endElement();
17377void XmlReporter::testGroupEnded(TestGroupStats
const& testGroupStats) {
17378 StreamingReporterBase::testGroupEnded(testGroupStats);
17380 m_xml.scopedElement(
"OverallResults")
17381 .writeAttribute(
"successes", testGroupStats.totals.assertions.passed)
17382 .writeAttribute(
"failures", testGroupStats.totals.assertions.failed)
17383 .writeAttribute(
"expectedFailures", testGroupStats.totals.assertions.failedButOk);
17384 m_xml.scopedElement(
"OverallResultsCases")
17385 .writeAttribute(
"successes", testGroupStats.totals.testCases.passed)
17386 .writeAttribute(
"failures", testGroupStats.totals.testCases.failed)
17387 .writeAttribute(
"expectedFailures", testGroupStats.totals.testCases.failedButOk);
17388 m_xml.endElement();
17391void XmlReporter::testRunEnded(TestRunStats
const& testRunStats) {
17392 StreamingReporterBase::testRunEnded(testRunStats);
17393 m_xml.scopedElement(
"OverallResults")
17394 .writeAttribute(
"successes", testRunStats.totals.assertions.passed)
17395 .writeAttribute(
"failures", testRunStats.totals.assertions.failed)
17396 .writeAttribute(
"expectedFailures", testRunStats.totals.assertions.failedButOk);
17397 m_xml.scopedElement(
"OverallResultsCases")
17398 .writeAttribute(
"successes", testRunStats.totals.testCases.passed)
17399 .writeAttribute(
"failures", testRunStats.totals.testCases.failed)
17400 .writeAttribute(
"expectedFailures", testRunStats.totals.testCases.failedButOk);
17401 m_xml.endElement();
17404#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17405void XmlReporter::benchmarkPreparing(std::string
const& name) {
17406 m_xml.startElement(
"BenchmarkResults").writeAttribute(
"name", name);
17409void XmlReporter::benchmarkStarting(BenchmarkInfo
const& info) {
17410 m_xml.writeAttribute(
"samples", info.samples)
17411 .writeAttribute(
"resamples", info.resamples)
17412 .writeAttribute(
"iterations", info.iterations)
17413 .writeAttribute(
"clockResolution", info.clockResolution)
17414 .writeAttribute(
"estimatedDuration", info.estimatedDuration)
17415 .writeComment(
"All values in nano seconds");
17418void XmlReporter::benchmarkEnded(BenchmarkStats<>
const& benchmarkStats) {
17419 m_xml.startElement(
"mean")
17420 .writeAttribute(
"value", benchmarkStats.mean.point.count())
17421 .writeAttribute(
"lowerBound", benchmarkStats.mean.lower_bound.count())
17422 .writeAttribute(
"upperBound", benchmarkStats.mean.upper_bound.count())
17423 .writeAttribute(
"ci", benchmarkStats.mean.confidence_interval);
17424 m_xml.endElement();
17425 m_xml.startElement(
"standardDeviation")
17426 .writeAttribute(
"value", benchmarkStats.standardDeviation.point.count())
17427 .writeAttribute(
"lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
17428 .writeAttribute(
"upperBound", benchmarkStats.standardDeviation.upper_bound.count())
17429 .writeAttribute(
"ci", benchmarkStats.standardDeviation.confidence_interval);
17430 m_xml.endElement();
17431 m_xml.startElement(
"outliers")
17432 .writeAttribute(
"variance", benchmarkStats.outlierVariance)
17433 .writeAttribute(
"lowMild", benchmarkStats.outliers.low_mild)
17434 .writeAttribute(
"lowSevere", benchmarkStats.outliers.low_severe)
17435 .writeAttribute(
"highMild", benchmarkStats.outliers.high_mild)
17436 .writeAttribute(
"highSevere", benchmarkStats.outliers.high_severe);
17437 m_xml.endElement();
17438 m_xml.endElement();
17441void XmlReporter::benchmarkFailed(std::string
const& error) {
17442 m_xml.scopedElement(
"failed").writeAttribute(
"message", error);
17443 m_xml.endElement();
17447CATCH_REGISTER_REPORTER(
"xml", XmlReporter)
17451#if defined(_MSC_VER)
17452#pragma warning(pop)
17457LeakDetector leakDetector;
17461#pragma clang diagnostic pop
17467#ifdef CATCH_CONFIG_MAIN
17472#if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && \
17473 !defined(DO_NOT_USE_WMAIN)
17475extern "C" int wmain(
int argc,
wchar_t* argv[],
wchar_t*[]) {
17478int main(
int argc,
char* argv[]) {
17481 return Catch::Session().run(argc, argv);
17487int main(
int argc,
char*
const argv[]) {
17488#if !CATCH_ARC_ENABLED
17489 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
17492 Catch::registerTestMethods();
17493 int result = Catch::Session().run(argc, (
char**)argv);
17495#if !CATCH_ARC_ENABLED
17507#if !defined(CATCH_CONFIG_IMPL_ONLY)
17509#ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
17510#undef CLARA_CONFIG_MAIN
17513#if !defined(CATCH_CONFIG_DISABLE)
17517#ifdef CATCH_CONFIG_PREFIX_ALL
17519#define CATCH_REQUIRE(...) \
17520 INTERNAL_CATCH_TEST("CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__)
17521#define CATCH_REQUIRE_FALSE(...) \
17522 INTERNAL_CATCH_TEST("CATCH_REQUIRE_FALSE", \
17523 Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, \
17526#define CATCH_REQUIRE_THROWS(...) \
17527 INTERNAL_CATCH_THROWS("CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__)
17528#define CATCH_REQUIRE_THROWS_AS(expr, exceptionType) \
17529 INTERNAL_CATCH_THROWS_AS("CATCH_REQUIRE_THROWS_AS", exceptionType, \
17530 Catch::ResultDisposition::Normal, expr)
17531#define CATCH_REQUIRE_THROWS_WITH(expr, matcher) \
17532 INTERNAL_CATCH_THROWS_STR_MATCHES("CATCH_REQUIRE_THROWS_WITH", \
17533 Catch::ResultDisposition::Normal, matcher, expr)
17534#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17535#define CATCH_REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) \
17536 INTERNAL_CATCH_THROWS_MATCHES("CATCH_REQUIRE_THROWS_MATCHES", exceptionType, \
17537 Catch::ResultDisposition::Normal, matcher, expr)
17539#define CATCH_REQUIRE_NOTHROW(...) \
17540 INTERNAL_CATCH_NO_THROW("CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__)
17542#define CATCH_CHECK(...) \
17543 INTERNAL_CATCH_TEST("CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17544#define CATCH_CHECK_FALSE(...) \
17545 INTERNAL_CATCH_TEST("CATCH_CHECK_FALSE", \
17546 Catch::ResultDisposition::ContinueOnFailure | \
17547 Catch::ResultDisposition::FalseTest, \
17549#define CATCH_CHECKED_IF(...) \
17550 INTERNAL_CATCH_IF("CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17551#define CATCH_CHECKED_ELSE(...) \
17552 INTERNAL_CATCH_ELSE("CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, \
17554#define CATCH_CHECK_NOFAIL(...) \
17555 INTERNAL_CATCH_TEST("CATCH_CHECK_NOFAIL", \
17556 Catch::ResultDisposition::ContinueOnFailure | \
17557 Catch::ResultDisposition::SuppressFail, \
17560#define CATCH_CHECK_THROWS(...) \
17561 INTERNAL_CATCH_THROWS("CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, \
17563#define CATCH_CHECK_THROWS_AS(expr, exceptionType) \
17564 INTERNAL_CATCH_THROWS_AS("CATCH_CHECK_THROWS_AS", exceptionType, \
17565 Catch::ResultDisposition::ContinueOnFailure, expr)
17566#define CATCH_CHECK_THROWS_WITH(expr, matcher) \
17567 INTERNAL_CATCH_THROWS_STR_MATCHES("CATCH_CHECK_THROWS_WITH", \
17568 Catch::ResultDisposition::ContinueOnFailure, matcher, expr)
17569#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17570#define CATCH_CHECK_THROWS_MATCHES(expr, exceptionType, matcher) \
17571 INTERNAL_CATCH_THROWS_MATCHES("CATCH_CHECK_THROWS_MATCHES", exceptionType, \
17572 Catch::ResultDisposition::ContinueOnFailure, matcher, expr)
17574#define CATCH_CHECK_NOTHROW(...) \
17575 INTERNAL_CATCH_NO_THROW("CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, \
17578#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17579#define CATCH_CHECK_THAT(arg, matcher) \
17580 INTERNAL_CHECK_THAT("CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, \
17583#define CATCH_REQUIRE_THAT(arg, matcher) \
17584 INTERNAL_CHECK_THAT("CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg)
17587#define CATCH_INFO(msg) INTERNAL_CATCH_INFO("CATCH_INFO", msg)
17588#define CATCH_UNSCOPED_INFO(msg) INTERNAL_CATCH_UNSCOPED_INFO("CATCH_UNSCOPED_INFO", msg)
17589#define CATCH_WARN(msg) \
17590 INTERNAL_CATCH_MSG("CATCH_WARN", Catch::ResultWas::Warning, \
17591 Catch::ResultDisposition::ContinueOnFailure, msg)
17592#define CATCH_CAPTURE(...) \
17593 INTERNAL_CATCH_CAPTURE(INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE", __VA_ARGS__)
17595#define CATCH_TEST_CASE(...) INTERNAL_CATCH_TESTCASE(__VA_ARGS__)
17596#define CATCH_TEST_CASE_METHOD(className, ...) \
17597 INTERNAL_CATCH_TEST_CASE_METHOD(className, __VA_ARGS__)
17598#define CATCH_METHOD_AS_TEST_CASE(method, ...) \
17599 INTERNAL_CATCH_METHOD_AS_TEST_CASE(method, __VA_ARGS__)
17600#define CATCH_REGISTER_TEST_CASE(Function, ...) \
17601 INTERNAL_CATCH_REGISTER_TESTCASE(Function, __VA_ARGS__)
17602#define CATCH_SECTION(...) INTERNAL_CATCH_SECTION(__VA_ARGS__)
17603#define CATCH_DYNAMIC_SECTION(...) INTERNAL_CATCH_DYNAMIC_SECTION(__VA_ARGS__)
17604#define CATCH_FAIL(...) \
17605 INTERNAL_CATCH_MSG("CATCH_FAIL", Catch::ResultWas::ExplicitFailure, \
17606 Catch::ResultDisposition::Normal, __VA_ARGS__)
17607#define CATCH_FAIL_CHECK(...) \
17608 INTERNAL_CATCH_MSG("CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, \
17609 Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17610#define CATCH_SUCCEED(...) \
17611 INTERNAL_CATCH_MSG("CATCH_SUCCEED", Catch::ResultWas::Ok, \
17612 Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17614#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17616#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17617#define CATCH_TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
17618#define CATCH_TEMPLATE_TEST_CASE_SIG(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__)
17619#define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \
17620 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
17621#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
17622 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
17623#define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__)
17624#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \
17625 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__)
17626#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
17627 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__)
17628#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
17629 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
17631#define CATCH_TEMPLATE_TEST_CASE(...) \
17632 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__))
17633#define CATCH_TEMPLATE_TEST_CASE_SIG(...) \
17634 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__))
17635#define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \
17636 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__))
17637#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
17638 INTERNAL_CATCH_EXPAND_VARGS( \
17639 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
17640#define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) \
17641 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__))
17642#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \
17643 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__))
17644#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
17645 INTERNAL_CATCH_EXPAND_VARGS( \
17646 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__))
17647#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
17648 INTERNAL_CATCH_EXPAND_VARGS( \
17649 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
17652#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17653#define CATCH_STATIC_REQUIRE(...) \
17654 static_assert(__VA_ARGS__, #__VA_ARGS__); \
17655 CATCH_SUCCEED(#__VA_ARGS__)
17656#define CATCH_STATIC_REQUIRE_FALSE(...) \
17657 static_assert(!(__VA_ARGS__), "!(" #__VA_ARGS__ ")"); \
17658 CATCH_SUCCEED(#__VA_ARGS__)
17660#define CATCH_STATIC_REQUIRE(...) CATCH_REQUIRE(__VA_ARGS__)
17661#define CATCH_STATIC_REQUIRE_FALSE(...) CATCH_REQUIRE_FALSE(__VA_ARGS__)
17665#define CATCH_SCENARIO(...) CATCH_TEST_CASE("Scenario: " __VA_ARGS__)
17666#define CATCH_SCENARIO_METHOD(className, ...) \
17667 INTERNAL_CATCH_TEST_CASE_METHOD(className, "Scenario: " __VA_ARGS__)
17668#define CATCH_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Given: " << desc)
17669#define CATCH_AND_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("And given: " << desc)
17670#define CATCH_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" When: " << desc)
17671#define CATCH_AND_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And when: " << desc)
17672#define CATCH_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Then: " << desc)
17673#define CATCH_AND_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And: " << desc)
17675#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17676#define CATCH_BENCHMARK(...) \
17677 INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), \
17678 INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__, , ), \
17679 INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__, , ))
17680#define CATCH_BENCHMARK_ADVANCED(name) \
17681 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), name)
17688#define REQUIRE(...) INTERNAL_CATCH_TEST("REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__)
17689#define REQUIRE_FALSE(...) \
17690 INTERNAL_CATCH_TEST("REQUIRE_FALSE", \
17691 Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, \
17694#define REQUIRE_THROWS(...) \
17695 INTERNAL_CATCH_THROWS("REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__)
17696#define REQUIRE_THROWS_AS(expr, exceptionType) \
17697 INTERNAL_CATCH_THROWS_AS("REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, \
17699#define REQUIRE_THROWS_WITH(expr, matcher) \
17700 INTERNAL_CATCH_THROWS_STR_MATCHES("REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, \
17702#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17703#define REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) \
17704 INTERNAL_CATCH_THROWS_MATCHES("REQUIRE_THROWS_MATCHES", exceptionType, \
17705 Catch::ResultDisposition::Normal, matcher, expr)
17707#define REQUIRE_NOTHROW(...) \
17708 INTERNAL_CATCH_NO_THROW("REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__)
17710#define CHECK(...) \
17711 INTERNAL_CATCH_TEST("CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17712#define CHECK_FALSE(...) \
17713 INTERNAL_CATCH_TEST("CHECK_FALSE", \
17714 Catch::ResultDisposition::ContinueOnFailure | \
17715 Catch::ResultDisposition::FalseTest, \
17717#define CHECKED_IF(...) \
17718 INTERNAL_CATCH_IF("CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17719#define CHECKED_ELSE(...) \
17720 INTERNAL_CATCH_ELSE("CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17721#define CHECK_NOFAIL(...) \
17722 INTERNAL_CATCH_TEST("CHECK_NOFAIL", \
17723 Catch::ResultDisposition::ContinueOnFailure | \
17724 Catch::ResultDisposition::SuppressFail, \
17727#define CHECK_THROWS(...) \
17728 INTERNAL_CATCH_THROWS("CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17729#define CHECK_THROWS_AS(expr, exceptionType) \
17730 INTERNAL_CATCH_THROWS_AS("CHECK_THROWS_AS", exceptionType, \
17731 Catch::ResultDisposition::ContinueOnFailure, expr)
17732#define CHECK_THROWS_WITH(expr, matcher) \
17733 INTERNAL_CATCH_THROWS_STR_MATCHES("CHECK_THROWS_WITH", \
17734 Catch::ResultDisposition::ContinueOnFailure, matcher, expr)
17735#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17736#define CHECK_THROWS_MATCHES(expr, exceptionType, matcher) \
17737 INTERNAL_CATCH_THROWS_MATCHES("CHECK_THROWS_MATCHES", exceptionType, \
17738 Catch::ResultDisposition::ContinueOnFailure, matcher, expr)
17740#define CHECK_NOTHROW(...) \
17741 INTERNAL_CATCH_NO_THROW("CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, \
17744#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17745#define CHECK_THAT(arg, matcher) \
17746 INTERNAL_CHECK_THAT("CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg)
17748#define REQUIRE_THAT(arg, matcher) \
17749 INTERNAL_CHECK_THAT("REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg)
17752#define INFO(msg) INTERNAL_CATCH_INFO("INFO", msg)
17753#define UNSCOPED_INFO(msg) INTERNAL_CATCH_UNSCOPED_INFO("UNSCOPED_INFO", msg)
17755 INTERNAL_CATCH_MSG("WARN", Catch::ResultWas::Warning, \
17756 Catch::ResultDisposition::ContinueOnFailure, msg)
17757#define CAPTURE(...) \
17758 INTERNAL_CATCH_CAPTURE(INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE", __VA_ARGS__)
17760#define TEST_CASE(...) INTERNAL_CATCH_TESTCASE(__VA_ARGS__)
17761#define TEST_CASE_METHOD(className, ...) INTERNAL_CATCH_TEST_CASE_METHOD(className, __VA_ARGS__)
17762#define METHOD_AS_TEST_CASE(method, ...) INTERNAL_CATCH_METHOD_AS_TEST_CASE(method, __VA_ARGS__)
17763#define REGISTER_TEST_CASE(Function, ...) INTERNAL_CATCH_REGISTER_TESTCASE(Function, __VA_ARGS__)
17764#define SECTION(...) INTERNAL_CATCH_SECTION(__VA_ARGS__)
17765#define DYNAMIC_SECTION(...) INTERNAL_CATCH_DYNAMIC_SECTION(__VA_ARGS__)
17767 INTERNAL_CATCH_MSG("FAIL", Catch::ResultWas::ExplicitFailure, \
17768 Catch::ResultDisposition::Normal, __VA_ARGS__)
17769#define FAIL_CHECK(...) \
17770 INTERNAL_CATCH_MSG("FAIL_CHECK", Catch::ResultWas::ExplicitFailure, \
17771 Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17772#define SUCCEED(...) \
17773 INTERNAL_CATCH_MSG("SUCCEED", Catch::ResultWas::Ok, \
17774 Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__)
17775#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17777#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17778#define TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
17779#define TEMPLATE_TEST_CASE_SIG(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__)
17780#define TEMPLATE_TEST_CASE_METHOD(className, ...) \
17781 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
17782#define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
17783 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
17784#define TEMPLATE_PRODUCT_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__)
17785#define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \
17786 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__)
17787#define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
17788 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__)
17789#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
17790 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__)
17791#define TEMPLATE_LIST_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
17792#define TEMPLATE_LIST_TEST_CASE_METHOD(className, ...) \
17793 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(className, __VA_ARGS__)
17795#define TEMPLATE_TEST_CASE(...) \
17796 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__))
17797#define TEMPLATE_TEST_CASE_SIG(...) \
17798 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(__VA_ARGS__))
17799#define TEMPLATE_TEST_CASE_METHOD(className, ...) \
17800 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__))
17801#define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
17802 INTERNAL_CATCH_EXPAND_VARGS( \
17803 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
17804#define TEMPLATE_PRODUCT_TEST_CASE(...) \
17805 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(__VA_ARGS__))
17806#define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) \
17807 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(__VA_ARGS__))
17808#define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
17809 INTERNAL_CATCH_EXPAND_VARGS( \
17810 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, __VA_ARGS__))
17811#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
17812 INTERNAL_CATCH_EXPAND_VARGS( \
17813 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, __VA_ARGS__))
17814#define TEMPLATE_LIST_TEST_CASE(...) \
17815 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__))
17816#define TEMPLATE_LIST_TEST_CASE_METHOD(className, ...) \
17817 INTERNAL_CATCH_EXPAND_VARGS( \
17818 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(className, __VA_ARGS__))
17821#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17822#define STATIC_REQUIRE(...) \
17823 static_assert(__VA_ARGS__, #__VA_ARGS__); \
17824 SUCCEED(#__VA_ARGS__)
17825#define STATIC_REQUIRE_FALSE(...) \
17826 static_assert(!(__VA_ARGS__), "!(" #__VA_ARGS__ ")"); \
17827 SUCCEED("!(" #__VA_ARGS__ ")")
17829#define STATIC_REQUIRE(...) REQUIRE(__VA_ARGS__)
17830#define STATIC_REQUIRE_FALSE(...) REQUIRE_FALSE(__VA_ARGS__)
17835#define CATCH_TRANSLATE_EXCEPTION(signature) INTERNAL_CATCH_TRANSLATE_EXCEPTION(signature)
17838#define SCENARIO(...) TEST_CASE("Scenario: " __VA_ARGS__)
17839#define SCENARIO_METHOD(className, ...) \
17840 INTERNAL_CATCH_TEST_CASE_METHOD(className, "Scenario: " __VA_ARGS__)
17842#define GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Given: " << desc)
17843#define AND_GIVEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION("And given: " << desc)
17844#define WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" When: " << desc)
17845#define AND_WHEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And when: " << desc)
17846#define THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" Then: " << desc)
17847#define AND_THEN(desc) INTERNAL_CATCH_DYNAMIC_SECTION(" And: " << desc)
17849#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17850#define BENCHMARK(...) \
17851 INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), \
17852 INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__, , ), \
17853 INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__, , ))
17854#define BENCHMARK_ADVANCED(name) \
17855 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), name)
17865#ifdef CATCH_CONFIG_PREFIX_ALL
17867#define CATCH_REQUIRE(...) (void)(0)
17868#define CATCH_REQUIRE_FALSE(...) (void)(0)
17870#define CATCH_REQUIRE_THROWS(...) (void)(0)
17871#define CATCH_REQUIRE_THROWS_AS(expr, exceptionType) (void)(0)
17872#define CATCH_REQUIRE_THROWS_WITH(expr, matcher) (void)(0)
17873#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17874#define CATCH_REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
17876#define CATCH_REQUIRE_NOTHROW(...) (void)(0)
17878#define CATCH_CHECK(...) (void)(0)
17879#define CATCH_CHECK_FALSE(...) (void)(0)
17880#define CATCH_CHECKED_IF(...) if (__VA_ARGS__)
17881#define CATCH_CHECKED_ELSE(...) if (!(__VA_ARGS__))
17882#define CATCH_CHECK_NOFAIL(...) (void)(0)
17884#define CATCH_CHECK_THROWS(...) (void)(0)
17885#define CATCH_CHECK_THROWS_AS(expr, exceptionType) (void)(0)
17886#define CATCH_CHECK_THROWS_WITH(expr, matcher) (void)(0)
17887#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17888#define CATCH_CHECK_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
17890#define CATCH_CHECK_NOTHROW(...) (void)(0)
17892#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17893#define CATCH_CHECK_THAT(arg, matcher) (void)(0)
17895#define CATCH_REQUIRE_THAT(arg, matcher) (void)(0)
17898#define CATCH_INFO(msg) (void)(0)
17899#define CATCH_UNSCOPED_INFO(msg) (void)(0)
17900#define CATCH_WARN(msg) (void)(0)
17901#define CATCH_CAPTURE(msg) (void)(0)
17903#define CATCH_TEST_CASE(...) \
17904 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_))
17905#define CATCH_TEST_CASE_METHOD(className, ...) \
17906 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_))
17907#define CATCH_METHOD_AS_TEST_CASE(method, ...)
17908#define CATCH_REGISTER_TEST_CASE(Function, ...) (void)(0)
17909#define CATCH_SECTION(...)
17910#define CATCH_DYNAMIC_SECTION(...)
17911#define CATCH_FAIL(...) (void)(0)
17912#define CATCH_FAIL_CHECK(...) (void)(0)
17913#define CATCH_SUCCEED(...) (void)(0)
17915#define CATCH_ANON_TEST_CASE() \
17916 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_))
17918#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17919#define CATCH_TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
17920#define CATCH_TEMPLATE_TEST_CASE_SIG(...) \
17921 INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
17922#define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \
17923 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
17924#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
17925 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__)
17926#define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
17927#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
17928#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
17929 CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
17930#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
17931 CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
17933#define CATCH_TEMPLATE_TEST_CASE(...) \
17934 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__))
17935#define CATCH_TEMPLATE_TEST_CASE_SIG(...) \
17936 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__))
17937#define CATCH_TEMPLATE_TEST_CASE_METHOD(className, ...) \
17938 INTERNAL_CATCH_EXPAND_VARGS( \
17939 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__))
17940#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
17941 INTERNAL_CATCH_EXPAND_VARGS( \
17942 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__))
17943#define CATCH_TEMPLATE_PRODUCT_TEST_CASE(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
17944#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(...) CATCH_TEMPLATE_TEST_CASE(__VA_ARGS__)
17945#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
17946 CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
17947#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
17948 CATCH_TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
17952#define CATCH_SCENARIO(...) \
17953 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_))
17954#define CATCH_SCENARIO_METHOD(className, ...) \
17955 INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_), \
17957#define CATCH_GIVEN(desc)
17958#define CATCH_AND_GIVEN(desc)
17959#define CATCH_WHEN(desc)
17960#define CATCH_AND_WHEN(desc)
17961#define CATCH_THEN(desc)
17962#define CATCH_AND_THEN(desc)
17964#define CATCH_STATIC_REQUIRE(...) (void)(0)
17965#define CATCH_STATIC_REQUIRE_FALSE(...) (void)(0)
17971#define REQUIRE(...) (void)(0)
17972#define REQUIRE_FALSE(...) (void)(0)
17974#define REQUIRE_THROWS(...) (void)(0)
17975#define REQUIRE_THROWS_AS(expr, exceptionType) (void)(0)
17976#define REQUIRE_THROWS_WITH(expr, matcher) (void)(0)
17977#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17978#define REQUIRE_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
17980#define REQUIRE_NOTHROW(...) (void)(0)
17982#define CHECK(...) (void)(0)
17983#define CHECK_FALSE(...) (void)(0)
17984#define CHECKED_IF(...) if (__VA_ARGS__)
17985#define CHECKED_ELSE(...) if (!(__VA_ARGS__))
17986#define CHECK_NOFAIL(...) (void)(0)
17988#define CHECK_THROWS(...) (void)(0)
17989#define CHECK_THROWS_AS(expr, exceptionType) (void)(0)
17990#define CHECK_THROWS_WITH(expr, matcher) (void)(0)
17991#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17992#define CHECK_THROWS_MATCHES(expr, exceptionType, matcher) (void)(0)
17994#define CHECK_NOTHROW(...) (void)(0)
17996#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17997#define CHECK_THAT(arg, matcher) (void)(0)
17999#define REQUIRE_THAT(arg, matcher) (void)(0)
18002#define INFO(msg) (void)(0)
18003#define UNSCOPED_INFO(msg) (void)(0)
18004#define WARN(msg) (void)(0)
18005#define CAPTURE(...) (void)(0)
18007#define TEST_CASE(...) \
18008 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_))
18009#define TEST_CASE_METHOD(className, ...) \
18010 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_))
18011#define METHOD_AS_TEST_CASE(method, ...)
18012#define REGISTER_TEST_CASE(Function, ...) (void)(0)
18013#define SECTION(...)
18014#define DYNAMIC_SECTION(...)
18015#define FAIL(...) (void)(0)
18016#define FAIL_CHECK(...) (void)(0)
18017#define SUCCEED(...) (void)(0)
18018#define ANON_TEST_CASE() \
18019 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_))
18021#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
18022#define TEMPLATE_TEST_CASE(...) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
18023#define TEMPLATE_TEST_CASE_SIG(...) \
18024 INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
18025#define TEMPLATE_TEST_CASE_METHOD(className, ...) \
18026 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
18027#define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18028 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__)
18029#define TEMPLATE_PRODUCT_TEST_CASE(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18030#define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18031#define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18032 TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18033#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18034 TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18036#define TEMPLATE_TEST_CASE(...) \
18037 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__))
18038#define TEMPLATE_TEST_CASE_SIG(...) \
18039 INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__))
18040#define TEMPLATE_TEST_CASE_METHOD(className, ...) \
18041 INTERNAL_CATCH_EXPAND_VARGS( \
18042 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__))
18043#define TEMPLATE_TEST_CASE_METHOD_SIG(className, ...) \
18044 INTERNAL_CATCH_EXPAND_VARGS( \
18045 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__))
18046#define TEMPLATE_PRODUCT_TEST_CASE(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18047#define TEMPLATE_PRODUCT_TEST_CASE_SIG(...) TEMPLATE_TEST_CASE(__VA_ARGS__)
18048#define TEMPLATE_PRODUCT_TEST_CASE_METHOD(className, ...) \
18049 TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18050#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG(className, ...) \
18051 TEMPLATE_TEST_CASE_METHOD(className, __VA_ARGS__)
18054#define STATIC_REQUIRE(...) (void)(0)
18055#define STATIC_REQUIRE_FALSE(...) (void)(0)
18059#define CATCH_TRANSLATE_EXCEPTION(signature) \
18060 INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( \
18061 INTERNAL_CATCH_UNIQUE_NAME(catch_internal_ExceptionTranslator), signature)
18064#define SCENARIO(...) \
18065 INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_))
18066#define SCENARIO_METHOD(className, ...) \
18067 INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_T_E_S_T_), \
18071#define AND_GIVEN(desc)
18073#define AND_WHEN(desc)
18075#define AND_THEN(desc)
18087#pragma warning(pop)
18089#pragma clang diagnostic pop
18091#elif defined __GNUC__
18092#pragma GCC diagnostic pop
Definition catch.hpp:2800
Definition catch.hpp:2497
Definition catch.hpp:3349
Definition catch.hpp:1923
Definition catch.hpp:2607
Definition catch.hpp:4203
Definition catch.hpp:4416
Definition catch.hpp:4259
Definition catch.hpp:4276
Definition catch.hpp:4909
Definition catch.hpp:4512
Definition catch.hpp:4839
Definition catch.hpp:4871
Definition catch.hpp:4458
Definition catch.hpp:4232
Definition catch.hpp:4385
Definition catch.hpp:2777
Definition catch.hpp:4046
Definition catch.hpp:3672
Definition catch.hpp:3768
Definition catch.hpp:4652
Definition catch.hpp:1798
Definition catch.hpp:2887
Definition catch.hpp:4781
Definition catch.hpp:5001
Definition catch.hpp:1164
Definition catch.hpp:3159
Definition catch.hpp:2560
@ error
throw a parse_error exception in case of a tag
Definition json.hpp:8727
@ object
object (unordered set of name/value pairs)
Definition json.hpp:3069
@ string
string value
Definition json.hpp:3071
std::size_t hash(const BasicJsonType &j)
hash a JSON value
Definition json.hpp:5883
StringType escape(StringType s)
string escaping as described in RFC 6901 (Sect. 4)
Definition json.hpp:3175
Definition catch.hpp:1755
Definition catch.hpp:2795
Definition catch.hpp:3098
Definition catch.hpp:2679
Definition catch.hpp:1824
Definition catch.hpp:4221
Definition catch.hpp:4319
Definition catch.hpp:4735
Definition catch.hpp:4606
Definition catch.hpp:3280
Definition catch.hpp:3286
Definition catch.hpp:4142
Definition catch.hpp:4614
Definition catch.hpp:1834
Definition catch.hpp:3245
Definition catch.hpp:3234
Definition catch.hpp:2719
Definition catch.hpp:5031
Definition catch.hpp:1791
Definition catch.hpp:2478
Definition catch.hpp:3700
Definition catch.hpp:3727
Definition catch.hpp:3710
Definition catch.hpp:3569
Definition catch.hpp:3601
Definition catch.hpp:3562
Definition catch.hpp:3545
Definition catch.hpp:3806
Definition catch.hpp:3827
Definition catch.hpp:3835
Definition catch.hpp:3823
Definition catch.hpp:3840
Definition catch.hpp:3831
Definition catch.hpp:3953
Definition catch.hpp:3879
Definition catch.hpp:3900
Definition catch.hpp:3989
Definition catch.hpp:2875
Definition catch.hpp:2848
Definition catch.hpp:2865
Definition catch.hpp:1732
Definition catch.hpp:1706
Definition catch.hpp:4718
Definition catch.hpp:3141
Definition catch.hpp:3129
Definition catch.hpp:4715
Definition catch.hpp:1969
Definition catch.hpp:4968
Definition catch.hpp:2772
Definition catch.hpp:3111
Definition catch.hpp:4721
Definition catch.hpp:4724
Definition catch.hpp:4711
Definition catch.hpp:1128
Definition catch.hpp:2291
Definition catch.hpp:2287
Definition catch.hpp:1131
Definition catch.hpp:1137
Definition catch.hpp:2298
Definition catch.hpp:3500
Definition catch.hpp:1130