wxMaxima
Loading...
Searching...
No Matches
catch.hpp
1/*
2 * Catch v2.13.10
3 * Generated: 2022-10-16 11:01:23.452308
4 * ----------------------------------------------------------
5 * This file has been merged from multiple headers. Please don't edit it directly
6 * Copyright (c) 2022 Two Blue Cubes Ltd. All rights reserved.
7 *
8 * Distributed under the Boost Software License, Version 1.0. (See accompanying
9 * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
10 */
11#ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
12#define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
13// start catch.hpp
14
15
16#define CATCH_VERSION_MAJOR 2
17#define CATCH_VERSION_MINOR 13
18#define CATCH_VERSION_PATCH 10
19
20#ifdef __clang__
21# pragma clang system_header
22#elif defined __GNUC__
23# pragma GCC system_header
24#endif
25
26// start catch_suppress_warnings.h
27
28#ifdef __clang__
29# ifdef __ICC // icpc defines the __clang__ macro
30# pragma warning(push)
31# pragma warning(disable: 161 1682)
32# else // __ICC
33# pragma clang diagnostic push
34# pragma clang diagnostic ignored "-Wpadded"
35# pragma clang diagnostic ignored "-Wswitch-enum"
36# pragma clang diagnostic ignored "-Wcovered-switch-default"
37# endif
38#elif defined __GNUC__
39 // Because REQUIREs trigger GCC's -Wparentheses, and because still
40 // supported version of g++ have only buggy support for _Pragmas,
41 // Wparentheses have to be suppressed globally.
42# pragma GCC diagnostic ignored "-Wparentheses" // See #674 for details
43
44# pragma GCC diagnostic push
45# pragma GCC diagnostic ignored "-Wunused-variable"
46# pragma GCC diagnostic ignored "-Wpadded"
47#endif
48// end catch_suppress_warnings.h
49#if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
50# define CATCH_IMPL
51# define CATCH_CONFIG_ALL_PARTS
52#endif
53
54// In the impl file, we want to have access to all parts of the headers
55// Can also be used to sanely support PCHs
56#if defined(CATCH_CONFIG_ALL_PARTS)
57# define CATCH_CONFIG_EXTERNAL_INTERFACES
58# if defined(CATCH_CONFIG_DISABLE_MATCHERS)
59# undef CATCH_CONFIG_DISABLE_MATCHERS
60# endif
61# if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
62# define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
63# endif
64#endif
65
66#if !defined(CATCH_CONFIG_IMPL_ONLY)
67// start catch_platform.h
68
69// See e.g.:
70// https://opensource.apple.com/source/CarbonHeaders/CarbonHeaders-18.1/TargetConditionals.h.auto.html
71#ifdef __APPLE__
72# include <TargetConditionals.h>
73# if (defined(TARGET_OS_OSX) && TARGET_OS_OSX == 1) || \
74 (defined(TARGET_OS_MAC) && TARGET_OS_MAC == 1)
75# define CATCH_PLATFORM_MAC
76# elif (defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1)
77# define CATCH_PLATFORM_IPHONE
78# endif
79
80#elif defined(linux) || defined(__linux) || defined(__linux__)
81# define CATCH_PLATFORM_LINUX
82
83#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
84# define CATCH_PLATFORM_WINDOWS
85#endif
86
87// end catch_platform.h
88
89#ifdef CATCH_IMPL
90# ifndef CLARA_CONFIG_MAIN
91# define CLARA_CONFIG_MAIN_NOT_DEFINED
92# define CLARA_CONFIG_MAIN
93# endif
94#endif
95
96// start catch_user_interfaces.h
97
98namespace Catch {
99 unsigned int rngSeed();
100}
101
102// end catch_user_interfaces.h
103// start catch_tag_alias_autoregistrar.h
104
105// start catch_common.h
106
107// start catch_compiler_capabilities.h
108
109// Detect a number of compiler features - by compiler
110// The following features are defined:
111//
112// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
113// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
114// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
115// CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
116// ****************
117// Note to maintainers: if new toggles are added please document them
118// in configuration.md, too
119// ****************
120
121// In general each macro has a _NO_<feature name> form
122// (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
123// Many features, at point of detection, define an _INTERNAL_ macro, so they
124// can be combined, en-mass, with the _NO_ forms later.
125
126#ifdef __cplusplus
127
128# if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
129# define CATCH_CPP14_OR_GREATER
130# endif
131
132# if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
133# define CATCH_CPP17_OR_GREATER
134# endif
135
136#endif
137
138// Only GCC compiler should be used in this block, so other compilers trying to
139// mask themselves as GCC should be ignored.
140#if defined(__GNUC__) && !defined(__clang__) && !defined(__ICC) && !defined(__CUDACC__) && !defined(__LCC__)
141# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic push" )
142# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "GCC diagnostic pop" )
143
144# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__)
145
146#endif
147
148#if defined(__clang__)
149
150# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic push" )
151# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION _Pragma( "clang diagnostic pop" )
152
153// As of this writing, IBM XL's implementation of __builtin_constant_p has a bug
154// which results in calls to destructors being emitted for each temporary,
155// without a matching initialization. In practice, this can result in something
156// like `std::string::~string` being called on an uninitialized value.
157//
158// For example, this code will likely segfault under IBM XL:
159// ```
160// REQUIRE(std::string("12") + "34" == "1234")
161// ```
162//
163// Therefore, `CATCH_INTERNAL_IGNORE_BUT_WARN` is not implemented.
164# if !defined(__ibmxl__) && !defined(__CUDACC__)
165# define CATCH_INTERNAL_IGNORE_BUT_WARN(...) (void)__builtin_constant_p(__VA_ARGS__) /* NOLINT(cppcoreguidelines-pro-type-vararg, hicpp-vararg) */
166# endif
167
168# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
169 _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
170 _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
171
172# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
173 _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
174
175# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
176 _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
177
178# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
179 _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
180
181# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
182 _Pragma( "clang diagnostic ignored \"-Wunused-template\"" )
183
184#endif // __clang__
185
187// Assume that non-Windows platforms support posix signals by default
188#if !defined(CATCH_PLATFORM_WINDOWS)
189 #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
190#endif
191
193// We know some environments not to support full POSIX signals
194#if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
195 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
196#endif
197
198#ifdef __OS400__
199# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
200# define CATCH_CONFIG_COLOUR_NONE
201#endif
202
204// Android somehow still does not support std::to_string
205#if defined(__ANDROID__)
206# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
207# define CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE
208#endif
209
211// Not all Windows environments support SEH properly
212#if defined(__MINGW32__)
213# define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
214#endif
215
217// PS4
218#if defined(__ORBIS__)
219# define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
220#endif
221
223// Cygwin
224#ifdef __CYGWIN__
225
226// Required for some versions of Cygwin to declare gettimeofday
227// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
228# define _BSD_SOURCE
229// some versions of cygwin (most) do not support std::to_string. Use the libstd check.
230// https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
231# if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
232 && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
233
234# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
235
236# endif
237#endif // __CYGWIN__
238
240// Visual C++
241#if defined(_MSC_VER)
242
243// Universal Windows platform does not support SEH
244// Or console colours (or console at all...)
245# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
246# define CATCH_CONFIG_COLOUR_NONE
247# else
248# define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
249# endif
250
251# if !defined(__clang__) // Handle Clang masquerading for msvc
252
253// MSVC traditional preprocessor needs some workaround for __VA_ARGS__
254// _MSVC_TRADITIONAL == 0 means new conformant preprocessor
255// _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
256# if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
257# define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
258# endif // MSVC_TRADITIONAL
259
260// Only do this if we're not using clang on Windows, which uses `diagnostic push` & `diagnostic pop`
261# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION __pragma( warning(push) )
262# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION __pragma( warning(pop) )
263# endif // __clang__
264
265#endif // _MSC_VER
266
267#if defined(_REENTRANT) || defined(_MSC_VER)
268// Enable async processing, as -pthread is specified or no additional linking is required
269# define CATCH_INTERNAL_CONFIG_USE_ASYNC
270#endif // _MSC_VER
271
273// Check if we are compiled with -fno-exceptions or equivalent
274#if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
275# define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
276#endif
277
279// DJGPP
280#ifdef __DJGPP__
281# define CATCH_INTERNAL_CONFIG_NO_WCHAR
282#endif // __DJGPP__
283
285// Embarcadero C++Build
286#if defined(__BORLANDC__)
287 #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
288#endif
289
291
292// Use of __COUNTER__ is suppressed during code analysis in
293// CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
294// handled by it.
295// Otherwise all supported compilers support COUNTER macro,
296// but user still might want to turn it off
297#if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
298 #define CATCH_INTERNAL_CONFIG_COUNTER
299#endif
300
302
303// RTX is a special version of Windows that is real time.
304// This means that it is detected as Windows, but does not provide
305// the same set of capabilities as real Windows does.
306#if defined(UNDER_RTSS) || defined(RTX64_BUILD)
307 #define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
308 #define CATCH_INTERNAL_CONFIG_NO_ASYNC
309 #define CATCH_CONFIG_COLOUR_NONE
310#endif
311
312#if !defined(_GLIBCXX_USE_C99_MATH_TR1)
313#define CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER
314#endif
315
316// Various stdlib support checks that require __has_include
317#if defined(__has_include)
318 // Check if string_view is available and usable
319 #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
320 # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
321 #endif
322
323 // Check if optional is available and usable
324 # if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
325 # define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
326 # endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
327
328 // Check if byte is available and usable
329 # if __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
330 # include <cstddef>
331 # if defined(__cpp_lib_byte) && (__cpp_lib_byte > 0)
332 # define CATCH_INTERNAL_CONFIG_CPP17_BYTE
333 # endif
334 # endif // __has_include(<cstddef>) && defined(CATCH_CPP17_OR_GREATER)
335
336 // Check if variant is available and usable
337 # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
338 # if defined(__clang__) && (__clang_major__ < 8)
339 // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
340 // fix should be in clang 8, workaround in libstdc++ 8.2
341 # include <ciso646>
342 # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
343 # define CATCH_CONFIG_NO_CPP17_VARIANT
344 # else
345 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
346 # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
347 # else
348 # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
349 # endif // defined(__clang__) && (__clang_major__ < 8)
350 # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
351#endif // defined(__has_include)
352
353#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
354# define CATCH_CONFIG_COUNTER
355#endif
356#if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
357# define CATCH_CONFIG_WINDOWS_SEH
358#endif
359// This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
360#if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
361# define CATCH_CONFIG_POSIX_SIGNALS
362#endif
363// This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
364#if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
365# define CATCH_CONFIG_WCHAR
366#endif
367
368#if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
369# define CATCH_CONFIG_CPP11_TO_STRING
370#endif
371
372#if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
373# define CATCH_CONFIG_CPP17_OPTIONAL
374#endif
375
376#if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
377# define CATCH_CONFIG_CPP17_STRING_VIEW
378#endif
379
380#if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
381# define CATCH_CONFIG_CPP17_VARIANT
382#endif
383
384#if defined(CATCH_INTERNAL_CONFIG_CPP17_BYTE) && !defined(CATCH_CONFIG_NO_CPP17_BYTE) && !defined(CATCH_CONFIG_CPP17_BYTE)
385# define CATCH_CONFIG_CPP17_BYTE
386#endif
387
388#if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
389# define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
390#endif
391
392#if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE)
393# define CATCH_CONFIG_NEW_CAPTURE
394#endif
395
396#if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
397# define CATCH_CONFIG_DISABLE_EXCEPTIONS
398#endif
399
400#if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
401# define CATCH_CONFIG_POLYFILL_ISNAN
402#endif
403
404#if defined(CATCH_INTERNAL_CONFIG_USE_ASYNC) && !defined(CATCH_INTERNAL_CONFIG_NO_ASYNC) && !defined(CATCH_CONFIG_NO_USE_ASYNC) && !defined(CATCH_CONFIG_USE_ASYNC)
405# define CATCH_CONFIG_USE_ASYNC
406#endif
407
408#if defined(CATCH_INTERNAL_CONFIG_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_NO_ANDROID_LOGWRITE) && !defined(CATCH_CONFIG_ANDROID_LOGWRITE)
409# define CATCH_CONFIG_ANDROID_LOGWRITE
410#endif
411
412#if defined(CATCH_INTERNAL_CONFIG_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_NO_GLOBAL_NEXTAFTER) && !defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
413# define CATCH_CONFIG_GLOBAL_NEXTAFTER
414#endif
415
416// Even if we do not think the compiler has that warning, we still have
417// to provide a macro that can be used by the code.
418#if !defined(CATCH_INTERNAL_START_WARNINGS_SUPPRESSION)
419# define CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
420#endif
421#if !defined(CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION)
422# define CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
423#endif
424#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
425# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
426#endif
427#if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
428# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
429#endif
430#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
431# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
432#endif
433#if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
434# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
435#endif
436
437// The goal of this macro is to avoid evaluation of the arguments, but
438// still have the compiler warn on problems inside...
439#if !defined(CATCH_INTERNAL_IGNORE_BUT_WARN)
440# define CATCH_INTERNAL_IGNORE_BUT_WARN(...)
441#endif
442
443#if defined(__APPLE__) && defined(__apple_build_version__) && (__clang_major__ < 10)
444# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
445#elif defined(__clang__) && (__clang_major__ < 5)
446# undef CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
447#endif
448
449#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS)
450# define CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS
451#endif
452
453#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
454#define CATCH_TRY if ((true))
455#define CATCH_CATCH_ALL if ((false))
456#define CATCH_CATCH_ANON(type) if ((false))
457#else
458#define CATCH_TRY try
459#define CATCH_CATCH_ALL catch (...)
460#define CATCH_CATCH_ANON(type) catch (type)
461#endif
462
463#if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
464#define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
465#endif
466
467// end catch_compiler_capabilities.h
468#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
469#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
470#ifdef CATCH_CONFIG_COUNTER
471# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
472#else
473# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
474#endif
475
476#include <iosfwd>
477#include <string>
478#include <cstdint>
479
480// We need a dummy global operator<< so we can bring it into Catch namespace later
482std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
483
484namespace Catch {
485
486 struct CaseSensitive { enum Choice {
487 Yes,
488 No
489 }; };
490
492 NonCopyable( NonCopyable const& ) = delete;
493 NonCopyable( NonCopyable && ) = delete;
494 NonCopyable& operator = ( NonCopyable const& ) = delete;
495 NonCopyable& operator = ( NonCopyable && ) = delete;
496
497 protected:
498 NonCopyable();
499 virtual ~NonCopyable();
500 };
501
503
504 SourceLineInfo() = delete;
505 SourceLineInfo( char const* _file, std::size_t _line ) noexcept
506 : file( _file ),
507 line( _line )
508 {}
509
510 SourceLineInfo( SourceLineInfo const& other ) = default;
511 SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
512 SourceLineInfo( SourceLineInfo&& ) noexcept = default;
513 SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
514
515 bool empty() const noexcept { return file[0] == '\0'; }
516 bool operator == ( SourceLineInfo const& other ) const noexcept;
517 bool operator < ( SourceLineInfo const& other ) const noexcept;
518
519 char const* file;
520 std::size_t line;
521 };
522
523 std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
524
525 // Bring in operator<< from global namespace into Catch namespace
526 // This is necessary because the overload of operator<< above makes
527 // lookup stop at namespace Catch
528 using ::operator<<;
529
530 // Use this in variadic streaming macros to allow
531 // >> +StreamEndStop
532 // as well as
533 // >> stuff +StreamEndStop
535 std::string operator+() const;
536 };
537 template<typename T>
538 T const& operator + ( T const& value, StreamEndStop ) {
539 return value;
540 }
541}
542
543#define CATCH_INTERNAL_LINEINFO \
544 ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
545
546// end catch_common.h
547namespace Catch {
548
550 RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
551 };
552
553} // end namespace Catch
554
555#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
556 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
557 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
558 namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
559 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
560
561// end catch_tag_alias_autoregistrar.h
562// start catch_test_registry.h
563
564// start catch_interfaces_testcase.h
565
566#include <vector>
567
568namespace Catch {
569
570 class TestSpec;
571
573 virtual void invoke () const = 0;
574 virtual ~ITestInvoker();
575 };
576
577 class TestCase;
578 struct IConfig;
579
581 virtual ~ITestCaseRegistry();
582 virtual std::vector<TestCase> const& getAllTests() const = 0;
583 virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
584 };
585
586 bool isThrowSafe( TestCase const& testCase, IConfig const& config );
587 bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
588 std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
589 std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
590
591}
592
593// end catch_interfaces_testcase.h
594// start catch_stringref.h
595
596#include <cstddef>
597#include <string>
598#include <iosfwd>
599#include <cassert>
600
601namespace Catch {
602
606 class StringRef {
607 public:
608 using size_type = std::size_t;
609 using const_iterator = const char*;
610
611 private:
612 static constexpr char const* const s_empty = "";
613
614 char const* m_start = s_empty;
615 size_type m_size = 0;
616
617 public: // construction
618 constexpr StringRef() noexcept = default;
619
620 StringRef( char const* rawChars ) noexcept;
621
622 constexpr StringRef( char const* rawChars, size_type size ) noexcept
623 : m_start( rawChars ),
624 m_size( size )
625 {}
626
627 StringRef( std::string const& stdString ) noexcept
628 : m_start( stdString.c_str() ),
629 m_size( stdString.size() )
630 {}
631
632 explicit operator std::string() const {
633 return std::string(m_start, m_size);
634 }
635
636 public: // operators
637 auto operator == ( StringRef const& other ) const noexcept -> bool;
638 auto operator != (StringRef const& other) const noexcept -> bool {
639 return !(*this == other);
640 }
641
642 auto operator[] ( size_type index ) const noexcept -> char {
643 assert(index < m_size);
644 return m_start[index];
645 }
646
647 public: // named queries
648 constexpr auto empty() const noexcept -> bool {
649 return m_size == 0;
650 }
651 constexpr auto size() const noexcept -> size_type {
652 return m_size;
653 }
654
655 // Returns the current start pointer. If the StringRef is not
656 // null-terminated, throws std::domain_exception
657 auto c_str() const -> char const*;
658
659 public: // substrings and searches
660 // Returns a substring of [start, start + length).
661 // If start + length > size(), then the substring is [start, size()).
662 // If start > size(), then the substring is empty.
663 auto substr( size_type start, size_type length ) const noexcept -> StringRef;
664
665 // Returns the current start pointer. May not be null-terminated.
666 auto data() const noexcept -> char const*;
667
668 constexpr auto isNullTerminated() const noexcept -> bool {
669 return m_start[m_size] == '\0';
670 }
671
672 public: // iterators
673 constexpr const_iterator begin() const { return m_start; }
674 constexpr const_iterator end() const { return m_start + m_size; }
675 };
676
677 auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
678 auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
679
680 constexpr auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
681 return StringRef( rawChars, size );
682 }
683} // namespace Catch
684
685constexpr auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
686 return Catch::StringRef( rawChars, size );
687}
688
689// end catch_stringref.h
690// start catch_preprocessor.hpp
691
692
693#define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
694#define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
695#define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
696#define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
697#define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
698#define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
699
700#ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
701#define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
702// MSVC needs more evaluations
703#define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
704#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
705#else
706#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
707#endif
708
709#define CATCH_REC_END(...)
710#define CATCH_REC_OUT
711
712#define CATCH_EMPTY()
713#define CATCH_DEFER(id) id CATCH_EMPTY()
714
715#define CATCH_REC_GET_END2() 0, CATCH_REC_END
716#define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
717#define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
718#define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
719#define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
720#define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
721
722#define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
723#define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
724#define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
725
726#define CATCH_REC_LIST0_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
727#define CATCH_REC_LIST1_UD(f, userdata, x, peek, ...) , f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0_UD) ) ( f, userdata, peek, __VA_ARGS__ )
728#define CATCH_REC_LIST2_UD(f, userdata, x, peek, ...) f(userdata, x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1_UD) ) ( f, userdata, peek, __VA_ARGS__ )
729
730// Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
731// and passes userdata as the first parameter to each invocation,
732// e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
733#define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
734
735#define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
736
737#define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
738#define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
739#define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
740#define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
741#define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
742#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
743#define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
744#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
745#else
746// MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
747#define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
748#define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
749#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
750#endif
751
752#define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
753#define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
754
755#define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
756
757#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
758#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
759#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
760#else
761#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
762#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
763#endif
764
765#define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
766 CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
767
768#define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
769#define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
770#define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
771#define INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_0, _1, _2, _3) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_1, _2, _3)
772#define INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_0, _1, _2, _3, _4) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_4_ARG(_1, _2, _3, _4)
773#define INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_0, _1, _2, _3, _4, _5) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_5_ARG(_1, _2, _3, _4, _5)
774#define INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_0, _1, _2, _3, _4, _5, _6) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_6_ARG(_1, _2, _3, _4, _5, _6)
775#define INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_0, _1, _2, _3, _4, _5, _6, _7) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_7_ARG(_1, _2, _3, _4, _5, _6, _7)
776#define INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_8_ARG(_1, _2, _3, _4, _5, _6, _7, _8)
777#define INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_9_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9)
778#define INTERNAL_CATCH_REMOVE_PARENS_11_ARG(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_10_ARG(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10)
779
780#define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
781
782#define INTERNAL_CATCH_TYPE_GEN\
783 template<typename...> struct TypeList {};\
784 template<typename...Ts>\
785 constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
786 template<template<typename...> class...> struct TemplateTypeList{};\
787 template<template<typename...> class...Cs>\
788 constexpr auto get_wrapper() noexcept -> TemplateTypeList<Cs...> { return {}; }\
789 template<typename...>\
790 struct append;\
791 template<typename...>\
792 struct rewrap;\
793 template<template<typename...> class, typename...>\
794 struct create;\
795 template<template<typename...> class, typename>\
796 struct convert;\
797 \
798 template<typename T> \
799 struct append<T> { using type = T; };\
800 template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
801 struct append<L1<E1...>, L2<E2...>, Rest...> { using type = typename append<L1<E1...,E2...>, Rest...>::type; };\
802 template< template<typename...> class L1, typename...E1, typename...Rest>\
803 struct append<L1<E1...>, TypeList<mpl_::na>, Rest...> { using type = L1<E1...>; };\
804 \
805 template< template<typename...> class Container, template<typename...> class List, typename...elems>\
806 struct rewrap<TemplateTypeList<Container>, List<elems...>> { using type = TypeList<Container<elems...>>; };\
807 template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
808 struct rewrap<TemplateTypeList<Container>, List<Elems...>, Elements...> { using type = typename append<TypeList<Container<Elems...>>, typename rewrap<TemplateTypeList<Container>, Elements...>::type>::type; };\
809 \
810 template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
811 struct create<Final, TemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<TemplateTypeList<Containers>, Types...>::type...>::type; };\
812 template<template <typename...> class Final, template <typename...> class List, typename...Ts>\
813 struct convert<Final, List<Ts...>> { using type = typename append<Final<>,TypeList<Ts>...>::type; };
814
815#define INTERNAL_CATCH_NTTP_1(signature, ...)\
816 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
817 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
818 constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
819 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...> struct NttpTemplateTypeList{};\
820 template<template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Cs>\
821 constexpr auto get_wrapper() noexcept -> NttpTemplateTypeList<Cs...> { return {}; } \
822 \
823 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
824 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>> { using type = TypeList<Container<__VA_ARGS__>>; };\
825 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
826 struct rewrap<NttpTemplateTypeList<Container>, List<__VA_ARGS__>, Elements...> { using type = typename append<TypeList<Container<__VA_ARGS__>>, typename rewrap<NttpTemplateTypeList<Container>, Elements...>::type>::type; };\
827 template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
828 struct create<Final, NttpTemplateTypeList<Containers...>, TypeList<Types...>> { using type = typename append<Final<>, typename rewrap<NttpTemplateTypeList<Containers>, Types...>::type...>::type; };
829
830#define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
831#define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
832 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
833 static void TestName()
834#define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
835 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
836 static void TestName()
837
838#define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
839#define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
840 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
841 static void TestName()
842#define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
843 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
844 static void TestName()
845
846#define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
847 template<typename Type>\
848 void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
849 {\
850 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
851 }
852
853#define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
854 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
855 void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
856 {\
857 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
858 }
859
860#define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
861 template<typename Type>\
862 void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
863 {\
864 Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
865 }
866
867#define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
868 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
869 void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
870 {\
871 Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
872 }
873
874#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
875#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
876 template<typename TestType> \
877 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
878 void test();\
879 }
880
881#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
882 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
883 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
884 void test();\
885 }
886
887#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
888#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
889 template<typename TestType> \
890 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
891#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
892 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
893 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
894
895#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
896#define INTERNAL_CATCH_NTTP_0
897#define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1(__VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_1( __VA_ARGS__),INTERNAL_CATCH_NTTP_1( __VA_ARGS__), INTERNAL_CATCH_NTTP_0)
898#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__)
899#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__)
900#define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__)
901#define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__)
902#define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__)
903#define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__)
904#define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__)
905#else
906#define INTERNAL_CATCH_NTTP_0(signature)
907#define INTERNAL_CATCH_NTTP_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_1,INTERNAL_CATCH_NTTP_1, INTERNAL_CATCH_NTTP_0)( __VA_ARGS__))
908#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1, INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0)(TestName, __VA_ARGS__))
909#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X,INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1, INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0)(TestName, ClassName, __VA_ARGS__))
910#define INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD, INTERNAL_CATCH_NTTP_REGISTER_METHOD0, INTERNAL_CATCH_NTTP_REGISTER_METHOD0)(TestName, __VA_ARGS__))
911#define INTERNAL_CATCH_NTTP_REG_GEN(TestFunc, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER, INTERNAL_CATCH_NTTP_REGISTER0, INTERNAL_CATCH_NTTP_REGISTER0)(TestFunc, __VA_ARGS__))
912#define INTERNAL_CATCH_DEFINE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DEFINE_SIG_TEST1, INTERNAL_CATCH_DEFINE_SIG_TEST0)(TestName, __VA_ARGS__))
913#define INTERNAL_CATCH_DECLARE_SIG_TEST(TestName, ...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL( "dummy", __VA_ARGS__, INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DEFINE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X,INTERNAL_CATCH_DECLARE_SIG_TEST_X, INTERNAL_CATCH_DECLARE_SIG_TEST1, INTERNAL_CATCH_DECLARE_SIG_TEST0)(TestName, __VA_ARGS__))
914#define INTERNAL_CATCH_REMOVE_PARENS_GEN(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_VA_NARGS_IMPL(__VA_ARGS__, INTERNAL_CATCH_REMOVE_PARENS_11_ARG,INTERNAL_CATCH_REMOVE_PARENS_10_ARG,INTERNAL_CATCH_REMOVE_PARENS_9_ARG,INTERNAL_CATCH_REMOVE_PARENS_8_ARG,INTERNAL_CATCH_REMOVE_PARENS_7_ARG,INTERNAL_CATCH_REMOVE_PARENS_6_ARG,INTERNAL_CATCH_REMOVE_PARENS_5_ARG,INTERNAL_CATCH_REMOVE_PARENS_4_ARG,INTERNAL_CATCH_REMOVE_PARENS_3_ARG,INTERNAL_CATCH_REMOVE_PARENS_2_ARG,INTERNAL_CATCH_REMOVE_PARENS_1_ARG)(__VA_ARGS__))
915#endif
916
917// end catch_preprocessor.hpp
918// start catch_meta.hpp
919
920
921#include <type_traits>
922#include <new> // std::nothrow, used by makeTestInvoker() below
923
924namespace Catch {
925 template<typename T>
926 struct always_false : std::false_type {};
927
928 template <typename> struct true_given : std::true_type {};
930 template <typename Fun, typename... Args>
931 true_given<decltype(std::declval<Fun>()(std::declval<Args>()...))> static test(int);
932 template <typename...>
933 std::false_type static test(...);
934 };
935
936 template <typename T>
938
939 template <typename Fun, typename... Args>
940 struct is_callable<Fun(Args...)> : decltype(is_callable_tester::test<Fun, Args...>(0)) {};
941
942#if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
943 // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
944 // replaced with std::invoke_result here.
945 template <typename Func, typename... U>
946 using FunctionReturnType = std::remove_reference_t<std::remove_cv_t<std::invoke_result_t<Func, U...>>>;
947#else
948 // Keep ::type here because we still support C++11
949 template <typename Func, typename... U>
950 using FunctionReturnType = typename std::remove_reference<typename std::remove_cv<typename std::result_of<Func(U...)>::type>::type>::type;
951#endif
952
953} // namespace Catch
954
955namespace mpl_{
956 struct na;
957}
958
959// end catch_meta.hpp
960namespace Catch {
961
962template<typename C>
964 void (C::*m_testAsMethod)();
965public:
966 TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
967
968 void invoke() const override {
969 C obj;
970 (obj.*m_testAsMethod)();
971 }
972};
973
974auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
975
976template<typename C>
977auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
978 return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
979}
980
982 NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
983 StringRef name;
984 StringRef tags;
985};
986
988 AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
989 ~AutoReg();
990};
991
992} // end namespace Catch
993
994#if defined(CATCH_CONFIG_DISABLE)
995 #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
996 static void TestName()
997 #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
998 namespace{ \
999 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1000 void test(); \
1001 }; \
1002 } \
1003 void TestName::test()
1004 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
1005 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1006 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1007 namespace{ \
1008 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1009 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1010 } \
1011 } \
1012 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1013
1014 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1015 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1016 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename TestType, __VA_ARGS__ )
1017 #else
1018 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
1019 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
1020 #endif
1021
1022 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1023 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1024 INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__ )
1025 #else
1026 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
1027 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__ ) )
1028 #endif
1029
1030 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1031 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1032 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
1033 #else
1034 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
1035 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
1036 #endif
1037
1038 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1039 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1040 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
1041 #else
1042 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
1043 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
1044 #endif
1045#endif
1046
1048 #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
1049 static void TestName(); \
1050 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1051 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1052 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
1053 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1054 static void TestName()
1055 #define INTERNAL_CATCH_TESTCASE( ... ) \
1056 INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), __VA_ARGS__ )
1057
1059 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
1060 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1061 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1062 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
1063 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1064
1066 #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
1067 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1068 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1069 namespace{ \
1070 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1071 void test(); \
1072 }; \
1073 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
1074 } \
1075 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1076 void TestName::test()
1077 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
1078 INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), ClassName, __VA_ARGS__ )
1079
1081 #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
1082 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1083 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1084 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
1085 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
1086
1088 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
1089 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1090 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1091 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1092 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1093 INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1094 namespace {\
1095 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1096 INTERNAL_CATCH_TYPE_GEN\
1097 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1098 INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1099 template<typename...Types> \
1100 struct TestName{\
1101 TestName(){\
1102 int index = 0; \
1103 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1104 using expander = int[];\
1105 (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
1106 }\
1107 };\
1108 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1109 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1110 return 0;\
1111 }();\
1112 }\
1113 }\
1114 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1115 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
1116
1117#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1118 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1119 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename TestType, __VA_ARGS__ )
1120#else
1121 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1122 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename TestType, __VA_ARGS__ ) )
1123#endif
1124
1125#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1126 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1127 INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__ )
1128#else
1129 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1130 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__ ) )
1131#endif
1132
1133 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
1134 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1135 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1136 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1137 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1138 template<typename TestType> static void TestFuncName(); \
1139 namespace {\
1140 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1141 INTERNAL_CATCH_TYPE_GEN \
1142 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1143 template<typename... Types> \
1144 struct TestName { \
1145 void reg_tests() { \
1146 int index = 0; \
1147 using expander = int[]; \
1148 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1149 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1150 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1151 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFuncName<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */\
1152 } \
1153 }; \
1154 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1155 using TestInit = typename create<TestName, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type; \
1156 TestInit t; \
1157 t.reg_tests(); \
1158 return 0; \
1159 }(); \
1160 } \
1161 } \
1162 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1163 template<typename TestType> \
1164 static void TestFuncName()
1165
1166#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1167 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1168 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename T,__VA_ARGS__)
1169#else
1170 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1171 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, typename T, __VA_ARGS__ ) )
1172#endif
1173
1174#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1175 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1176 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__)
1177#else
1178 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1179 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, Signature, __VA_ARGS__ ) )
1180#endif
1181
1182 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2(TestName, TestFunc, Name, Tags, TmplList)\
1183 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1184 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1185 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1186 template<typename TestType> static void TestFunc(); \
1187 namespace {\
1188 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1189 INTERNAL_CATCH_TYPE_GEN\
1190 template<typename... Types> \
1191 struct TestName { \
1192 void reg_tests() { \
1193 int index = 0; \
1194 using expander = int[]; \
1195 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestFunc<Types> ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */\
1196 } \
1197 };\
1198 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1199 using TestInit = typename convert<TestName, TmplList>::type; \
1200 TestInit t; \
1201 t.reg_tests(); \
1202 return 0; \
1203 }(); \
1204 }}\
1205 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1206 template<typename TestType> \
1207 static void TestFunc()
1208
1209 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(Name, Tags, TmplList) \
1210 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), Name, Tags, TmplList )
1211
1212 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1213 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1214 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1215 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1216 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1217 namespace {\
1218 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1219 INTERNAL_CATCH_TYPE_GEN\
1220 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1221 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1222 INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1223 template<typename...Types> \
1224 struct TestNameClass{\
1225 TestNameClass(){\
1226 int index = 0; \
1227 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1228 using expander = int[];\
1229 (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++)... };/* NOLINT */ \
1230 }\
1231 };\
1232 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1233 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1234 return 0;\
1235 }();\
1236 }\
1237 }\
1238 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1239 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1240
1241#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1242 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1243 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ )
1244#else
1245 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1246 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, typename T, __VA_ARGS__ ) )
1247#endif
1248
1249#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1250 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1251 INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ )
1252#else
1253 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1254 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_C_L_A_S_S_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ) , ClassName, Name, Tags, Signature, __VA_ARGS__ ) )
1255#endif
1256
1257 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
1258 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1259 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1260 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1261 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1262 template<typename TestType> \
1263 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1264 void test();\
1265 };\
1266 namespace {\
1267 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
1268 INTERNAL_CATCH_TYPE_GEN \
1269 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1270 template<typename...Types>\
1271 struct TestNameClass{\
1272 void reg_tests(){\
1273 int index = 0;\
1274 using expander = int[];\
1275 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1276 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1277 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1278 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index / num_types]) + "<" + std::string(types_list[index % num_types]) + ">", Tags } ), index++)... };/* NOLINT */ \
1279 }\
1280 };\
1281 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1282 using TestInit = typename create<TestNameClass, decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>()), TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>>::type;\
1283 TestInit t;\
1284 t.reg_tests();\
1285 return 0;\
1286 }(); \
1287 }\
1288 }\
1289 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1290 template<typename TestType> \
1291 void TestName<TestType>::test()
1292
1293#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1294 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1295 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), ClassName, Name, Tags, typename T, __VA_ARGS__ )
1296#else
1297 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1298 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), ClassName, Name, Tags, typename T,__VA_ARGS__ ) )
1299#endif
1300
1301#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1302 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1303 INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), ClassName, Name, Tags, Signature, __VA_ARGS__ )
1304#else
1305 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1306 INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), ClassName, Name, Tags, Signature,__VA_ARGS__ ) )
1307#endif
1308
1309 #define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, TmplList) \
1310 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
1311 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1312 CATCH_INTERNAL_SUPPRESS_UNUSED_TEMPLATE_WARNINGS \
1313 template<typename TestType> \
1314 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1315 void test();\
1316 };\
1317 namespace {\
1318 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1319 INTERNAL_CATCH_TYPE_GEN\
1320 template<typename...Types>\
1321 struct TestNameClass{\
1322 void reg_tests(){\
1323 int index = 0;\
1324 using expander = int[];\
1325 (void)expander{(Catch::AutoReg( Catch::makeTestInvoker( &TestName<Types>::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ Name " - " + std::string(INTERNAL_CATCH_STRINGIZE(TmplList)) + " - " + std::to_string(index), Tags } ), index++)... };/* NOLINT */ \
1326 }\
1327 };\
1328 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1329 using TestInit = typename convert<TestNameClass, TmplList>::type;\
1330 TestInit t;\
1331 t.reg_tests();\
1332 return 0;\
1333 }(); \
1334 }}\
1335 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
1336 template<typename TestType> \
1337 void TestName<TestType>::test()
1338
1339#define INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD(ClassName, Name, Tags, TmplList) \
1340 INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD_2( INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_ ), INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_M_P_L_A_T_E_T_E_S_T_F_U_N_C_ ), ClassName, Name, Tags, TmplList )
1341
1342// end catch_test_registry.h
1343// start catch_capture.hpp
1344
1345// start catch_assertionhandler.h
1346
1347// start catch_assertioninfo.h
1348
1349// start catch_result_type.h
1350
1351namespace Catch {
1352
1353 // ResultWas::OfType enum
1354 struct ResultWas { enum OfType {
1355 Unknown = -1,
1356 Ok = 0,
1357 Info = 1,
1358 Warning = 2,
1359
1360 FailureBit = 0x10,
1361
1362 ExpressionFailed = FailureBit | 1,
1363 ExplicitFailure = FailureBit | 2,
1364
1365 Exception = 0x100 | FailureBit,
1366
1367 ThrewException = Exception | 1,
1368 DidntThrowException = Exception | 2,
1369
1370 FatalErrorCondition = 0x200 | FailureBit
1371
1372 }; };
1373
1374 bool isOk( ResultWas::OfType resultType );
1375 bool isJustInfo( int flags );
1376
1377 // ResultDisposition::Flags enum
1378 struct ResultDisposition { enum Flags {
1379 Normal = 0x01,
1380
1381 ContinueOnFailure = 0x02, // Failures fail test, but execution continues
1382 FalseTest = 0x04, // Prefix expression with !
1383 SuppressFail = 0x08 // Failures are reported but do not fail the test
1384 }; };
1385
1386 ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
1387
1388 bool shouldContinueOnFailure( int flags );
1389 inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
1390 bool shouldSuppressFailure( int flags );
1391
1392} // end namespace Catch
1393
1394// end catch_result_type.h
1395namespace Catch {
1396
1398 {
1399 StringRef macroName;
1400 SourceLineInfo lineInfo;
1401 StringRef capturedExpression;
1402 ResultDisposition::Flags resultDisposition;
1403
1404 // We want to delete this constructor but a compiler bug in 4.8 means
1405 // the struct is then treated as non-aggregate
1406 //AssertionInfo() = delete;
1407 };
1408
1409} // end namespace Catch
1410
1411// end catch_assertioninfo.h
1412// start catch_decomposer.h
1413
1414// start catch_tostring.h
1415
1416#include <vector>
1417#include <cstddef>
1418#include <type_traits>
1419#include <string>
1420// start catch_stream.h
1421
1422#include <iosfwd>
1423#include <cstddef>
1424#include <ostream>
1425
1426namespace Catch {
1427
1428 std::ostream& cout();
1429 std::ostream& cerr();
1430 std::ostream& clog();
1431
1432 class StringRef;
1433
1434 struct IStream {
1435 virtual ~IStream();
1436 virtual std::ostream& stream() const = 0;
1437 };
1438
1439 auto makeStream( StringRef const &filename ) -> IStream const*;
1440
1442 std::size_t m_index;
1443 std::ostream* m_oss;
1444 public:
1447
1448 auto str() const -> std::string;
1449
1450 template<typename T>
1451 auto operator << ( T const& value ) -> ReusableStringStream& {
1452 *m_oss << value;
1453 return *this;
1454 }
1455 auto get() -> std::ostream& { return *m_oss; }
1456 };
1457}
1458
1459// end catch_stream.h
1460// start catch_interfaces_enum_values_registry.h
1461
1462#include <vector>
1463
1464namespace Catch {
1465
1466 namespace Detail {
1467 struct EnumInfo {
1468 StringRef m_name;
1469 std::vector<std::pair<int, StringRef>> m_values;
1470
1471 ~EnumInfo();
1472
1473 StringRef lookup( int value ) const;
1474 };
1475 } // namespace Detail
1476
1479
1480 virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
1481
1482 template<typename E>
1483 Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::initializer_list<E> values ) {
1484 static_assert(sizeof(int) >= sizeof(E), "Cannot serialize enum to int");
1485 std::vector<int> intValues;
1486 intValues.reserve( values.size() );
1487 for( auto enumValue : values )
1488 intValues.push_back( static_cast<int>( enumValue ) );
1489 return registerEnum( enumName, allEnums, intValues );
1490 }
1491 };
1492
1493} // Catch
1494
1495// end catch_interfaces_enum_values_registry.h
1496
1497#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1498#include <string_view>
1499#endif
1500
1501#ifdef __OBJC__
1502// start catch_objc_arc.hpp
1503
1504#import <Foundation/Foundation.h>
1505
1506#ifdef __has_feature
1507#define CATCH_ARC_ENABLED __has_feature(objc_arc)
1508#else
1509#define CATCH_ARC_ENABLED 0
1510#endif
1511
1512void arcSafeRelease( NSObject* obj );
1513id performOptionalSelector( id obj, SEL sel );
1514
1515#if !CATCH_ARC_ENABLED
1516inline void arcSafeRelease( NSObject* obj ) {
1517 [obj release];
1518}
1519inline id performOptionalSelector( id obj, SEL sel ) {
1520 if( [obj respondsToSelector: sel] )
1521 return [obj performSelector: sel];
1522 return nil;
1523}
1524#define CATCH_UNSAFE_UNRETAINED
1525#define CATCH_ARC_STRONG
1526#else
1527inline void arcSafeRelease( NSObject* ){}
1528inline id performOptionalSelector( id obj, SEL sel ) {
1529#ifdef __clang__
1530#pragma clang diagnostic push
1531#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
1532#endif
1533 if( [obj respondsToSelector: sel] )
1534 return [obj performSelector: sel];
1535#ifdef __clang__
1536#pragma clang diagnostic pop
1537#endif
1538 return nil;
1539}
1540#define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
1541#define CATCH_ARC_STRONG __strong
1542#endif
1543
1544// end catch_objc_arc.hpp
1545#endif
1546
1547#ifdef _MSC_VER
1548#pragma warning(push)
1549#pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
1550#endif
1551
1552namespace Catch {
1553 namespace Detail {
1554
1555 extern const std::string unprintableString;
1556
1557 std::string rawMemoryToString( const void *object, std::size_t size );
1558
1559 template<typename T>
1560 std::string rawMemoryToString( const T& object ) {
1561 return rawMemoryToString( &object, sizeof(object) );
1562 }
1563
1564 template<typename T>
1566 template<typename Stream, typename U>
1567 static auto test(int)
1568 -> decltype(std::declval<Stream&>() << std::declval<U>(), std::true_type());
1569
1570 template<typename, typename>
1571 static auto test(...)->std::false_type;
1572
1573 public:
1574 static const bool value = decltype(test<std::ostream, const T&>(0))::value;
1575 };
1576
1577 template<typename E>
1578 std::string convertUnknownEnumToString( E e );
1579
1580 template<typename T>
1581 typename std::enable_if<
1582 !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
1583 std::string>::type convertUnstreamable( T const& ) {
1584 return Detail::unprintableString;
1585 }
1586 template<typename T>
1587 typename std::enable_if<
1588 !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
1589 std::string>::type convertUnstreamable(T const& ex) {
1590 return ex.what();
1591 }
1592
1593 template<typename T>
1594 typename std::enable_if<
1595 std::is_enum<T>::value
1596 , std::string>::type convertUnstreamable( T const& value ) {
1597 return convertUnknownEnumToString( value );
1598 }
1599
1600#if defined(_MANAGED)
1602 template<typename T>
1603 std::string clrReferenceToString( T^ ref ) {
1604 if (ref == nullptr)
1605 return std::string("null");
1606 auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
1607 cli::pin_ptr<System::Byte> p = &bytes[0];
1608 return std::string(reinterpret_cast<char const *>(p), bytes->Length);
1609 }
1610#endif
1611
1612 } // namespace Detail
1613
1614 // If we decide for C++14, change these to enable_if_ts
1615 template <typename T, typename = void>
1617 template <typename Fake = T>
1618 static
1619 typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
1620 convert(const Fake& value) {
1622 // NB: call using the function-like syntax to avoid ambiguity with
1623 // user-defined templated operator<< under clang.
1624 rss.operator<<(value);
1625 return rss.str();
1626 }
1627
1628 template <typename Fake = T>
1629 static
1630 typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
1631 convert( const Fake& value ) {
1632#if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
1633 return Detail::convertUnstreamable(value);
1634#else
1635 return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
1636#endif
1637 }
1638 };
1639
1640 namespace Detail {
1641
1642 // This function dispatches all stringification requests inside of Catch.
1643 // Should be preferably called fully qualified, like ::Catch::Detail::stringify
1644 template <typename T>
1645 std::string stringify(const T& e) {
1646 return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
1647 }
1648
1649 template<typename E>
1650 std::string convertUnknownEnumToString( E e ) {
1651 return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
1652 }
1653
1654#if defined(_MANAGED)
1655 template <typename T>
1656 std::string stringify( T^ e ) {
1657 return ::Catch::StringMaker<T^>::convert(e);
1658 }
1659#endif
1660
1661 } // namespace Detail
1662
1663 // Some predefined specializations
1664
1665 template<>
1666 struct StringMaker<std::string> {
1667 static std::string convert(const std::string& str);
1668 };
1669
1670#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1671 template<>
1672 struct StringMaker<std::string_view> {
1673 static std::string convert(std::string_view str);
1674 };
1675#endif
1676
1677 template<>
1678 struct StringMaker<char const *> {
1679 static std::string convert(char const * str);
1680 };
1681 template<>
1682 struct StringMaker<char *> {
1683 static std::string convert(char * str);
1684 };
1685
1686#ifdef CATCH_CONFIG_WCHAR
1687 template<>
1688 struct StringMaker<std::wstring> {
1689 static std::string convert(const std::wstring& wstr);
1690 };
1691
1692# ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1693 template<>
1694 struct StringMaker<std::wstring_view> {
1695 static std::string convert(std::wstring_view str);
1696 };
1697# endif
1698
1699 template<>
1700 struct StringMaker<wchar_t const *> {
1701 static std::string convert(wchar_t const * str);
1702 };
1703 template<>
1704 struct StringMaker<wchar_t *> {
1705 static std::string convert(wchar_t * str);
1706 };
1707#endif
1708
1709 // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
1710 // while keeping string semantics?
1711 template<int SZ>
1712 struct StringMaker<char[SZ]> {
1713 static std::string convert(char const* str) {
1714 return ::Catch::Detail::stringify(std::string{ str });
1715 }
1716 };
1717 template<int SZ>
1718 struct StringMaker<signed char[SZ]> {
1719 static std::string convert(signed char const* str) {
1720 return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
1721 }
1722 };
1723 template<int SZ>
1724 struct StringMaker<unsigned char[SZ]> {
1725 static std::string convert(unsigned char const* str) {
1726 return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
1727 }
1728 };
1729
1730#if defined(CATCH_CONFIG_CPP17_BYTE)
1731 template<>
1732 struct StringMaker<std::byte> {
1733 static std::string convert(std::byte value);
1734 };
1735#endif // defined(CATCH_CONFIG_CPP17_BYTE)
1736 template<>
1737 struct StringMaker<int> {
1738 static std::string convert(int value);
1739 };
1740 template<>
1741 struct StringMaker<long> {
1742 static std::string convert(long value);
1743 };
1744 template<>
1745 struct StringMaker<long long> {
1746 static std::string convert(long long value);
1747 };
1748 template<>
1749 struct StringMaker<unsigned int> {
1750 static std::string convert(unsigned int value);
1751 };
1752 template<>
1753 struct StringMaker<unsigned long> {
1754 static std::string convert(unsigned long value);
1755 };
1756 template<>
1757 struct StringMaker<unsigned long long> {
1758 static std::string convert(unsigned long long value);
1759 };
1760
1761 template<>
1762 struct StringMaker<bool> {
1763 static std::string convert(bool b);
1764 };
1765
1766 template<>
1767 struct StringMaker<char> {
1768 static std::string convert(char c);
1769 };
1770 template<>
1771 struct StringMaker<signed char> {
1772 static std::string convert(signed char c);
1773 };
1774 template<>
1775 struct StringMaker<unsigned char> {
1776 static std::string convert(unsigned char c);
1777 };
1778
1779 template<>
1780 struct StringMaker<std::nullptr_t> {
1781 static std::string convert(std::nullptr_t);
1782 };
1783
1784 template<>
1785 struct StringMaker<float> {
1786 static std::string convert(float value);
1787 static int precision;
1788 };
1789
1790 template<>
1791 struct StringMaker<double> {
1792 static std::string convert(double value);
1793 static int precision;
1794 };
1795
1796 template <typename T>
1797 struct StringMaker<T*> {
1798 template <typename U>
1799 static std::string convert(U* p) {
1800 if (p) {
1801 return ::Catch::Detail::rawMemoryToString(p);
1802 } else {
1803 return "nullptr";
1804 }
1805 }
1806 };
1807
1808 template <typename R, typename C>
1809 struct StringMaker<R C::*> {
1810 static std::string convert(R C::* p) {
1811 if (p) {
1812 return ::Catch::Detail::rawMemoryToString(p);
1813 } else {
1814 return "nullptr";
1815 }
1816 }
1817 };
1818
1819#if defined(_MANAGED)
1820 template <typename T>
1821 struct StringMaker<T^> {
1822 static std::string convert( T^ ref ) {
1823 return ::Catch::Detail::clrReferenceToString(ref);
1824 }
1825 };
1826#endif
1827
1828 namespace Detail {
1829 template<typename InputIterator, typename Sentinel = InputIterator>
1830 std::string rangeToString(InputIterator first, Sentinel last) {
1831 ReusableStringStream rss;
1832 rss << "{ ";
1833 if (first != last) {
1834 rss << ::Catch::Detail::stringify(*first);
1835 for (++first; first != last; ++first)
1836 rss << ", " << ::Catch::Detail::stringify(*first);
1837 }
1838 rss << " }";
1839 return rss.str();
1840 }
1841 }
1842
1843#ifdef __OBJC__
1844 template<>
1845 struct StringMaker<NSString*> {
1846 static std::string convert(NSString * nsstring) {
1847 if (!nsstring)
1848 return "nil";
1849 return std::string("@") + [nsstring UTF8String];
1850 }
1851 };
1852 template<>
1853 struct StringMaker<NSObject*> {
1854 static std::string convert(NSObject* nsObject) {
1855 return ::Catch::Detail::stringify([nsObject description]);
1856 }
1857
1858 };
1859 namespace Detail {
1860 inline std::string stringify( NSString* nsstring ) {
1861 return StringMaker<NSString*>::convert( nsstring );
1862 }
1863
1864 } // namespace Detail
1865#endif // __OBJC__
1866
1867} // namespace Catch
1868
1870// Separate std-lib types stringification, so it can be selectively enabled
1871// This means that we do not bring in
1872
1873#if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
1874# define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1875# define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1876# define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1877# define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
1878# define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1879#endif
1880
1881// Separate std::pair specialization
1882#if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
1883#include <utility>
1884namespace Catch {
1885 template<typename T1, typename T2>
1886 struct StringMaker<std::pair<T1, T2> > {
1887 static std::string convert(const std::pair<T1, T2>& pair) {
1888 ReusableStringStream rss;
1889 rss << "{ "
1890 << ::Catch::Detail::stringify(pair.first)
1891 << ", "
1892 << ::Catch::Detail::stringify(pair.second)
1893 << " }";
1894 return rss.str();
1895 }
1896 };
1897}
1898#endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1899
1900#if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
1901#include <optional>
1902namespace Catch {
1903 template<typename T>
1904 struct StringMaker<std::optional<T> > {
1905 static std::string convert(const std::optional<T>& optional) {
1906 ReusableStringStream rss;
1907 if (optional.has_value()) {
1908 rss << ::Catch::Detail::stringify(*optional);
1909 } else {
1910 rss << "{ }";
1911 }
1912 return rss.str();
1913 }
1914 };
1915}
1916#endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1917
1918// Separate std::tuple specialization
1919#if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
1920#include <tuple>
1921namespace Catch {
1922 namespace Detail {
1923 template<
1924 typename Tuple,
1925 std::size_t N = 0,
1926 bool = (N < std::tuple_size<Tuple>::value)
1927 >
1928 struct TupleElementPrinter {
1929 static void print(const Tuple& tuple, std::ostream& os) {
1930 os << (N ? ", " : " ")
1931 << ::Catch::Detail::stringify(std::get<N>(tuple));
1932 TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
1933 }
1934 };
1935
1936 template<
1937 typename Tuple,
1938 std::size_t N
1939 >
1940 struct TupleElementPrinter<Tuple, N, false> {
1941 static void print(const Tuple&, std::ostream&) {}
1942 };
1943
1944 }
1945
1946 template<typename ...Types>
1947 struct StringMaker<std::tuple<Types...>> {
1948 static std::string convert(const std::tuple<Types...>& tuple) {
1949 ReusableStringStream rss;
1950 rss << '{';
1951 Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
1952 rss << " }";
1953 return rss.str();
1954 }
1955 };
1956}
1957#endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1958
1959#if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
1960#include <variant>
1961namespace Catch {
1962 template<>
1963 struct StringMaker<std::monostate> {
1964 static std::string convert(const std::monostate&) {
1965 return "{ }";
1966 }
1967 };
1968
1969 template<typename... Elements>
1970 struct StringMaker<std::variant<Elements...>> {
1971 static std::string convert(const std::variant<Elements...>& variant) {
1972 if (variant.valueless_by_exception()) {
1973 return "{valueless variant}";
1974 } else {
1975 return std::visit(
1976 [](const auto& value) {
1977 return ::Catch::Detail::stringify(value);
1978 },
1979 variant
1980 );
1981 }
1982 }
1983 };
1984}
1985#endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1986
1987namespace Catch {
1988 // Import begin/ end from std here
1989 using std::begin;
1990 using std::end;
1991
1992 namespace detail {
1993 template <typename...>
1994 struct void_type {
1995 using type = void;
1996 };
1997
1998 template <typename T, typename = void>
1999 struct is_range_impl : std::false_type {
2000 };
2001
2002 template <typename T>
2004 };
2005 } // namespace detail
2006
2007 template <typename T>
2009 };
2010
2011#if defined(_MANAGED) // Managed types are never ranges
2012 template <typename T>
2013 struct is_range<T^> {
2014 static const bool value = false;
2015 };
2016#endif
2017
2018 template<typename Range>
2019 std::string rangeToString( Range const& range ) {
2020 return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
2021 }
2022
2023 // Handle vector<bool> specially
2024 template<typename Allocator>
2025 std::string rangeToString( std::vector<bool, Allocator> const& v ) {
2026 ReusableStringStream rss;
2027 rss << "{ ";
2028 bool first = true;
2029 for( bool b : v ) {
2030 if( first )
2031 first = false;
2032 else
2033 rss << ", ";
2034 rss << ::Catch::Detail::stringify( b );
2035 }
2036 rss << " }";
2037 return rss.str();
2038 }
2039
2040 template<typename R>
2041 struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
2042 static std::string convert( R const& range ) {
2043 return rangeToString( range );
2044 }
2045 };
2046
2047 template <typename T, int SZ>
2048 struct StringMaker<T[SZ]> {
2049 static std::string convert(T const(&arr)[SZ]) {
2050 return rangeToString(arr);
2051 }
2052 };
2053
2054} // namespace Catch
2055
2056// Separate std::chrono::duration specialization
2057#if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
2058#include <ctime>
2059#include <ratio>
2060#include <chrono>
2061
2062namespace Catch {
2063
2064template <class Ratio>
2065struct ratio_string {
2066 static std::string symbol();
2067};
2068
2069template <class Ratio>
2070std::string ratio_string<Ratio>::symbol() {
2072 rss << '[' << Ratio::num << '/'
2073 << Ratio::den << ']';
2074 return rss.str();
2075}
2076template <>
2077struct ratio_string<std::atto> {
2078 static std::string symbol();
2079};
2080template <>
2081struct ratio_string<std::femto> {
2082 static std::string symbol();
2083};
2084template <>
2085struct ratio_string<std::pico> {
2086 static std::string symbol();
2087};
2088template <>
2089struct ratio_string<std::nano> {
2090 static std::string symbol();
2091};
2092template <>
2093struct ratio_string<std::micro> {
2094 static std::string symbol();
2095};
2096template <>
2097struct ratio_string<std::milli> {
2098 static std::string symbol();
2099};
2100
2102 // std::chrono::duration specializations
2103 template<typename Value, typename Ratio>
2104 struct StringMaker<std::chrono::duration<Value, Ratio>> {
2105 static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
2106 ReusableStringStream rss;
2107 rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
2108 return rss.str();
2109 }
2110 };
2111 template<typename Value>
2112 struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
2113 static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
2114 ReusableStringStream rss;
2115 rss << duration.count() << " s";
2116 return rss.str();
2117 }
2118 };
2119 template<typename Value>
2120 struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
2121 static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
2122 ReusableStringStream rss;
2123 rss << duration.count() << " m";
2124 return rss.str();
2125 }
2126 };
2127 template<typename Value>
2128 struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
2129 static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
2130 ReusableStringStream rss;
2131 rss << duration.count() << " h";
2132 return rss.str();
2133 }
2134 };
2135
2137 // std::chrono::time_point specialization
2138 // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
2139 template<typename Clock, typename Duration>
2140 struct StringMaker<std::chrono::time_point<Clock, Duration>> {
2141 static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
2142 return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
2143 }
2144 };
2145 // std::chrono::time_point<system_clock> specialization
2146 template<typename Duration>
2147 struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
2148 static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
2149 auto converted = std::chrono::system_clock::to_time_t(time_point);
2150
2151#ifdef _MSC_VER
2152 std::tm timeInfo = {};
2153 gmtime_s(&timeInfo, &converted);
2154#else
2155 std::tm* timeInfo = std::gmtime(&converted);
2156#endif
2157
2158 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
2159 char timeStamp[timeStampSize];
2160 const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
2161
2162#ifdef _MSC_VER
2163 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2164#else
2165 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2166#endif
2167 return std::string(timeStamp);
2168 }
2169 };
2170}
2171#endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2172
2173#define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
2174namespace Catch { \
2175 template<> struct StringMaker<enumName> { \
2176 static std::string convert( enumName value ) { \
2177 static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
2178 return static_cast<std::string>(enumInfo.lookup( static_cast<int>( value ) )); \
2179 } \
2180 }; \
2181}
2182
2183#define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
2184
2185#ifdef _MSC_VER
2186#pragma warning(pop)
2187#endif
2188
2189// end catch_tostring.h
2190#include <iosfwd>
2191
2192#ifdef _MSC_VER
2193#pragma warning(push)
2194#pragma warning(disable:4389) // '==' : signed/unsigned mismatch
2195#pragma warning(disable:4018) // more "signed/unsigned mismatch"
2196#pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
2197#pragma warning(disable:4180) // qualifier applied to function type has no meaning
2198#pragma warning(disable:4800) // Forcing result to true or false
2199#endif
2200
2201namespace Catch {
2202
2204 auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
2205 auto getResult() const -> bool { return m_result; }
2206 virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
2207
2208 ITransientExpression( bool isBinaryExpression, bool result )
2209 : m_isBinaryExpression( isBinaryExpression ),
2210 m_result( result )
2211 {}
2212
2213 // We don't actually need a virtual destructor, but many static analysers
2214 // complain if it's not here :-(
2215 virtual ~ITransientExpression();
2216
2217 bool m_isBinaryExpression;
2218 bool m_result;
2219
2220 };
2221
2222 void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
2223
2224 template<typename LhsT, typename RhsT>
2226 LhsT m_lhs;
2227 StringRef m_op;
2228 RhsT m_rhs;
2229
2230 void streamReconstructedExpression( std::ostream &os ) const override {
2231 formatReconstructedExpression
2232 ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
2233 }
2234
2235 public:
2236 BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
2237 : ITransientExpression{ true, comparisonResult },
2238 m_lhs( lhs ),
2239 m_op( op ),
2240 m_rhs( rhs )
2241 {}
2242
2243 template<typename T>
2244 auto operator && ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2245 static_assert(always_false<T>::value,
2246 "chained comparisons are not supported inside assertions, "
2247 "wrap the expression inside parentheses, or decompose it");
2248 }
2249
2250 template<typename T>
2251 auto operator || ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2252 static_assert(always_false<T>::value,
2253 "chained comparisons are not supported inside assertions, "
2254 "wrap the expression inside parentheses, or decompose it");
2255 }
2256
2257 template<typename T>
2258 auto operator == ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2259 static_assert(always_false<T>::value,
2260 "chained comparisons are not supported inside assertions, "
2261 "wrap the expression inside parentheses, or decompose it");
2262 }
2263
2264 template<typename T>
2265 auto operator != ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2266 static_assert(always_false<T>::value,
2267 "chained comparisons are not supported inside assertions, "
2268 "wrap the expression inside parentheses, or decompose it");
2269 }
2270
2271 template<typename T>
2272 auto operator > ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2273 static_assert(always_false<T>::value,
2274 "chained comparisons are not supported inside assertions, "
2275 "wrap the expression inside parentheses, or decompose it");
2276 }
2277
2278 template<typename T>
2279 auto operator < ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2280 static_assert(always_false<T>::value,
2281 "chained comparisons are not supported inside assertions, "
2282 "wrap the expression inside parentheses, or decompose it");
2283 }
2284
2285 template<typename T>
2286 auto operator >= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2287 static_assert(always_false<T>::value,
2288 "chained comparisons are not supported inside assertions, "
2289 "wrap the expression inside parentheses, or decompose it");
2290 }
2291
2292 template<typename T>
2293 auto operator <= ( T ) const -> BinaryExpr<LhsT, RhsT const&> const {
2294 static_assert(always_false<T>::value,
2295 "chained comparisons are not supported inside assertions, "
2296 "wrap the expression inside parentheses, or decompose it");
2297 }
2298 };
2299
2300 template<typename LhsT>
2302 LhsT m_lhs;
2303
2304 void streamReconstructedExpression( std::ostream &os ) const override {
2305 os << Catch::Detail::stringify( m_lhs );
2306 }
2307
2308 public:
2309 explicit UnaryExpr( LhsT lhs )
2310 : ITransientExpression{ false, static_cast<bool>(lhs) },
2311 m_lhs( lhs )
2312 {}
2313 };
2314
2315 // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
2316 template<typename LhsT, typename RhsT>
2317 auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
2318 template<typename T>
2319 auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
2320 template<typename T>
2321 auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
2322 template<typename T>
2323 auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
2324 template<typename T>
2325 auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
2326
2327 template<typename LhsT, typename RhsT>
2328 auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
2329 template<typename T>
2330 auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
2331 template<typename T>
2332 auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
2333 template<typename T>
2334 auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
2335 template<typename T>
2336 auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
2337
2338 template<typename LhsT>
2339 class ExprLhs {
2340 LhsT m_lhs;
2341 public:
2342 explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
2343
2344 template<typename RhsT>
2345 auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2346 return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
2347 }
2348 auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
2349 return { m_lhs == rhs, m_lhs, "==", rhs };
2350 }
2351
2352 template<typename RhsT>
2353 auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2354 return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
2355 }
2356 auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
2357 return { m_lhs != rhs, m_lhs, "!=", rhs };
2358 }
2359
2360 template<typename RhsT>
2361 auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2362 return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
2363 }
2364 template<typename RhsT>
2365 auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2366 return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
2367 }
2368 template<typename RhsT>
2369 auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2370 return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
2371 }
2372 template<typename RhsT>
2373 auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2374 return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
2375 }
2376 template <typename RhsT>
2377 auto operator | (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2378 return { static_cast<bool>(m_lhs | rhs), m_lhs, "|", rhs };
2379 }
2380 template <typename RhsT>
2381 auto operator & (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2382 return { static_cast<bool>(m_lhs & rhs), m_lhs, "&", rhs };
2383 }
2384 template <typename RhsT>
2385 auto operator ^ (RhsT const& rhs) -> BinaryExpr<LhsT, RhsT const&> const {
2386 return { static_cast<bool>(m_lhs ^ rhs), m_lhs, "^", rhs };
2387 }
2388
2389 template<typename RhsT>
2390 auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
2391 static_assert(always_false<RhsT>::value,
2392 "operator&& is not supported inside assertions, "
2393 "wrap the expression inside parentheses, or decompose it");
2394 }
2395
2396 template<typename RhsT>
2397 auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
2398 static_assert(always_false<RhsT>::value,
2399 "operator|| is not supported inside assertions, "
2400 "wrap the expression inside parentheses, or decompose it");
2401 }
2402
2403 auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
2404 return UnaryExpr<LhsT>{ m_lhs };
2405 }
2406 };
2407
2408 void handleExpression( ITransientExpression const& expr );
2409
2410 template<typename T>
2411 void handleExpression( ExprLhs<T> const& expr ) {
2412 handleExpression( expr.makeUnaryExpr() );
2413 }
2414
2415 struct Decomposer {
2416 template<typename T>
2417 auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
2418 return ExprLhs<T const&>{ lhs };
2419 }
2420
2421 auto operator <=( bool value ) -> ExprLhs<bool> {
2422 return ExprLhs<bool>{ value };
2423 }
2424 };
2425
2426} // end namespace Catch
2427
2428#ifdef _MSC_VER
2429#pragma warning(pop)
2430#endif
2431
2432// end catch_decomposer.h
2433// start catch_interfaces_capture.h
2434
2435#include <string>
2436#include <chrono>
2437
2438namespace Catch {
2439
2440 class AssertionResult;
2441 struct AssertionInfo;
2442 struct SectionInfo;
2443 struct SectionEndInfo;
2444 struct MessageInfo;
2445 struct MessageBuilder;
2446 struct Counts;
2447 struct AssertionReaction;
2448 struct SourceLineInfo;
2449
2450 struct ITransientExpression;
2451 struct IGeneratorTracker;
2452
2453#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2454 struct BenchmarkInfo;
2455 template <typename Duration = std::chrono::duration<double, std::nano>>
2456 struct BenchmarkStats;
2457#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2458
2460
2461 virtual ~IResultCapture();
2462
2463 virtual bool sectionStarted( SectionInfo const& sectionInfo,
2464 Counts& assertions ) = 0;
2465 virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
2466 virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
2467
2468 virtual auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
2469
2470#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
2471 virtual void benchmarkPreparing( std::string const& name ) = 0;
2472 virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
2473 virtual void benchmarkEnded( BenchmarkStats<> const& stats ) = 0;
2474 virtual void benchmarkFailed( std::string const& error ) = 0;
2475#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
2476
2477 virtual void pushScopedMessage( MessageInfo const& message ) = 0;
2478 virtual void popScopedMessage( MessageInfo const& message ) = 0;
2479
2480 virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
2481
2482 virtual void handleFatalErrorCondition( StringRef message ) = 0;
2483
2484 virtual void handleExpr
2485 ( AssertionInfo const& info,
2486 ITransientExpression const& expr,
2487 AssertionReaction& reaction ) = 0;
2488 virtual void handleMessage
2489 ( AssertionInfo const& info,
2490 ResultWas::OfType resultType,
2491 StringRef const& message,
2492 AssertionReaction& reaction ) = 0;
2493 virtual void handleUnexpectedExceptionNotThrown
2494 ( AssertionInfo const& info,
2495 AssertionReaction& reaction ) = 0;
2496 virtual void handleUnexpectedInflightException
2497 ( AssertionInfo const& info,
2498 std::string const& message,
2499 AssertionReaction& reaction ) = 0;
2500 virtual void handleIncomplete
2501 ( AssertionInfo const& info ) = 0;
2502 virtual void handleNonExpr
2503 ( AssertionInfo const &info,
2504 ResultWas::OfType resultType,
2505 AssertionReaction &reaction ) = 0;
2506
2507 virtual bool lastAssertionPassed() = 0;
2508 virtual void assertionPassed() = 0;
2509
2510 // Deprecated, do not use:
2511 virtual std::string getCurrentTestName() const = 0;
2512 virtual const AssertionResult* getLastResult() const = 0;
2513 virtual void exceptionEarlyReported() = 0;
2514 };
2515
2516 IResultCapture& getResultCapture();
2517}
2518
2519// end catch_interfaces_capture.h
2520namespace Catch {
2521
2523 struct AssertionResultData;
2524 struct IResultCapture;
2525 class RunContext;
2526
2528 friend class AssertionHandler;
2529 friend struct AssertionStats;
2530 friend class RunContext;
2531
2532 ITransientExpression const* m_transientExpression = nullptr;
2533 bool m_isNegated;
2534 public:
2535 LazyExpression( bool isNegated );
2536 LazyExpression( LazyExpression const& other );
2537 LazyExpression& operator = ( LazyExpression const& ) = delete;
2538
2539 explicit operator bool() const;
2540
2541 friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
2542 };
2543
2545 bool shouldDebugBreak = false;
2546 bool shouldThrow = false;
2547 };
2548
2550 AssertionInfo m_assertionInfo;
2551 AssertionReaction m_reaction;
2552 bool m_completed = false;
2553 IResultCapture& m_resultCapture;
2554
2555 public:
2557 ( StringRef const& macroName,
2558 SourceLineInfo const& lineInfo,
2559 StringRef capturedExpression,
2560 ResultDisposition::Flags resultDisposition );
2562 if ( !m_completed ) {
2563 m_resultCapture.handleIncomplete( m_assertionInfo );
2564 }
2565 }
2566
2567 template<typename T>
2568 void handleExpr( ExprLhs<T> const& expr ) {
2569 handleExpr( expr.makeUnaryExpr() );
2570 }
2571 void handleExpr( ITransientExpression const& expr );
2572
2573 void handleMessage(ResultWas::OfType resultType, StringRef const& message);
2574
2575 void handleExceptionThrownAsExpected();
2576 void handleUnexpectedExceptionNotThrown();
2577 void handleExceptionNotThrownAsExpected();
2578 void handleThrowingCallSkipped();
2579 void handleUnexpectedInflightException();
2580
2581 void complete();
2582 void setCompleted();
2583
2584 // query
2585 auto allowThrows() const -> bool;
2586 };
2587
2588 void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
2589
2590} // namespace Catch
2591
2592// end catch_assertionhandler.h
2593// start catch_message.h
2594
2595#include <string>
2596#include <vector>
2597
2598namespace Catch {
2599
2601 MessageInfo( StringRef const& _macroName,
2602 SourceLineInfo const& _lineInfo,
2603 ResultWas::OfType _type );
2604
2605 StringRef macroName;
2606 std::string message;
2607 SourceLineInfo lineInfo;
2608 ResultWas::OfType type;
2609 unsigned int sequence;
2610
2611 bool operator == ( MessageInfo const& other ) const;
2612 bool operator < ( MessageInfo const& other ) const;
2613 private:
2614 static unsigned int globalCount;
2615 };
2616
2618
2619 template<typename T>
2620 MessageStream& operator << ( T const& value ) {
2621 m_stream << value;
2622 return *this;
2623 }
2624
2625 ReusableStringStream m_stream;
2626 };
2627
2629 MessageBuilder( StringRef const& macroName,
2630 SourceLineInfo const& lineInfo,
2631 ResultWas::OfType type );
2632
2633 template<typename T>
2634 MessageBuilder& operator << ( T const& value ) {
2635 m_stream << value;
2636 return *this;
2637 }
2638
2639 MessageInfo m_info;
2640 };
2641
2643 public:
2644 explicit ScopedMessage( MessageBuilder const& builder );
2645 ScopedMessage( ScopedMessage& duplicate ) = delete;
2648
2649 MessageInfo m_info;
2650 bool m_moved;
2651 };
2652
2653 class Capturer {
2654 std::vector<MessageInfo> m_messages;
2655 IResultCapture& m_resultCapture = getResultCapture();
2656 size_t m_captured = 0;
2657 public:
2658 Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
2659 ~Capturer();
2660
2661 void captureValue( size_t index, std::string const& value );
2662
2663 template<typename T>
2664 void captureValues( size_t index, T const& value ) {
2665 captureValue( index, Catch::Detail::stringify( value ) );
2666 }
2667
2668 template<typename T, typename... Ts>
2669 void captureValues( size_t index, T const& value, Ts const&... values ) {
2670 captureValue( index, Catch::Detail::stringify(value) );
2671 captureValues( index+1, values... );
2672 }
2673 };
2674
2675} // end namespace Catch
2676
2677// end catch_message.h
2678#if !defined(CATCH_CONFIG_DISABLE)
2679
2680#if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
2681 #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
2682#else
2683 #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
2684#endif
2685
2686#if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
2687
2689// Another way to speed-up compilation is to omit local try-catch for REQUIRE*
2690// macros.
2691#define INTERNAL_CATCH_TRY
2692#define INTERNAL_CATCH_CATCH( capturer )
2693
2694#else // CATCH_CONFIG_FAST_COMPILE
2695
2696#define INTERNAL_CATCH_TRY try
2697#define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
2698
2699#endif
2700
2701#define INTERNAL_CATCH_REACT( handler ) handler.complete();
2702
2704#define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
2705 do { \
2706 CATCH_INTERNAL_IGNORE_BUT_WARN(__VA_ARGS__); \
2707 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2708 INTERNAL_CATCH_TRY { \
2709 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2710 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
2711 catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
2712 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
2713 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
2714 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2715 } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) )
2716
2718#define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
2719 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2720 if( Catch::getResultCapture().lastAssertionPassed() )
2721
2723#define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
2724 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2725 if( !Catch::getResultCapture().lastAssertionPassed() )
2726
2728#define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
2729 do { \
2730 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2731 try { \
2732 static_cast<void>(__VA_ARGS__); \
2733 catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
2734 } \
2735 catch( ... ) { \
2736 catchAssertionHandler.handleUnexpectedInflightException(); \
2737 } \
2738 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2739 } while( false )
2740
2742#define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
2743 do { \
2744 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
2745 if( catchAssertionHandler.allowThrows() ) \
2746 try { \
2747 static_cast<void>(__VA_ARGS__); \
2748 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2749 } \
2750 catch( ... ) { \
2751 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2752 } \
2753 else \
2754 catchAssertionHandler.handleThrowingCallSkipped(); \
2755 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2756 } while( false )
2757
2759#define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
2760 do { \
2761 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
2762 if( catchAssertionHandler.allowThrows() ) \
2763 try { \
2764 static_cast<void>(expr); \
2765 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2766 } \
2767 catch( exceptionType const& ) { \
2768 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2769 } \
2770 catch( ... ) { \
2771 catchAssertionHandler.handleUnexpectedInflightException(); \
2772 } \
2773 else \
2774 catchAssertionHandler.handleThrowingCallSkipped(); \
2775 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2776 } while( false )
2777
2779#define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
2780 do { \
2781 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
2782 catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
2783 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2784 } while( false )
2785
2787#define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
2788 auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
2789 varName.captureValues( 0, __VA_ARGS__ )
2790
2792#define INTERNAL_CATCH_INFO( macroName, log ) \
2793 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
2794
2796#define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
2797 Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
2798
2800// Although this is matcher-based, it can be used with just a string
2801#define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
2802 do { \
2803 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
2804 if( catchAssertionHandler.allowThrows() ) \
2805 try { \
2806 static_cast<void>(__VA_ARGS__); \
2807 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2808 } \
2809 catch( ... ) { \
2810 Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
2811 } \
2812 else \
2813 catchAssertionHandler.handleThrowingCallSkipped(); \
2814 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2815 } while( false )
2816
2817#endif // CATCH_CONFIG_DISABLE
2818
2819// end catch_capture.hpp
2820// start catch_section.h
2821
2822// start catch_section_info.h
2823
2824// start catch_totals.h
2825
2826#include <cstddef>
2827
2828namespace Catch {
2829
2830 struct Counts {
2831 Counts operator - ( Counts const& other ) const;
2832 Counts& operator += ( Counts const& other );
2833
2834 std::size_t total() const;
2835 bool allPassed() const;
2836 bool allOk() const;
2837
2838 std::size_t passed = 0;
2839 std::size_t failed = 0;
2840 std::size_t failedButOk = 0;
2841 };
2842
2843 struct Totals {
2844
2845 Totals operator - ( Totals const& other ) const;
2846 Totals& operator += ( Totals const& other );
2847
2848 Totals delta( Totals const& prevTotals ) const;
2849
2850 int error = 0;
2851 Counts assertions;
2852 Counts testCases;
2853 };
2854}
2855
2856// end catch_totals.h
2857#include <string>
2858
2859namespace Catch {
2860
2863 ( SourceLineInfo const& _lineInfo,
2864 std::string const& _name );
2865
2866 // Deprecated
2868 ( SourceLineInfo const& _lineInfo,
2869 std::string const& _name,
2870 std::string const& ) : SectionInfo( _lineInfo, _name ) {}
2871
2872 std::string name;
2873 std::string description; // !Deprecated: this will always be empty
2874 SourceLineInfo lineInfo;
2875 };
2876
2878 SectionInfo sectionInfo;
2879 Counts prevAssertions;
2880 double durationInSeconds;
2881 };
2882
2883} // end namespace Catch
2884
2885// end catch_section_info.h
2886// start catch_timer.h
2887
2888#include <cstdint>
2889
2890namespace Catch {
2891
2892 auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
2893 auto getEstimatedClockResolution() -> uint64_t;
2894
2895 class Timer {
2896 uint64_t m_nanoseconds = 0;
2897 public:
2898 void start();
2899 auto getElapsedNanoseconds() const -> uint64_t;
2900 auto getElapsedMicroseconds() const -> uint64_t;
2901 auto getElapsedMilliseconds() const -> unsigned int;
2902 auto getElapsedSeconds() const -> double;
2903 };
2904
2905} // namespace Catch
2906
2907// end catch_timer.h
2908#include <string>
2909
2910namespace Catch {
2911
2913 public:
2914 Section( SectionInfo const& info );
2915 ~Section();
2916
2917 // This indicates whether the section should be executed or not
2918 explicit operator bool() const;
2919
2920 private:
2921 SectionInfo m_info;
2922
2923 std::string m_name;
2924 Counts m_assertions;
2925 bool m_sectionIncluded;
2926 Timer m_timer;
2927 };
2928
2929} // end namespace Catch
2930
2931#define INTERNAL_CATCH_SECTION( ... ) \
2932 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2933 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2934 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
2935 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
2936
2937#define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
2938 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
2939 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2940 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
2941 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
2942
2943// end catch_section.h
2944// start catch_interfaces_exception.h
2945
2946// start catch_interfaces_registry_hub.h
2947
2948#include <string>
2949#include <memory>
2950
2951namespace Catch {
2952
2953 class TestCase;
2954 struct ITestCaseRegistry;
2955 struct IExceptionTranslatorRegistry;
2956 struct IExceptionTranslator;
2957 struct IReporterRegistry;
2958 struct IReporterFactory;
2959 struct ITagAliasRegistry;
2960 struct IMutableEnumValuesRegistry;
2961
2962 class StartupExceptionRegistry;
2963
2964 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
2965
2967 virtual ~IRegistryHub();
2968
2969 virtual IReporterRegistry const& getReporterRegistry() const = 0;
2970 virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
2971 virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
2972 virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
2973
2974 virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
2975 };
2976
2978 virtual ~IMutableRegistryHub();
2979 virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
2980 virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
2981 virtual void registerTest( TestCase const& testInfo ) = 0;
2982 virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
2983 virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
2984 virtual void registerStartupException() noexcept = 0;
2985 virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
2986 };
2987
2988 IRegistryHub const& getRegistryHub();
2989 IMutableRegistryHub& getMutableRegistryHub();
2990 void cleanUp();
2991 std::string translateActiveException();
2992
2993}
2994
2995// end catch_interfaces_registry_hub.h
2996#if defined(CATCH_CONFIG_DISABLE)
2997 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
2998 static std::string translatorName( signature )
2999#endif
3000
3001#include <exception>
3002#include <string>
3003#include <vector>
3004
3005namespace Catch {
3006 using exceptionTranslateFunction = std::string(*)();
3007
3008 struct IExceptionTranslator;
3009 using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
3010
3012 virtual ~IExceptionTranslator();
3013 virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
3014 };
3015
3018
3019 virtual std::string translateActiveException() const = 0;
3020 };
3021
3023 template<typename T>
3024 class ExceptionTranslator : public IExceptionTranslator {
3025 public:
3026
3027 ExceptionTranslator( std::string(*translateFunction)( T& ) )
3028 : m_translateFunction( translateFunction )
3029 {}
3030
3031 std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
3032#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3033 return "";
3034#else
3035 try {
3036 if( it == itEnd )
3037 std::rethrow_exception(std::current_exception());
3038 else
3039 return (*it)->translate( it+1, itEnd );
3040 }
3041 catch( T& ex ) {
3042 return m_translateFunction( ex );
3043 }
3044#endif
3045 }
3046
3047 protected:
3048 std::string(*m_translateFunction)( T& );
3049 };
3050
3051 public:
3052 template<typename T>
3053 ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
3054 getMutableRegistryHub().registerTranslator
3055 ( new ExceptionTranslator<T>( translateFunction ) );
3056 }
3057 };
3058}
3059
3061#define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
3062 static std::string translatorName( signature ); \
3063 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
3064 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
3065 namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
3066 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION \
3067 static std::string translatorName( signature )
3068
3069#define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
3070
3071// end catch_interfaces_exception.h
3072// start catch_approx.h
3073
3074#include <type_traits>
3075
3076namespace Catch {
3077namespace Detail {
3078
3079 class Approx {
3080 private:
3081 bool equalityComparisonImpl(double other) const;
3082 // Validates the new margin (margin >= 0)
3083 // out-of-line to avoid including stdexcept in the header
3084 void setMargin(double margin);
3085 // Validates the new epsilon (0 < epsilon < 1)
3086 // out-of-line to avoid including stdexcept in the header
3087 void setEpsilon(double epsilon);
3088
3089 public:
3090 explicit Approx ( double value );
3091
3092 static Approx custom();
3093
3094 Approx operator-() const;
3095
3096 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3097 Approx operator()( T const& value ) const {
3098 Approx approx( static_cast<double>(value) );
3099 approx.m_epsilon = m_epsilon;
3100 approx.m_margin = m_margin;
3101 approx.m_scale = m_scale;
3102 return approx;
3103 }
3104
3105 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3106 explicit Approx( T const& value ): Approx(static_cast<double>(value))
3107 {}
3108
3109 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3110 friend bool operator == ( const T& lhs, Approx const& rhs ) {
3111 auto lhs_v = static_cast<double>(lhs);
3112 return rhs.equalityComparisonImpl(lhs_v);
3113 }
3114
3115 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3116 friend bool operator == ( Approx const& lhs, const T& rhs ) {
3117 return operator==( rhs, lhs );
3118 }
3119
3120 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3121 friend bool operator != ( T const& lhs, Approx const& rhs ) {
3122 return !operator==( lhs, rhs );
3123 }
3124
3125 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3126 friend bool operator != ( Approx const& lhs, T const& rhs ) {
3127 return !operator==( rhs, lhs );
3128 }
3129
3130 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3131 friend bool operator <= ( T const& lhs, Approx const& rhs ) {
3132 return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
3133 }
3134
3135 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3136 friend bool operator <= ( Approx const& lhs, T const& rhs ) {
3137 return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
3138 }
3139
3140 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3141 friend bool operator >= ( T const& lhs, Approx const& rhs ) {
3142 return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3143 }
3144
3145 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3146 friend bool operator >= ( Approx const& lhs, T const& rhs ) {
3147 return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
3148 }
3149
3150 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3151 Approx& epsilon( T const& newEpsilon ) {
3152 double epsilonAsDouble = static_cast<double>(newEpsilon);
3153 setEpsilon(epsilonAsDouble);
3154 return *this;
3155 }
3156
3157 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3158 Approx& margin( T const& newMargin ) {
3159 double marginAsDouble = static_cast<double>(newMargin);
3160 setMargin(marginAsDouble);
3161 return *this;
3162 }
3163
3164 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3165 Approx& scale( T const& newScale ) {
3166 m_scale = static_cast<double>(newScale);
3167 return *this;
3168 }
3169
3170 std::string toString() const;
3171
3172 private:
3173 double m_epsilon;
3174 double m_margin;
3175 double m_scale;
3176 double m_value;
3177 };
3178} // end namespace Detail
3179
3180namespace literals {
3181 Detail::Approx operator "" _a(long double val);
3182 Detail::Approx operator "" _a(unsigned long long val);
3183} // end namespace literals
3184
3185template<>
3187 static std::string convert(Catch::Detail::Approx const& value);
3188};
3189
3190} // end namespace Catch
3191
3192// end catch_approx.h
3193// start catch_string_manip.h
3194
3195#include <string>
3196#include <iosfwd>
3197#include <vector>
3198
3199namespace Catch {
3200
3201 bool startsWith( std::string const& s, std::string const& prefix );
3202 bool startsWith( std::string const& s, char prefix );
3203 bool endsWith( std::string const& s, std::string const& suffix );
3204 bool endsWith( std::string const& s, char suffix );
3205 bool contains( std::string const& s, std::string const& infix );
3206 void toLowerInPlace( std::string& s );
3207 std::string toLower( std::string const& s );
3209 std::string trim( std::string const& str );
3211 StringRef trim(StringRef ref);
3212
3213 // !!! Be aware, returns refs into original string - make sure original string outlives them
3214 std::vector<StringRef> splitStringRef( StringRef str, char delimiter );
3215 bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
3216
3217 struct pluralise {
3218 pluralise( std::size_t count, std::string const& label );
3219
3220 friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
3221
3222 std::size_t m_count;
3223 std::string m_label;
3224 };
3225}
3226
3227// end catch_string_manip.h
3228#ifndef CATCH_CONFIG_DISABLE_MATCHERS
3229// start catch_capture_matchers.h
3230
3231// start catch_matchers.h
3232
3233#include <string>
3234#include <vector>
3235
3236namespace Catch {
3237namespace Matchers {
3238 namespace Impl {
3239
3240 template<typename ArgT> struct MatchAllOf;
3241 template<typename ArgT> struct MatchAnyOf;
3242 template<typename ArgT> struct MatchNotOf;
3243
3245 public:
3246 MatcherUntypedBase() = default;
3247 MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
3248 MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
3249 std::string toString() const;
3250
3251 protected:
3252 virtual ~MatcherUntypedBase();
3253 virtual std::string describe() const = 0;
3254 mutable std::string m_cachedToString;
3255 };
3256
3257#ifdef __clang__
3258# pragma clang diagnostic push
3259# pragma clang diagnostic ignored "-Wnon-virtual-dtor"
3260#endif
3261
3262 template<typename ObjectT>
3264 virtual bool match( ObjectT const& arg ) const = 0;
3265 };
3266
3267#if defined(__OBJC__)
3268 // Hack to fix Catch GH issue #1661. Could use id for generic Object support.
3269 // use of const for Object pointers is very uncommon and under ARC it causes some kind of signature mismatch that breaks compilation
3270 template<>
3271 struct MatcherMethod<NSString*> {
3272 virtual bool match( NSString* arg ) const = 0;
3273 };
3274#endif
3275
3276#ifdef __clang__
3277# pragma clang diagnostic pop
3278#endif
3279
3280 template<typename T>
3282
3283 MatchAllOf<T> operator && ( MatcherBase const& other ) const;
3284 MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
3285 MatchNotOf<T> operator ! () const;
3286 };
3287
3288 template<typename ArgT>
3289 struct MatchAllOf : MatcherBase<ArgT> {
3290 bool match( ArgT const& arg ) const override {
3291 for( auto matcher : m_matchers ) {
3292 if (!matcher->match(arg))
3293 return false;
3294 }
3295 return true;
3296 }
3297 std::string describe() const override {
3298 std::string description;
3299 description.reserve( 4 + m_matchers.size()*32 );
3300 description += "( ";
3301 bool first = true;
3302 for( auto matcher : m_matchers ) {
3303 if( first )
3304 first = false;
3305 else
3306 description += " and ";
3307 description += matcher->toString();
3308 }
3309 description += " )";
3310 return description;
3311 }
3312
3313 MatchAllOf<ArgT> operator && ( MatcherBase<ArgT> const& other ) {
3314 auto copy(*this);
3315 copy.m_matchers.push_back( &other );
3316 return copy;
3317 }
3318
3319 std::vector<MatcherBase<ArgT> const*> m_matchers;
3320 };
3321 template<typename ArgT>
3322 struct MatchAnyOf : MatcherBase<ArgT> {
3323
3324 bool match( ArgT const& arg ) const override {
3325 for( auto matcher : m_matchers ) {
3326 if (matcher->match(arg))
3327 return true;
3328 }
3329 return false;
3330 }
3331 std::string describe() const override {
3332 std::string description;
3333 description.reserve( 4 + m_matchers.size()*32 );
3334 description += "( ";
3335 bool first = true;
3336 for( auto matcher : m_matchers ) {
3337 if( first )
3338 first = false;
3339 else
3340 description += " or ";
3341 description += matcher->toString();
3342 }
3343 description += " )";
3344 return description;
3345 }
3346
3347 MatchAnyOf<ArgT> operator || ( MatcherBase<ArgT> const& other ) {
3348 auto copy(*this);
3349 copy.m_matchers.push_back( &other );
3350 return copy;
3351 }
3352
3353 std::vector<MatcherBase<ArgT> const*> m_matchers;
3354 };
3355
3356 template<typename ArgT>
3357 struct MatchNotOf : MatcherBase<ArgT> {
3358
3359 MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
3360
3361 bool match( ArgT const& arg ) const override {
3362 return !m_underlyingMatcher.match( arg );
3363 }
3364
3365 std::string describe() const override {
3366 return "not " + m_underlyingMatcher.toString();
3367 }
3368 MatcherBase<ArgT> const& m_underlyingMatcher;
3369 };
3370
3371 template<typename T>
3373 return MatchAllOf<T>() && *this && other;
3374 }
3375 template<typename T>
3376 MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
3377 return MatchAnyOf<T>() || *this || other;
3378 }
3379 template<typename T>
3380 MatchNotOf<T> MatcherBase<T>::operator ! () const {
3381 return MatchNotOf<T>( *this );
3382 }
3383
3384 } // namespace Impl
3385
3386} // namespace Matchers
3387
3388using namespace Matchers;
3389using Matchers::Impl::MatcherBase;
3390
3391} // namespace Catch
3392
3393// end catch_matchers.h
3394// start catch_matchers_exception.hpp
3395
3396namespace Catch {
3397namespace Matchers {
3398namespace Exception {
3399
3400class ExceptionMessageMatcher : public MatcherBase<std::exception> {
3401 std::string m_message;
3402public:
3403
3404 ExceptionMessageMatcher(std::string const& message):
3405 m_message(message)
3406 {}
3407
3408 bool match(std::exception const& ex) const override;
3409
3410 std::string describe() const override;
3411};
3412
3413} // namespace Exception
3414
3415Exception::ExceptionMessageMatcher Message(std::string const& message);
3416
3417} // namespace Matchers
3418} // namespace Catch
3419
3420// end catch_matchers_exception.hpp
3421// start catch_matchers_floating.h
3422
3423namespace Catch {
3424namespace Matchers {
3425
3426 namespace Floating {
3427
3428 enum class FloatingPointKind : uint8_t;
3429
3431 WithinAbsMatcher(double target, double margin);
3432 bool match(double const& matchee) const override;
3433 std::string describe() const override;
3434 private:
3435 double m_target;
3436 double m_margin;
3437 };
3438
3440 WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType);
3441 bool match(double const& matchee) const override;
3442 std::string describe() const override;
3443 private:
3444 double m_target;
3445 uint64_t m_ulps;
3446 FloatingPointKind m_type;
3447 };
3448
3449 // Given IEEE-754 format for floats and doubles, we can assume
3450 // that float -> double promotion is lossless. Given this, we can
3451 // assume that if we do the standard relative comparison of
3452 // |lhs - rhs| <= epsilon * max(fabs(lhs), fabs(rhs)), then we get
3453 // the same result if we do this for floats, as if we do this for
3454 // doubles that were promoted from floats.
3456 WithinRelMatcher(double target, double epsilon);
3457 bool match(double const& matchee) const override;
3458 std::string describe() const override;
3459 private:
3460 double m_target;
3461 double m_epsilon;
3462 };
3463
3464 } // namespace Floating
3465
3466 // The following functions create the actual matcher objects.
3467 // This allows the types to be inferred
3468 Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff);
3469 Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff);
3470 Floating::WithinAbsMatcher WithinAbs(double target, double margin);
3471 Floating::WithinRelMatcher WithinRel(double target, double eps);
3472 // defaults epsilon to 100*numeric_limits<double>::epsilon()
3473 Floating::WithinRelMatcher WithinRel(double target);
3474 Floating::WithinRelMatcher WithinRel(float target, float eps);
3475 // defaults epsilon to 100*numeric_limits<float>::epsilon()
3476 Floating::WithinRelMatcher WithinRel(float target);
3477
3478} // namespace Matchers
3479} // namespace Catch
3480
3481// end catch_matchers_floating.h
3482// start catch_matchers_generic.hpp
3483
3484#include <functional>
3485#include <string>
3486
3487namespace Catch {
3488namespace Matchers {
3489namespace Generic {
3490
3491namespace Detail {
3492 std::string finalizeDescription(const std::string& desc);
3493}
3494
3495template <typename T>
3497 std::function<bool(T const&)> m_predicate;
3498 std::string m_description;
3499public:
3500
3501 PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
3502 :m_predicate(std::move(elem)),
3503 m_description(Detail::finalizeDescription(descr))
3504 {}
3505
3506 bool match( T const& item ) const override {
3507 return m_predicate(item);
3508 }
3509
3510 std::string describe() const override {
3511 return m_description;
3512 }
3513};
3514
3515} // namespace Generic
3516
3517 // The following functions create the actual matcher objects.
3518 // The user has to explicitly specify type to the function, because
3519 // inferring std::function<bool(T const&)> is hard (but possible) and
3520 // requires a lot of TMP.
3521 template<typename T>
3522 Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
3523 return Generic::PredicateMatcher<T>(predicate, description);
3524 }
3525
3526} // namespace Matchers
3527} // namespace Catch
3528
3529// end catch_matchers_generic.hpp
3530// start catch_matchers_string.h
3531
3532#include <string>
3533
3534namespace Catch {
3535namespace Matchers {
3536
3537 namespace StdString {
3538
3540 {
3541 CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
3542 std::string adjustString( std::string const& str ) const;
3543 std::string caseSensitivitySuffix() const;
3544
3545 CaseSensitive::Choice m_caseSensitivity;
3546 std::string m_str;
3547 };
3548
3549 struct StringMatcherBase : MatcherBase<std::string> {
3550 StringMatcherBase( std::string const& operation, CasedString const& comparator );
3551 std::string describe() const override;
3552
3553 CasedString m_comparator;
3554 std::string m_operation;
3555 };
3556
3558 EqualsMatcher( CasedString const& comparator );
3559 bool match( std::string const& source ) const override;
3560 };
3562 ContainsMatcher( CasedString const& comparator );
3563 bool match( std::string const& source ) const override;
3564 };
3566 StartsWithMatcher( CasedString const& comparator );
3567 bool match( std::string const& source ) const override;
3568 };
3570 EndsWithMatcher( CasedString const& comparator );
3571 bool match( std::string const& source ) const override;
3572 };
3573
3574 struct RegexMatcher : MatcherBase<std::string> {
3575 RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
3576 bool match( std::string const& matchee ) const override;
3577 std::string describe() const override;
3578
3579 private:
3580 std::string m_regex;
3581 CaseSensitive::Choice m_caseSensitivity;
3582 };
3583
3584 } // namespace StdString
3585
3586 // The following functions create the actual matcher objects.
3587 // This allows the types to be inferred
3588
3589 StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3590 StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3591 StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3592 StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3593 StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3594
3595} // namespace Matchers
3596} // namespace Catch
3597
3598// end catch_matchers_string.h
3599// start catch_matchers_vector.h
3600
3601#include <algorithm>
3602
3603namespace Catch {
3604namespace Matchers {
3605
3606 namespace Vector {
3607 template<typename T, typename Alloc>
3608 struct ContainsElementMatcher : MatcherBase<std::vector<T, Alloc>> {
3609
3610 ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
3611
3612 bool match(std::vector<T, Alloc> const &v) const override {
3613 for (auto const& el : v) {
3614 if (el == m_comparator) {
3615 return true;
3616 }
3617 }
3618 return false;
3619 }
3620
3621 std::string describe() const override {
3622 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3623 }
3624
3625 T const& m_comparator;
3626 };
3627
3628 template<typename T, typename AllocComp, typename AllocMatch>
3629 struct ContainsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3630
3631 ContainsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
3632
3633 bool match(std::vector<T, AllocMatch> const &v) const override {
3634 // !TBD: see note in EqualsMatcher
3635 if (m_comparator.size() > v.size())
3636 return false;
3637 for (auto const& comparator : m_comparator) {
3638 auto present = false;
3639 for (const auto& el : v) {
3640 if (el == comparator) {
3641 present = true;
3642 break;
3643 }
3644 }
3645 if (!present) {
3646 return false;
3647 }
3648 }
3649 return true;
3650 }
3651 std::string describe() const override {
3652 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3653 }
3654
3655 std::vector<T, AllocComp> const& m_comparator;
3656 };
3657
3658 template<typename T, typename AllocComp, typename AllocMatch>
3659 struct EqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3660
3661 EqualsMatcher(std::vector<T, AllocComp> const &comparator) : m_comparator( comparator ) {}
3662
3663 bool match(std::vector<T, AllocMatch> const &v) const override {
3664 // !TBD: This currently works if all elements can be compared using !=
3665 // - a more general approach would be via a compare template that defaults
3666 // to using !=. but could be specialised for, e.g. std::vector<T, Alloc> etc
3667 // - then just call that directly
3668 if (m_comparator.size() != v.size())
3669 return false;
3670 for (std::size_t i = 0; i < v.size(); ++i)
3671 if (m_comparator[i] != v[i])
3672 return false;
3673 return true;
3674 }
3675 std::string describe() const override {
3676 return "Equals: " + ::Catch::Detail::stringify( m_comparator );
3677 }
3678 std::vector<T, AllocComp> const& m_comparator;
3679 };
3680
3681 template<typename T, typename AllocComp, typename AllocMatch>
3682 struct ApproxMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3683
3684 ApproxMatcher(std::vector<T, AllocComp> const& comparator) : m_comparator( comparator ) {}
3685
3686 bool match(std::vector<T, AllocMatch> const &v) const override {
3687 if (m_comparator.size() != v.size())
3688 return false;
3689 for (std::size_t i = 0; i < v.size(); ++i)
3690 if (m_comparator[i] != approx(v[i]))
3691 return false;
3692 return true;
3693 }
3694 std::string describe() const override {
3695 return "is approx: " + ::Catch::Detail::stringify( m_comparator );
3696 }
3697 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3698 ApproxMatcher& epsilon( T const& newEpsilon ) {
3699 approx.epsilon(newEpsilon);
3700 return *this;
3701 }
3702 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3703 ApproxMatcher& margin( T const& newMargin ) {
3704 approx.margin(newMargin);
3705 return *this;
3706 }
3707 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3708 ApproxMatcher& scale( T const& newScale ) {
3709 approx.scale(newScale);
3710 return *this;
3711 }
3712
3713 std::vector<T, AllocComp> const& m_comparator;
3714 mutable Catch::Detail::Approx approx = Catch::Detail::Approx::custom();
3715 };
3716
3717 template<typename T, typename AllocComp, typename AllocMatch>
3718 struct UnorderedEqualsMatcher : MatcherBase<std::vector<T, AllocMatch>> {
3719 UnorderedEqualsMatcher(std::vector<T, AllocComp> const& target) : m_target(target) {}
3720 bool match(std::vector<T, AllocMatch> const& vec) const override {
3721 if (m_target.size() != vec.size()) {
3722 return false;
3723 }
3724 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
3725 }
3726
3727 std::string describe() const override {
3728 return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
3729 }
3730 private:
3731 std::vector<T, AllocComp> const& m_target;
3732 };
3733
3734 } // namespace Vector
3735
3736 // The following functions create the actual matcher objects.
3737 // This allows the types to be inferred
3738
3739 template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
3740 Vector::ContainsMatcher<T, AllocComp, AllocMatch> Contains( std::vector<T, AllocComp> const& comparator ) {
3742 }
3743
3744 template<typename T, typename Alloc = std::allocator<T>>
3745 Vector::ContainsElementMatcher<T, Alloc> VectorContains( T const& comparator ) {
3746 return Vector::ContainsElementMatcher<T, Alloc>( comparator );
3747 }
3748
3749 template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
3750 Vector::EqualsMatcher<T, AllocComp, AllocMatch> Equals( std::vector<T, AllocComp> const& comparator ) {
3751 return Vector::EqualsMatcher<T, AllocComp, AllocMatch>( comparator );
3752 }
3753
3754 template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
3755 Vector::ApproxMatcher<T, AllocComp, AllocMatch> Approx( std::vector<T, AllocComp> const& comparator ) {
3756 return Vector::ApproxMatcher<T, AllocComp, AllocMatch>( comparator );
3757 }
3758
3759 template<typename T, typename AllocComp = std::allocator<T>, typename AllocMatch = AllocComp>
3760 Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch> UnorderedEquals(std::vector<T, AllocComp> const& target) {
3761 return Vector::UnorderedEqualsMatcher<T, AllocComp, AllocMatch>( target );
3762 }
3763
3764} // namespace Matchers
3765} // namespace Catch
3766
3767// end catch_matchers_vector.h
3768namespace Catch {
3769
3770 template<typename ArgT, typename MatcherT>
3772 ArgT const& m_arg;
3773 MatcherT m_matcher;
3774 StringRef m_matcherString;
3775 public:
3776 MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
3777 : ITransientExpression{ true, matcher.match( arg ) },
3778 m_arg( arg ),
3779 m_matcher( matcher ),
3780 m_matcherString( matcherString )
3781 {}
3782
3783 void streamReconstructedExpression( std::ostream &os ) const override {
3784 auto matcherAsString = m_matcher.toString();
3785 os << Catch::Detail::stringify( m_arg ) << ' ';
3786 if( matcherAsString == Detail::unprintableString )
3787 os << m_matcherString;
3788 else
3789 os << matcherAsString;
3790 }
3791 };
3792
3794
3795 void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
3796
3797 template<typename ArgT, typename MatcherT>
3798 auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
3799 return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
3800 }
3801
3802} // namespace Catch
3803
3805#define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
3806 do { \
3807 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3808 INTERNAL_CATCH_TRY { \
3809 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
3810 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
3811 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3812 } while( false )
3813
3815#define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
3816 do { \
3817 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3818 if( catchAssertionHandler.allowThrows() ) \
3819 try { \
3820 static_cast<void>(__VA_ARGS__ ); \
3821 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3822 } \
3823 catch( exceptionType const& ex ) { \
3824 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
3825 } \
3826 catch( ... ) { \
3827 catchAssertionHandler.handleUnexpectedInflightException(); \
3828 } \
3829 else \
3830 catchAssertionHandler.handleThrowingCallSkipped(); \
3831 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3832 } while( false )
3833
3834// end catch_capture_matchers.h
3835#endif
3836// start catch_generators.hpp
3837
3838// start catch_interfaces_generatortracker.h
3839
3840
3841#include <memory>
3842
3843namespace Catch {
3844
3845 namespace Generators {
3847 public:
3848 GeneratorUntypedBase() = default;
3849 virtual ~GeneratorUntypedBase();
3850 // Attempts to move the generator to the next element
3851 //
3852 // Returns true iff the move succeeded (and a valid element
3853 // can be retrieved).
3854 virtual bool next() = 0;
3855 };
3856 using GeneratorBasePtr = std::unique_ptr<GeneratorUntypedBase>;
3857
3858 } // namespace Generators
3859
3861 virtual ~IGeneratorTracker();
3862 virtual auto hasGenerator() const -> bool = 0;
3863 virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
3864 virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
3865 };
3866
3867} // namespace Catch
3868
3869// end catch_interfaces_generatortracker.h
3870// start catch_enforce.h
3871
3872#include <exception>
3873
3874namespace Catch {
3875#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3876 template <typename Ex>
3877 [[noreturn]]
3878 void throw_exception(Ex const& e) {
3879 throw e;
3880 }
3881#else // ^^ Exceptions are enabled // Exceptions are disabled vv
3882 [[noreturn]]
3883 void throw_exception(std::exception const& e);
3884#endif
3885
3886 [[noreturn]]
3887 void throw_logic_error(std::string const& msg);
3888 [[noreturn]]
3889 void throw_domain_error(std::string const& msg);
3890 [[noreturn]]
3891 void throw_runtime_error(std::string const& msg);
3892
3893} // namespace Catch;
3894
3895#define CATCH_MAKE_MSG(...) \
3896 (Catch::ReusableStringStream() << __VA_ARGS__).str()
3897
3898#define CATCH_INTERNAL_ERROR(...) \
3899 Catch::throw_logic_error(CATCH_MAKE_MSG( CATCH_INTERNAL_LINEINFO << ": Internal Catch2 error: " << __VA_ARGS__))
3900
3901#define CATCH_ERROR(...) \
3902 Catch::throw_domain_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
3903
3904#define CATCH_RUNTIME_ERROR(...) \
3905 Catch::throw_runtime_error(CATCH_MAKE_MSG( __VA_ARGS__ ))
3906
3907#define CATCH_ENFORCE( condition, ... ) \
3908 do{ if( !(condition) ) CATCH_ERROR( __VA_ARGS__ ); } while(false)
3909
3910// end catch_enforce.h
3911#include <memory>
3912#include <vector>
3913#include <cassert>
3914
3915#include <utility>
3916#include <exception>
3917
3918namespace Catch {
3919
3920class GeneratorException : public std::exception {
3921 const char* const m_msg = "";
3922
3923public:
3924 GeneratorException(const char* msg):
3925 m_msg(msg)
3926 {}
3927
3928 const char* what() const noexcept override final;
3929};
3930
3931namespace Generators {
3932
3933 // !TBD move this into its own location?
3934 namespace pf{
3935 template<typename T, typename... Args>
3936 std::unique_ptr<T> make_unique( Args&&... args ) {
3937 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
3938 }
3939 }
3940
3941 template<typename T>
3943 virtual ~IGenerator() = default;
3944
3945 // Returns the current element of the generator
3946 //
3947 // \Precondition The generator is either freshly constructed,
3948 // or the last call to `next()` returned true
3949 virtual T const& get() const = 0;
3950 using type = T;
3951 };
3952
3953 template<typename T>
3954 class SingleValueGenerator final : public IGenerator<T> {
3955 T m_value;
3956 public:
3957 SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
3958
3959 T const& get() const override {
3960 return m_value;
3961 }
3962 bool next() override {
3963 return false;
3964 }
3965 };
3966
3967 template<typename T>
3968 class FixedValuesGenerator final : public IGenerator<T> {
3969 static_assert(!std::is_same<T, bool>::value,
3970 "FixedValuesGenerator does not support bools because of std::vector<bool>"
3971 "specialization, use SingleValue Generator instead.");
3972 std::vector<T> m_values;
3973 size_t m_idx = 0;
3974 public:
3975 FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
3976
3977 T const& get() const override {
3978 return m_values[m_idx];
3979 }
3980 bool next() override {
3981 ++m_idx;
3982 return m_idx < m_values.size();
3983 }
3984 };
3985
3986 template <typename T>
3987 class GeneratorWrapper final {
3988 std::unique_ptr<IGenerator<T>> m_generator;
3989 public:
3990 GeneratorWrapper(std::unique_ptr<IGenerator<T>> generator):
3991 m_generator(std::move(generator))
3992 {}
3993 T const& get() const {
3994 return m_generator->get();
3995 }
3996 bool next() {
3997 return m_generator->next();
3998 }
3999 };
4000
4001 template <typename T>
4002 GeneratorWrapper<T> value(T&& value) {
4003 return GeneratorWrapper<T>(pf::make_unique<SingleValueGenerator<T>>(std::forward<T>(value)));
4004 }
4005 template <typename T>
4006 GeneratorWrapper<T> values(std::initializer_list<T> values) {
4007 return GeneratorWrapper<T>(pf::make_unique<FixedValuesGenerator<T>>(values));
4008 }
4009
4010 template<typename T>
4011 class Generators : public IGenerator<T> {
4012 std::vector<GeneratorWrapper<T>> m_generators;
4013 size_t m_current = 0;
4014
4015 void populate(GeneratorWrapper<T>&& generator) {
4016 m_generators.emplace_back(std::move(generator));
4017 }
4018 void populate(T&& val) {
4019 m_generators.emplace_back(value(std::forward<T>(val)));
4020 }
4021 template<typename U>
4022 void populate(U&& val) {
4023 populate(T(std::forward<U>(val)));
4024 }
4025 template<typename U, typename... Gs>
4026 void populate(U&& valueOrGenerator, Gs &&... moreGenerators) {
4027 populate(std::forward<U>(valueOrGenerator));
4028 populate(std::forward<Gs>(moreGenerators)...);
4029 }
4030
4031 public:
4032 template <typename... Gs>
4033 Generators(Gs &&... moreGenerators) {
4034 m_generators.reserve(sizeof...(Gs));
4035 populate(std::forward<Gs>(moreGenerators)...);
4036 }
4037
4038 T const& get() const override {
4039 return m_generators[m_current].get();
4040 }
4041
4042 bool next() override {
4043 if (m_current >= m_generators.size()) {
4044 return false;
4045 }
4046 const bool current_status = m_generators[m_current].next();
4047 if (!current_status) {
4048 ++m_current;
4049 }
4050 return m_current < m_generators.size();
4051 }
4052 };
4053
4054 template<typename... Ts>
4055 GeneratorWrapper<std::tuple<Ts...>> table( std::initializer_list<std::tuple<typename std::decay<Ts>::type...>> tuples ) {
4056 return values<std::tuple<Ts...>>( tuples );
4057 }
4058
4059 // Tag type to signal that a generator sequence should convert arguments to a specific type
4060 template <typename T>
4061 struct as {};
4062
4063 template<typename T, typename... Gs>
4064 auto makeGenerators( GeneratorWrapper<T>&& generator, Gs &&... moreGenerators ) -> Generators<T> {
4065 return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
4066 }
4067 template<typename T>
4068 auto makeGenerators( GeneratorWrapper<T>&& generator ) -> Generators<T> {
4069 return Generators<T>(std::move(generator));
4070 }
4071 template<typename T, typename... Gs>
4072 auto makeGenerators( T&& val, Gs &&... moreGenerators ) -> Generators<T> {
4073 return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
4074 }
4075 template<typename T, typename U, typename... Gs>
4076 auto makeGenerators( as<T>, U&& val, Gs &&... moreGenerators ) -> Generators<T> {
4077 return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
4078 }
4079
4080 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
4081
4082 template<typename L>
4083 // Note: The type after -> is weird, because VS2015 cannot parse
4084 // the expression used in the typedef inside, when it is in
4085 // return type. Yeah.
4086 auto generate( StringRef generatorName, SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
4087 using UnderlyingType = typename decltype(generatorExpression())::type;
4088
4089 IGeneratorTracker& tracker = acquireGeneratorTracker( generatorName, lineInfo );
4090 if (!tracker.hasGenerator()) {
4091 tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
4092 }
4093
4094 auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
4095 return generator.get();
4096 }
4097
4098} // namespace Generators
4099} // namespace Catch
4100
4101#define GENERATE( ... ) \
4102 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4103 CATCH_INTERNAL_LINEINFO, \
4104 [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4105#define GENERATE_COPY( ... ) \
4106 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4107 CATCH_INTERNAL_LINEINFO, \
4108 [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4109#define GENERATE_REF( ... ) \
4110 Catch::Generators::generate( INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_UNIQUE_NAME(generator)), \
4111 CATCH_INTERNAL_LINEINFO, \
4112 [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } ) //NOLINT(google-build-using-namespace)
4113
4114// end catch_generators.hpp
4115// start catch_generators_generic.hpp
4116
4117namespace Catch {
4118namespace Generators {
4119
4120 template <typename T>
4121 class TakeGenerator : public IGenerator<T> {
4122 GeneratorWrapper<T> m_generator;
4123 size_t m_returned = 0;
4124 size_t m_target;
4125 public:
4126 TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
4127 m_generator(std::move(generator)),
4128 m_target(target)
4129 {
4130 assert(target != 0 && "Empty generators are not allowed");
4131 }
4132 T const& get() const override {
4133 return m_generator.get();
4134 }
4135 bool next() override {
4136 ++m_returned;
4137 if (m_returned >= m_target) {
4138 return false;
4139 }
4140
4141 const auto success = m_generator.next();
4142 // If the underlying generator does not contain enough values
4143 // then we cut short as well
4144 if (!success) {
4145 m_returned = m_target;
4146 }
4147 return success;
4148 }
4149 };
4150
4151 template <typename T>
4152 GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
4153 return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
4154 }
4155
4156 template <typename T, typename Predicate>
4157 class FilterGenerator : public IGenerator<T> {
4158 GeneratorWrapper<T> m_generator;
4159 Predicate m_predicate;
4160 public:
4161 template <typename P = Predicate>
4162 FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
4163 m_generator(std::move(generator)),
4164 m_predicate(std::forward<P>(pred))
4165 {
4166 if (!m_predicate(m_generator.get())) {
4167 // It might happen that there are no values that pass the
4168 // filter. In that case we throw an exception.
4169 auto has_initial_value = nextImpl();
4170 if (!has_initial_value) {
4171 Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
4172 }
4173 }
4174 }
4175
4176 T const& get() const override {
4177 return m_generator.get();
4178 }
4179
4180 bool next() override {
4181 return nextImpl();
4182 }
4183
4184 private:
4185 bool nextImpl() {
4186 bool success = m_generator.next();
4187 if (!success) {
4188 return false;
4189 }
4190 while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
4191 return success;
4192 }
4193 };
4194
4195 template <typename T, typename Predicate>
4196 GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
4197 return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
4198 }
4199
4200 template <typename T>
4201 class RepeatGenerator : public IGenerator<T> {
4202 static_assert(!std::is_same<T, bool>::value,
4203 "RepeatGenerator currently does not support bools"
4204 "because of std::vector<bool> specialization");
4205 GeneratorWrapper<T> m_generator;
4206 mutable std::vector<T> m_returned;
4207 size_t m_target_repeats;
4208 size_t m_current_repeat = 0;
4209 size_t m_repeat_index = 0;
4210 public:
4211 RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
4212 m_generator(std::move(generator)),
4213 m_target_repeats(repeats)
4214 {
4215 assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
4216 }
4217
4218 T const& get() const override {
4219 if (m_current_repeat == 0) {
4220 m_returned.push_back(m_generator.get());
4221 return m_returned.back();
4222 }
4223 return m_returned[m_repeat_index];
4224 }
4225
4226 bool next() override {
4227 // There are 2 basic cases:
4228 // 1) We are still reading the generator
4229 // 2) We are reading our own cache
4230
4231 // In the first case, we need to poke the underlying generator.
4232 // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
4233 if (m_current_repeat == 0) {
4234 const auto success = m_generator.next();
4235 if (!success) {
4236 ++m_current_repeat;
4237 }
4238 return m_current_repeat < m_target_repeats;
4239 }
4240
4241 // In the second case, we need to move indices forward and check that we haven't run up against the end
4242 ++m_repeat_index;
4243 if (m_repeat_index == m_returned.size()) {
4244 m_repeat_index = 0;
4245 ++m_current_repeat;
4246 }
4247 return m_current_repeat < m_target_repeats;
4248 }
4249 };
4250
4251 template <typename T>
4252 GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
4253 return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
4254 }
4255
4256 template <typename T, typename U, typename Func>
4257 class MapGenerator : public IGenerator<T> {
4258 // TBD: provide static assert for mapping function, for friendly error message
4259 GeneratorWrapper<U> m_generator;
4260 Func m_function;
4261 // To avoid returning dangling reference, we have to save the values
4262 T m_cache;
4263 public:
4264 template <typename F2 = Func>
4265 MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
4266 m_generator(std::move(generator)),
4267 m_function(std::forward<F2>(function)),
4268 m_cache(m_function(m_generator.get()))
4269 {}
4270
4271 T const& get() const override {
4272 return m_cache;
4273 }
4274 bool next() override {
4275 const auto success = m_generator.next();
4276 if (success) {
4277 m_cache = m_function(m_generator.get());
4278 }
4279 return success;
4280 }
4281 };
4282
4283 template <typename Func, typename U, typename T = FunctionReturnType<Func, U>>
4284 GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4285 return GeneratorWrapper<T>(
4286 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
4287 );
4288 }
4289
4290 template <typename T, typename U, typename Func>
4291 GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4292 return GeneratorWrapper<T>(
4293 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
4294 );
4295 }
4296
4297 template <typename T>
4298 class ChunkGenerator final : public IGenerator<std::vector<T>> {
4299 std::vector<T> m_chunk;
4300 size_t m_chunk_size;
4301 GeneratorWrapper<T> m_generator;
4302 bool m_used_up = false;
4303 public:
4304 ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
4305 m_chunk_size(size), m_generator(std::move(generator))
4306 {
4307 m_chunk.reserve(m_chunk_size);
4308 if (m_chunk_size != 0) {
4309 m_chunk.push_back(m_generator.get());
4310 for (size_t i = 1; i < m_chunk_size; ++i) {
4311 if (!m_generator.next()) {
4312 Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
4313 }
4314 m_chunk.push_back(m_generator.get());
4315 }
4316 }
4317 }
4318 std::vector<T> const& get() const override {
4319 return m_chunk;
4320 }
4321 bool next() override {
4322 m_chunk.clear();
4323 for (size_t idx = 0; idx < m_chunk_size; ++idx) {
4324 if (!m_generator.next()) {
4325 return false;
4326 }
4327 m_chunk.push_back(m_generator.get());
4328 }
4329 return true;
4330 }
4331 };
4332
4333 template <typename T>
4334 GeneratorWrapper<std::vector<T>> chunk(size_t size, GeneratorWrapper<T>&& generator) {
4336 pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
4337 );
4338 }
4339
4340} // namespace Generators
4341} // namespace Catch
4342
4343// end catch_generators_generic.hpp
4344// start catch_generators_specific.hpp
4345
4346// start catch_context.h
4347
4348#include <memory>
4349
4350namespace Catch {
4351
4352 struct IResultCapture;
4353 struct IRunner;
4354 struct IConfig;
4355 struct IMutableContext;
4356
4357 using IConfigPtr = std::shared_ptr<IConfig const>;
4358
4360 {
4361 virtual ~IContext();
4362
4363 virtual IResultCapture* getResultCapture() = 0;
4364 virtual IRunner* getRunner() = 0;
4365 virtual IConfigPtr const& getConfig() const = 0;
4366 };
4367
4369 {
4370 virtual ~IMutableContext();
4371 virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
4372 virtual void setRunner( IRunner* runner ) = 0;
4373 virtual void setConfig( IConfigPtr const& config ) = 0;
4374
4375 private:
4376 static IMutableContext *currentContext;
4377 friend IMutableContext& getCurrentMutableContext();
4378 friend void cleanUpContext();
4379 static void createContext();
4380 };
4381
4382 inline IMutableContext& getCurrentMutableContext()
4383 {
4384 if( !IMutableContext::currentContext )
4385 IMutableContext::createContext();
4386 // NOLINTNEXTLINE(clang-analyzer-core.uninitialized.UndefReturn)
4387 return *IMutableContext::currentContext;
4388 }
4389
4390 inline IContext& getCurrentContext()
4391 {
4392 return getCurrentMutableContext();
4393 }
4394
4395 void cleanUpContext();
4396
4397 class SimplePcg32;
4398 SimplePcg32& rng();
4399}
4400
4401// end catch_context.h
4402// start catch_interfaces_config.h
4403
4404// start catch_option.hpp
4405
4406namespace Catch {
4407
4408 // An optional type
4409 template<typename T>
4410 class Option {
4411 public:
4412 Option() : nullableValue( nullptr ) {}
4413 Option( T const& _value )
4414 : nullableValue( new( storage ) T( _value ) )
4415 {}
4416 Option( Option const& _other )
4417 : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
4418 {}
4419
4420 ~Option() {
4421 reset();
4422 }
4423
4424 Option& operator= ( Option const& _other ) {
4425 if( &_other != this ) {
4426 reset();
4427 if( _other )
4428 nullableValue = new( storage ) T( *_other );
4429 }
4430 return *this;
4431 }
4432 Option& operator = ( T const& _value ) {
4433 reset();
4434 nullableValue = new( storage ) T( _value );
4435 return *this;
4436 }
4437
4438 void reset() {
4439 if( nullableValue )
4440 nullableValue->~T();
4441 nullableValue = nullptr;
4442 }
4443
4444 T& operator*() { return *nullableValue; }
4445 T const& operator*() const { return *nullableValue; }
4446 T* operator->() { return nullableValue; }
4447 const T* operator->() const { return nullableValue; }
4448
4449 T valueOr( T const& defaultValue ) const {
4450 return nullableValue ? *nullableValue : defaultValue;
4451 }
4452
4453 bool some() const { return nullableValue != nullptr; }
4454 bool none() const { return nullableValue == nullptr; }
4455
4456 bool operator !() const { return nullableValue == nullptr; }
4457 explicit operator bool() const {
4458 return some();
4459 }
4460
4461 private:
4462 T *nullableValue;
4463 alignas(alignof(T)) char storage[sizeof(T)];
4464 };
4465
4466} // end namespace Catch
4467
4468// end catch_option.hpp
4469#include <chrono>
4470#include <iosfwd>
4471#include <string>
4472#include <vector>
4473#include <memory>
4474
4475namespace Catch {
4476
4477 enum class Verbosity {
4478 Quiet = 0,
4479 Normal,
4480 High
4481 };
4482
4483 struct WarnAbout { enum What {
4484 Nothing = 0x00,
4485 NoAssertions = 0x01,
4486 NoTests = 0x02
4487 }; };
4488
4489 struct ShowDurations { enum OrNot {
4490 DefaultForReporter,
4491 Always,
4492 Never
4493 }; };
4494 struct RunTests { enum InWhatOrder {
4495 InDeclarationOrder,
4496 InLexicographicalOrder,
4497 InRandomOrder
4498 }; };
4499 struct UseColour { enum YesOrNo {
4500 Auto,
4501 Yes,
4502 No
4503 }; };
4504 struct WaitForKeypress { enum When {
4505 Never,
4506 BeforeStart = 1,
4507 BeforeExit = 2,
4508 BeforeStartAndExit = BeforeStart | BeforeExit
4509 }; };
4510
4511 class TestSpec;
4512
4514
4515 virtual ~IConfig();
4516
4517 virtual bool allowThrows() const = 0;
4518 virtual std::ostream& stream() const = 0;
4519 virtual std::string name() const = 0;
4520 virtual bool includeSuccessfulResults() const = 0;
4521 virtual bool shouldDebugBreak() const = 0;
4522 virtual bool warnAboutMissingAssertions() const = 0;
4523 virtual bool warnAboutNoTests() const = 0;
4524 virtual int abortAfter() const = 0;
4525 virtual bool showInvisibles() const = 0;
4526 virtual ShowDurations::OrNot showDurations() const = 0;
4527 virtual double minDuration() const = 0;
4528 virtual TestSpec const& testSpec() const = 0;
4529 virtual bool hasTestFilters() const = 0;
4530 virtual std::vector<std::string> const& getTestsOrTags() const = 0;
4531 virtual RunTests::InWhatOrder runOrder() const = 0;
4532 virtual unsigned int rngSeed() const = 0;
4533 virtual UseColour::YesOrNo useColour() const = 0;
4534 virtual std::vector<std::string> const& getSectionsToRun() const = 0;
4535 virtual Verbosity verbosity() const = 0;
4536
4537 virtual bool benchmarkNoAnalysis() const = 0;
4538 virtual int benchmarkSamples() const = 0;
4539 virtual double benchmarkConfidenceInterval() const = 0;
4540 virtual unsigned int benchmarkResamples() const = 0;
4541 virtual std::chrono::milliseconds benchmarkWarmupTime() const = 0;
4542 };
4543
4544 using IConfigPtr = std::shared_ptr<IConfig const>;
4545}
4546
4547// end catch_interfaces_config.h
4548// start catch_random_number_generator.h
4549
4550#include <cstdint>
4551
4552namespace Catch {
4553
4554 // This is a simple implementation of C++11 Uniform Random Number
4555 // Generator. It does not provide all operators, because Catch2
4556 // does not use it, but it should behave as expected inside stdlib's
4557 // distributions.
4558 // The implementation is based on the PCG family (http://pcg-random.org)
4560 using state_type = std::uint64_t;
4561 public:
4562 using result_type = std::uint32_t;
4563 static constexpr result_type (min)() {
4564 return 0;
4565 }
4566 static constexpr result_type (max)() {
4567 return static_cast<result_type>(-1);
4568 }
4569
4570 // Provide some default initial state for the default constructor
4571 SimplePcg32():SimplePcg32(0xed743cc4U) {}
4572
4573 explicit SimplePcg32(result_type seed_);
4574
4575 void seed(result_type seed_);
4576 void discard(uint64_t skip);
4577
4578 result_type operator()();
4579
4580 private:
4581 friend bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
4582 friend bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs);
4583
4584 // In theory we also need operator<< and operator>>
4585 // In practice we do not use them, so we will skip them for now
4586
4587 std::uint64_t m_state;
4588 // This part of the state determines which "stream" of the numbers
4589 // is chosen -- we take it as a constant for Catch2, so we only
4590 // need to deal with seeding the main state.
4591 // Picked by reading 8 bytes from `/dev/random` :-)
4592 static const std::uint64_t s_inc = (0x13ed0cc53f939476ULL << 1ULL) | 1ULL;
4593 };
4594
4595} // end namespace Catch
4596
4597// end catch_random_number_generator.h
4598#include <random>
4599
4600namespace Catch {
4601namespace Generators {
4602
4603template <typename Float>
4604class RandomFloatingGenerator final : public IGenerator<Float> {
4605 Catch::SimplePcg32& m_rng;
4606 std::uniform_real_distribution<Float> m_dist;
4607 Float m_current_number;
4608public:
4609
4610 RandomFloatingGenerator(Float a, Float b):
4611 m_rng(rng()),
4612 m_dist(a, b) {
4613 static_cast<void>(next());
4614 }
4615
4616 Float const& get() const override {
4617 return m_current_number;
4618 }
4619 bool next() override {
4620 m_current_number = m_dist(m_rng);
4621 return true;
4622 }
4623};
4624
4625template <typename Integer>
4626class RandomIntegerGenerator final : public IGenerator<Integer> {
4627 Catch::SimplePcg32& m_rng;
4628 std::uniform_int_distribution<Integer> m_dist;
4629 Integer m_current_number;
4630public:
4631
4632 RandomIntegerGenerator(Integer a, Integer b):
4633 m_rng(rng()),
4634 m_dist(a, b) {
4635 static_cast<void>(next());
4636 }
4637
4638 Integer const& get() const override {
4639 return m_current_number;
4640 }
4641 bool next() override {
4642 m_current_number = m_dist(m_rng);
4643 return true;
4644 }
4645};
4646
4647// TODO: Ideally this would be also constrained against the various char types,
4648// but I don't expect users to run into that in practice.
4649template <typename T>
4650typename std::enable_if<std::is_integral<T>::value && !std::is_same<T, bool>::value,
4652random(T a, T b) {
4653 return GeneratorWrapper<T>(
4654 pf::make_unique<RandomIntegerGenerator<T>>(a, b)
4655 );
4656}
4657
4658template <typename T>
4659typename std::enable_if<std::is_floating_point<T>::value,
4660GeneratorWrapper<T>>::type
4661random(T a, T b) {
4662 return GeneratorWrapper<T>(
4663 pf::make_unique<RandomFloatingGenerator<T>>(a, b)
4664 );
4665}
4666
4667template <typename T>
4668class RangeGenerator final : public IGenerator<T> {
4669 T m_current;
4670 T m_end;
4671 T m_step;
4672 bool m_positive;
4673
4674public:
4675 RangeGenerator(T const& start, T const& end, T const& step):
4676 m_current(start),
4677 m_end(end),
4678 m_step(step),
4679 m_positive(m_step > T(0))
4680 {
4681 assert(m_current != m_end && "Range start and end cannot be equal");
4682 assert(m_step != T(0) && "Step size cannot be zero");
4683 assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
4684 }
4685
4686 RangeGenerator(T const& start, T const& end):
4687 RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
4688 {}
4689
4690 T const& get() const override {
4691 return m_current;
4692 }
4693
4694 bool next() override {
4695 m_current += m_step;
4696 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
4697 }
4698};
4699
4700template <typename T>
4701GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
4702 static_assert(std::is_arithmetic<T>::value && !std::is_same<T, bool>::value, "Type must be numeric");
4703 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
4704}
4705
4706template <typename T>
4707GeneratorWrapper<T> range(T const& start, T const& end) {
4708 static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
4709 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
4710}
4711
4712template <typename T>
4713class IteratorGenerator final : public IGenerator<T> {
4714 static_assert(!std::is_same<T, bool>::value,
4715 "IteratorGenerator currently does not support bools"
4716 "because of std::vector<bool> specialization");
4717
4718 std::vector<T> m_elems;
4719 size_t m_current = 0;
4720public:
4721 template <typename InputIterator, typename InputSentinel>
4722 IteratorGenerator(InputIterator first, InputSentinel last):m_elems(first, last) {
4723 if (m_elems.empty()) {
4724 Catch::throw_exception(GeneratorException("IteratorGenerator received no valid values"));
4725 }
4726 }
4727
4728 T const& get() const override {
4729 return m_elems[m_current];
4730 }
4731
4732 bool next() override {
4733 ++m_current;
4734 return m_current != m_elems.size();
4735 }
4736};
4737
4738template <typename InputIterator,
4739 typename InputSentinel,
4740 typename ResultType = typename std::iterator_traits<InputIterator>::value_type>
4741GeneratorWrapper<ResultType> from_range(InputIterator from, InputSentinel to) {
4742 return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(from, to));
4743}
4744
4745template <typename Container,
4746 typename ResultType = typename Container::value_type>
4747GeneratorWrapper<ResultType> from_range(Container const& cnt) {
4748 return GeneratorWrapper<ResultType>(pf::make_unique<IteratorGenerator<ResultType>>(cnt.begin(), cnt.end()));
4749}
4750
4751} // namespace Generators
4752} // namespace Catch
4753
4754// end catch_generators_specific.hpp
4755
4756// These files are included here so the single_include script doesn't put them
4757// in the conditionally compiled sections
4758// start catch_test_case_info.h
4759
4760#include <string>
4761#include <vector>
4762#include <memory>
4763
4764#ifdef __clang__
4765#pragma clang diagnostic push
4766#pragma clang diagnostic ignored "-Wpadded"
4767#endif
4768
4769namespace Catch {
4770
4771 struct ITestInvoker;
4772
4774 enum SpecialProperties{
4775 None = 0,
4776 IsHidden = 1 << 1,
4777 ShouldFail = 1 << 2,
4778 MayFail = 1 << 3,
4779 Throws = 1 << 4,
4780 NonPortable = 1 << 5,
4781 Benchmark = 1 << 6
4782 };
4783
4784 TestCaseInfo( std::string const& _name,
4785 std::string const& _className,
4786 std::string const& _description,
4787 std::vector<std::string> const& _tags,
4788 SourceLineInfo const& _lineInfo );
4789
4790 friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
4791
4792 bool isHidden() const;
4793 bool throws() const;
4794 bool okToFail() const;
4795 bool expectedToFail() const;
4796
4797 std::string tagsAsString() const;
4798
4799 std::string name;
4800 std::string className;
4801 std::string description;
4802 std::vector<std::string> tags;
4803 std::vector<std::string> lcaseTags;
4804 SourceLineInfo lineInfo;
4805 SpecialProperties properties;
4806 };
4807
4808 class TestCase : public TestCaseInfo {
4809 public:
4810
4811 TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
4812
4813 TestCase withName( std::string const& _newName ) const;
4814
4815 void invoke() const;
4816
4817 TestCaseInfo const& getTestCaseInfo() const;
4818
4819 bool operator == ( TestCase const& other ) const;
4820 bool operator < ( TestCase const& other ) const;
4821
4822 private:
4823 std::shared_ptr<ITestInvoker> test;
4824 };
4825
4826 TestCase makeTestCase( ITestInvoker* testCase,
4827 std::string const& className,
4828 NameAndTags const& nameAndTags,
4829 SourceLineInfo const& lineInfo );
4830}
4831
4832#ifdef __clang__
4833#pragma clang diagnostic pop
4834#endif
4835
4836// end catch_test_case_info.h
4837// start catch_interfaces_runner.h
4838
4839namespace Catch {
4840
4841 struct IRunner {
4842 virtual ~IRunner();
4843 virtual bool aborting() const = 0;
4844 };
4845}
4846
4847// end catch_interfaces_runner.h
4848
4849#ifdef __OBJC__
4850// start catch_objc.hpp
4851
4852#import <objc/runtime.h>
4853
4854#include <string>
4855
4856// NB. Any general catch headers included here must be included
4857// in catch.hpp first to make sure they are included by the single
4858// header for non obj-usage
4859
4861// This protocol is really only here for (self) documenting purposes, since
4862// all its methods are optional.
4863@protocol OcFixture
4864
4865@optional
4866
4867-(void) setUp;
4868-(void) tearDown;
4869
4870@end
4871
4872namespace Catch {
4873
4874 class OcMethod : public ITestInvoker {
4875
4876 public:
4877 OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
4878
4879 virtual void invoke() const {
4880 id obj = [[m_cls alloc] init];
4881
4882 performOptionalSelector( obj, @selector(setUp) );
4883 performOptionalSelector( obj, m_sel );
4884 performOptionalSelector( obj, @selector(tearDown) );
4885
4886 arcSafeRelease( obj );
4887 }
4888 private:
4889 virtual ~OcMethod() {}
4890
4891 Class m_cls;
4892 SEL m_sel;
4893 };
4894
4895 namespace Detail{
4896
4897 inline std::string getAnnotation( Class cls,
4898 std::string const& annotationName,
4899 std::string const& testCaseName ) {
4900 NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
4901 SEL sel = NSSelectorFromString( selStr );
4902 arcSafeRelease( selStr );
4903 id value = performOptionalSelector( cls, sel );
4904 if( value )
4905 return [(NSString*)value UTF8String];
4906 return "";
4907 }
4908 }
4909
4910 inline std::size_t registerTestMethods() {
4911 std::size_t noTestMethods = 0;
4912 int noClasses = objc_getClassList( nullptr, 0 );
4913
4914 Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
4915 objc_getClassList( classes, noClasses );
4916
4917 for( int c = 0; c < noClasses; c++ ) {
4918 Class cls = classes[c];
4919 {
4920 u_int count;
4921 Method* methods = class_copyMethodList( cls, &count );
4922 for( u_int m = 0; m < count ; m++ ) {
4923 SEL selector = method_getName(methods[m]);
4924 std::string methodName = sel_getName(selector);
4925 if( startsWith( methodName, "Catch_TestCase_" ) ) {
4926 std::string testCaseName = methodName.substr( 15 );
4927 std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
4928 std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
4929 const char* className = class_getName( cls );
4930
4931 getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
4932 noTestMethods++;
4933 }
4934 }
4935 free(methods);
4936 }
4937 }
4938 return noTestMethods;
4939 }
4940
4941#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
4942
4943 namespace Matchers {
4944 namespace Impl {
4945 namespace NSStringMatchers {
4946
4947 struct StringHolder : MatcherBase<NSString*>{
4948 StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
4949 StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
4950 StringHolder() {
4951 arcSafeRelease( m_substr );
4952 }
4953
4954 bool match( NSString* str ) const override {
4955 return false;
4956 }
4957
4958 NSString* CATCH_ARC_STRONG m_substr;
4959 };
4960
4961 struct Equals : StringHolder {
4962 Equals( NSString* substr ) : StringHolder( substr ){}
4963
4964 bool match( NSString* str ) const override {
4965 return (str != nil || m_substr == nil ) &&
4966 [str isEqualToString:m_substr];
4967 }
4968
4969 std::string describe() const override {
4970 return "equals string: " + Catch::Detail::stringify( m_substr );
4971 }
4972 };
4973
4974 struct Contains : StringHolder {
4975 Contains( NSString* substr ) : StringHolder( substr ){}
4976
4977 bool match( NSString* str ) const override {
4978 return (str != nil || m_substr == nil ) &&
4979 [str rangeOfString:m_substr].location != NSNotFound;
4980 }
4981
4982 std::string describe() const override {
4983 return "contains string: " + Catch::Detail::stringify( m_substr );
4984 }
4985 };
4986
4987 struct StartsWith : StringHolder {
4988 StartsWith( NSString* substr ) : StringHolder( substr ){}
4989
4990 bool match( NSString* str ) const override {
4991 return (str != nil || m_substr == nil ) &&
4992 [str rangeOfString:m_substr].location == 0;
4993 }
4994
4995 std::string describe() const override {
4996 return "starts with: " + Catch::Detail::stringify( m_substr );
4997 }
4998 };
4999 struct EndsWith : StringHolder {
5000 EndsWith( NSString* substr ) : StringHolder( substr ){}
5001
5002 bool match( NSString* str ) const override {
5003 return (str != nil || m_substr == nil ) &&
5004 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
5005 }
5006
5007 std::string describe() const override {
5008 return "ends with: " + Catch::Detail::stringify( m_substr );
5009 }
5010 };
5011
5012 } // namespace NSStringMatchers
5013 } // namespace Impl
5014
5015 inline Impl::NSStringMatchers::Equals
5016 Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
5017
5018 inline Impl::NSStringMatchers::Contains
5019 Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
5020
5021 inline Impl::NSStringMatchers::StartsWith
5022 StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
5023
5024 inline Impl::NSStringMatchers::EndsWith
5025 EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
5026
5027 } // namespace Matchers
5028
5029 using namespace Matchers;
5030
5031#endif // CATCH_CONFIG_DISABLE_MATCHERS
5032
5033} // namespace Catch
5034
5036#define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
5037#define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
5038+(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
5039{ \
5040return @ name; \
5041} \
5042+(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
5043{ \
5044return @ desc; \
5045} \
5046-(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
5047
5048#define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
5049
5050// end catch_objc.hpp
5051#endif
5052
5053// Benchmarking needs the externally-facing parts of reporters to work
5054#if defined(CATCH_CONFIG_EXTERNAL_INTERFACES) || defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5055// start catch_external_interfaces.h
5056
5057// start catch_reporter_bases.hpp
5058
5059// start catch_interfaces_reporter.h
5060
5061// start catch_config.hpp
5062
5063// start catch_test_spec_parser.h
5064
5065#ifdef __clang__
5066#pragma clang diagnostic push
5067#pragma clang diagnostic ignored "-Wpadded"
5068#endif
5069
5070// start catch_test_spec.h
5071
5072#ifdef __clang__
5073#pragma clang diagnostic push
5074#pragma clang diagnostic ignored "-Wpadded"
5075#endif
5076
5077// start catch_wildcard_pattern.h
5078
5079namespace Catch
5080{
5081 class WildcardPattern {
5082 enum WildcardPosition {
5083 NoWildcard = 0,
5084 WildcardAtStart = 1,
5085 WildcardAtEnd = 2,
5086 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
5087 };
5088
5089 public:
5090
5091 WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
5092 virtual ~WildcardPattern() = default;
5093 virtual bool matches( std::string const& str ) const;
5094
5095 private:
5096 std::string normaliseString( std::string const& str ) const;
5097 CaseSensitive::Choice m_caseSensitivity;
5098 WildcardPosition m_wildcard = NoWildcard;
5099 std::string m_pattern;
5100 };
5101}
5102
5103// end catch_wildcard_pattern.h
5104#include <string>
5105#include <vector>
5106#include <memory>
5107
5108namespace Catch {
5109
5110 struct IConfig;
5111
5112 class TestSpec {
5113 class Pattern {
5114 public:
5115 explicit Pattern( std::string const& name );
5116 virtual ~Pattern();
5117 virtual bool matches( TestCaseInfo const& testCase ) const = 0;
5118 std::string const& name() const;
5119 private:
5120 std::string const m_name;
5121 };
5122 using PatternPtr = std::shared_ptr<Pattern>;
5123
5124 class NamePattern : public Pattern {
5125 public:
5126 explicit NamePattern( std::string const& name, std::string const& filterString );
5127 bool matches( TestCaseInfo const& testCase ) const override;
5128 private:
5129 WildcardPattern m_wildcardPattern;
5130 };
5131
5132 class TagPattern : public Pattern {
5133 public:
5134 explicit TagPattern( std::string const& tag, std::string const& filterString );
5135 bool matches( TestCaseInfo const& testCase ) const override;
5136 private:
5137 std::string m_tag;
5138 };
5139
5140 class ExcludedPattern : public Pattern {
5141 public:
5142 explicit ExcludedPattern( PatternPtr const& underlyingPattern );
5143 bool matches( TestCaseInfo const& testCase ) const override;
5144 private:
5145 PatternPtr m_underlyingPattern;
5146 };
5147
5148 struct Filter {
5149 std::vector<PatternPtr> m_patterns;
5150
5151 bool matches( TestCaseInfo const& testCase ) const;
5152 std::string name() const;
5153 };
5154
5155 public:
5156 struct FilterMatch {
5157 std::string name;
5158 std::vector<TestCase const*> tests;
5159 };
5160 using Matches = std::vector<FilterMatch>;
5161 using vectorStrings = std::vector<std::string>;
5162
5163 bool hasFilters() const;
5164 bool matches( TestCaseInfo const& testCase ) const;
5165 Matches matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const;
5166 const vectorStrings & getInvalidArgs() const;
5167
5168 private:
5169 std::vector<Filter> m_filters;
5170 std::vector<std::string> m_invalidArgs;
5171 friend class TestSpecParser;
5172 };
5173}
5174
5175#ifdef __clang__
5176#pragma clang diagnostic pop
5177#endif
5178
5179// end catch_test_spec.h
5180// start catch_interfaces_tag_alias_registry.h
5181
5182#include <string>
5183
5184namespace Catch {
5185
5186 struct TagAlias;
5187
5188 struct ITagAliasRegistry {
5189 virtual ~ITagAliasRegistry();
5190 // Nullptr if not present
5191 virtual TagAlias const* find( std::string const& alias ) const = 0;
5192 virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
5193
5194 static ITagAliasRegistry const& get();
5195 };
5196
5197} // end namespace Catch
5198
5199// end catch_interfaces_tag_alias_registry.h
5200namespace Catch {
5201
5202 class TestSpecParser {
5203 enum Mode{ None, Name, QuotedName, Tag, EscapedName };
5204 Mode m_mode = None;
5205 Mode lastMode = None;
5206 bool m_exclusion = false;
5207 std::size_t m_pos = 0;
5208 std::size_t m_realPatternPos = 0;
5209 std::string m_arg;
5210 std::string m_substring;
5211 std::string m_patternName;
5212 std::vector<std::size_t> m_escapeChars;
5213 TestSpec::Filter m_currentFilter;
5214 TestSpec m_testSpec;
5215 ITagAliasRegistry const* m_tagAliases = nullptr;
5216
5217 public:
5218 TestSpecParser( ITagAliasRegistry const& tagAliases );
5219
5220 TestSpecParser& parse( std::string const& arg );
5221 TestSpec testSpec();
5222
5223 private:
5224 bool visitChar( char c );
5225 void startNewMode( Mode mode );
5226 bool processNoneChar( char c );
5227 void processNameChar( char c );
5228 bool processOtherChar( char c );
5229 void endMode();
5230 void escape();
5231 bool isControlChar( char c ) const;
5232 void saveLastMode();
5233 void revertBackToLastMode();
5234 void addFilter();
5235 bool separate();
5236
5237 // Handles common preprocessing of the pattern for name/tag patterns
5238 std::string preprocessPattern();
5239 // Adds the current pattern as a test name
5240 void addNamePattern();
5241 // Adds the current pattern as a tag
5242 void addTagPattern();
5243
5244 inline void addCharToPattern(char c) {
5245 m_substring += c;
5246 m_patternName += c;
5247 m_realPatternPos++;
5248 }
5249
5250 };
5251 TestSpec parseTestSpec( std::string const& arg );
5252
5253} // namespace Catch
5254
5255#ifdef __clang__
5256#pragma clang diagnostic pop
5257#endif
5258
5259// end catch_test_spec_parser.h
5260// Libstdc++ doesn't like incomplete classes for unique_ptr
5261
5262#include <memory>
5263#include <vector>
5264#include <string>
5265
5266#ifndef CATCH_CONFIG_CONSOLE_WIDTH
5267#define CATCH_CONFIG_CONSOLE_WIDTH 80
5268#endif
5269
5270namespace Catch {
5271
5272 struct IStream;
5273
5274 struct ConfigData {
5275 bool listTests = false;
5276 bool listTags = false;
5277 bool listReporters = false;
5278 bool listTestNamesOnly = false;
5279
5280 bool showSuccessfulTests = false;
5281 bool shouldDebugBreak = false;
5282 bool noThrow = false;
5283 bool showHelp = false;
5284 bool showInvisibles = false;
5285 bool filenamesAsTags = false;
5286 bool libIdentify = false;
5287
5288 int abortAfter = -1;
5289 unsigned int rngSeed = 0;
5290
5291 bool benchmarkNoAnalysis = false;
5292 unsigned int benchmarkSamples = 100;
5293 double benchmarkConfidenceInterval = 0.95;
5294 unsigned int benchmarkResamples = 100000;
5295 std::chrono::milliseconds::rep benchmarkWarmupTime = 100;
5296
5297 Verbosity verbosity = Verbosity::Normal;
5298 WarnAbout::What warnings = WarnAbout::Nothing;
5299 ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
5300 double minDuration = -1;
5301 RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
5302 UseColour::YesOrNo useColour = UseColour::Auto;
5303 WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
5304
5305 std::string outputFilename;
5306 std::string name;
5307 std::string processName;
5308#ifndef CATCH_CONFIG_DEFAULT_REPORTER
5309#define CATCH_CONFIG_DEFAULT_REPORTER "console"
5310#endif
5311 std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
5312#undef CATCH_CONFIG_DEFAULT_REPORTER
5313
5314 std::vector<std::string> testsOrTags;
5315 std::vector<std::string> sectionsToRun;
5316 };
5317
5318 class Config : public IConfig {
5319 public:
5320
5321 Config() = default;
5322 Config( ConfigData const& data );
5323 virtual ~Config() = default;
5324
5325 std::string const& getFilename() const;
5326
5327 bool listTests() const;
5328 bool listTestNamesOnly() const;
5329 bool listTags() const;
5330 bool listReporters() const;
5331
5332 std::string getProcessName() const;
5333 std::string const& getReporterName() const;
5334
5335 std::vector<std::string> const& getTestsOrTags() const override;
5336 std::vector<std::string> const& getSectionsToRun() const override;
5337
5338 TestSpec const& testSpec() const override;
5339 bool hasTestFilters() const override;
5340
5341 bool showHelp() const;
5342
5343 // IConfig interface
5344 bool allowThrows() const override;
5345 std::ostream& stream() const override;
5346 std::string name() const override;
5347 bool includeSuccessfulResults() const override;
5348 bool warnAboutMissingAssertions() const override;
5349 bool warnAboutNoTests() const override;
5350 ShowDurations::OrNot showDurations() const override;
5351 double minDuration() const override;
5352 RunTests::InWhatOrder runOrder() const override;
5353 unsigned int rngSeed() const override;
5354 UseColour::YesOrNo useColour() const override;
5355 bool shouldDebugBreak() const override;
5356 int abortAfter() const override;
5357 bool showInvisibles() const override;
5358 Verbosity verbosity() const override;
5359 bool benchmarkNoAnalysis() const override;
5360 int benchmarkSamples() const override;
5361 double benchmarkConfidenceInterval() const override;
5362 unsigned int benchmarkResamples() const override;
5363 std::chrono::milliseconds benchmarkWarmupTime() const override;
5364
5365 private:
5366
5367 IStream const* openStream();
5368 ConfigData m_data;
5369
5370 std::unique_ptr<IStream const> m_stream;
5371 TestSpec m_testSpec;
5372 bool m_hasTestFilters = false;
5373 };
5374
5375} // end namespace Catch
5376
5377// end catch_config.hpp
5378// start catch_assertionresult.h
5379
5380#include <string>
5381
5382namespace Catch {
5383
5384 struct AssertionResultData
5385 {
5386 AssertionResultData() = delete;
5387
5388 AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
5389
5390 std::string message;
5391 mutable std::string reconstructedExpression;
5392 LazyExpression lazyExpression;
5393 ResultWas::OfType resultType;
5394
5395 std::string reconstructExpression() const;
5396 };
5397
5398 class AssertionResult {
5399 public:
5400 AssertionResult() = delete;
5401 AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
5402
5403 bool isOk() const;
5404 bool succeeded() const;
5405 ResultWas::OfType getResultType() const;
5406 bool hasExpression() const;
5407 bool hasMessage() const;
5408 std::string getExpression() const;
5409 std::string getExpressionInMacro() const;
5410 bool hasExpandedExpression() const;
5411 std::string getExpandedExpression() const;
5412 std::string getMessage() const;
5413 SourceLineInfo getSourceInfo() const;
5414 StringRef getTestMacroName() const;
5415
5416 //protected:
5417 AssertionInfo m_info;
5418 AssertionResultData m_resultData;
5419 };
5420
5421} // end namespace Catch
5422
5423// end catch_assertionresult.h
5424#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5425// start catch_estimate.hpp
5426
5427 // Statistics estimates
5428
5429
5430namespace Catch {
5431 namespace Benchmark {
5432 template <typename Duration>
5433 struct Estimate {
5434 Duration point;
5435 Duration lower_bound;
5436 Duration upper_bound;
5437 double confidence_interval;
5438
5439 template <typename Duration2>
5440 operator Estimate<Duration2>() const {
5441 return { point, lower_bound, upper_bound, confidence_interval };
5442 }
5443 };
5444 } // namespace Benchmark
5445} // namespace Catch
5446
5447// end catch_estimate.hpp
5448// start catch_outlier_classification.hpp
5449
5450// Outlier information
5451
5452namespace Catch {
5453 namespace Benchmark {
5454 struct OutlierClassification {
5455 int samples_seen = 0;
5456 int low_severe = 0; // more than 3 times IQR below Q1
5457 int low_mild = 0; // 1.5 to 3 times IQR below Q1
5458 int high_mild = 0; // 1.5 to 3 times IQR above Q3
5459 int high_severe = 0; // more than 3 times IQR above Q3
5460
5461 int total() const {
5462 return low_severe + low_mild + high_mild + high_severe;
5463 }
5464 };
5465 } // namespace Benchmark
5466} // namespace Catch
5467
5468// end catch_outlier_classification.hpp
5469
5470#include <iterator>
5471#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5472
5473#include <string>
5474#include <iosfwd>
5475#include <map>
5476#include <set>
5477#include <memory>
5478#include <algorithm>
5479
5480namespace Catch {
5481
5482 struct ReporterConfig {
5483 explicit ReporterConfig( IConfigPtr const& _fullConfig );
5484
5485 ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
5486
5487 std::ostream& stream() const;
5488 IConfigPtr fullConfig() const;
5489
5490 private:
5491 std::ostream* m_stream;
5492 IConfigPtr m_fullConfig;
5493 };
5494
5495 struct ReporterPreferences {
5496 bool shouldRedirectStdOut = false;
5497 bool shouldReportAllAssertions = false;
5498 };
5499
5500 template<typename T>
5501 struct LazyStat : Option<T> {
5502 LazyStat& operator=( T const& _value ) {
5503 Option<T>::operator=( _value );
5504 used = false;
5505 return *this;
5506 }
5507 void reset() {
5508 Option<T>::reset();
5509 used = false;
5510 }
5511 bool used = false;
5512 };
5513
5514 struct TestRunInfo {
5515 TestRunInfo( std::string const& _name );
5516 std::string name;
5517 };
5518 struct GroupInfo {
5519 GroupInfo( std::string const& _name,
5520 std::size_t _groupIndex,
5521 std::size_t _groupsCount );
5522
5523 std::string name;
5524 std::size_t groupIndex;
5525 std::size_t groupsCounts;
5526 };
5527
5528 struct AssertionStats {
5529 AssertionStats( AssertionResult const& _assertionResult,
5530 std::vector<MessageInfo> const& _infoMessages,
5531 Totals const& _totals );
5532
5533 AssertionStats( AssertionStats const& ) = default;
5534 AssertionStats( AssertionStats && ) = default;
5535 AssertionStats& operator = ( AssertionStats const& ) = delete;
5536 AssertionStats& operator = ( AssertionStats && ) = delete;
5537 virtual ~AssertionStats();
5538
5539 AssertionResult assertionResult;
5540 std::vector<MessageInfo> infoMessages;
5541 Totals totals;
5542 };
5543
5544 struct SectionStats {
5545 SectionStats( SectionInfo const& _sectionInfo,
5546 Counts const& _assertions,
5547 double _durationInSeconds,
5548 bool _missingAssertions );
5549 SectionStats( SectionStats const& ) = default;
5550 SectionStats( SectionStats && ) = default;
5551 SectionStats& operator = ( SectionStats const& ) = default;
5552 SectionStats& operator = ( SectionStats && ) = default;
5553 virtual ~SectionStats();
5554
5555 SectionInfo sectionInfo;
5556 Counts assertions;
5557 double durationInSeconds;
5558 bool missingAssertions;
5559 };
5560
5561 struct TestCaseStats {
5562 TestCaseStats( TestCaseInfo const& _testInfo,
5563 Totals const& _totals,
5564 std::string const& _stdOut,
5565 std::string const& _stdErr,
5566 bool _aborting );
5567
5568 TestCaseStats( TestCaseStats const& ) = default;
5569 TestCaseStats( TestCaseStats && ) = default;
5570 TestCaseStats& operator = ( TestCaseStats const& ) = default;
5571 TestCaseStats& operator = ( TestCaseStats && ) = default;
5572 virtual ~TestCaseStats();
5573
5574 TestCaseInfo testInfo;
5575 Totals totals;
5576 std::string stdOut;
5577 std::string stdErr;
5578 bool aborting;
5579 };
5580
5581 struct TestGroupStats {
5582 TestGroupStats( GroupInfo const& _groupInfo,
5583 Totals const& _totals,
5584 bool _aborting );
5585 TestGroupStats( GroupInfo const& _groupInfo );
5586
5587 TestGroupStats( TestGroupStats const& ) = default;
5588 TestGroupStats( TestGroupStats && ) = default;
5589 TestGroupStats& operator = ( TestGroupStats const& ) = default;
5590 TestGroupStats& operator = ( TestGroupStats && ) = default;
5591 virtual ~TestGroupStats();
5592
5593 GroupInfo groupInfo;
5594 Totals totals;
5595 bool aborting;
5596 };
5597
5598 struct TestRunStats {
5599 TestRunStats( TestRunInfo const& _runInfo,
5600 Totals const& _totals,
5601 bool _aborting );
5602
5603 TestRunStats( TestRunStats const& ) = default;
5604 TestRunStats( TestRunStats && ) = default;
5605 TestRunStats& operator = ( TestRunStats const& ) = default;
5606 TestRunStats& operator = ( TestRunStats && ) = default;
5607 virtual ~TestRunStats();
5608
5609 TestRunInfo runInfo;
5610 Totals totals;
5611 bool aborting;
5612 };
5613
5614#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5615 struct BenchmarkInfo {
5616 std::string name;
5617 double estimatedDuration;
5618 int iterations;
5619 int samples;
5620 unsigned int resamples;
5621 double clockResolution;
5622 double clockCost;
5623 };
5624
5625 template <class Duration>
5626 struct BenchmarkStats {
5627 BenchmarkInfo info;
5628
5629 std::vector<Duration> samples;
5630 Benchmark::Estimate<Duration> mean;
5631 Benchmark::Estimate<Duration> standardDeviation;
5632 Benchmark::OutlierClassification outliers;
5633 double outlierVariance;
5634
5635 template <typename Duration2>
5636 operator BenchmarkStats<Duration2>() const {
5637 std::vector<Duration2> samples2;
5638 samples2.reserve(samples.size());
5639 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
5640 return {
5641 info,
5642 std::move(samples2),
5643 mean,
5644 standardDeviation,
5645 outliers,
5646 outlierVariance,
5647 };
5648 }
5649 };
5650#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5651
5652 struct IStreamingReporter {
5653 virtual ~IStreamingReporter() = default;
5654
5655 // Implementing class must also provide the following static methods:
5656 // static std::string getDescription();
5657 // static std::set<Verbosity> getSupportedVerbosities()
5658
5659 virtual ReporterPreferences getPreferences() const = 0;
5660
5661 virtual void noMatchingTestCases( std::string const& spec ) = 0;
5662
5663 virtual void reportInvalidArguments(std::string const&) {}
5664
5665 virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
5666 virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
5667
5668 virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
5669 virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
5670
5671#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
5672 virtual void benchmarkPreparing( std::string const& ) {}
5673 virtual void benchmarkStarting( BenchmarkInfo const& ) {}
5674 virtual void benchmarkEnded( BenchmarkStats<> const& ) {}
5675 virtual void benchmarkFailed( std::string const& ) {}
5676#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
5677
5678 virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
5679
5680 // The return value indicates if the messages buffer should be cleared:
5681 virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
5682
5683 virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
5684 virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
5685 virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
5686 virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
5687
5688 virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
5689
5690 // Default empty implementation provided
5691 virtual void fatalErrorEncountered( StringRef name );
5692
5693 virtual bool isMulti() const;
5694 };
5695 using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
5696
5697 struct IReporterFactory {
5698 virtual ~IReporterFactory();
5699 virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
5700 virtual std::string getDescription() const = 0;
5701 };
5702 using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
5703
5704 struct IReporterRegistry {
5705 using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
5706 using Listeners = std::vector<IReporterFactoryPtr>;
5707
5708 virtual ~IReporterRegistry();
5709 virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
5710 virtual FactoryMap const& getFactories() const = 0;
5711 virtual Listeners const& getListeners() const = 0;
5712 };
5713
5714} // end namespace Catch
5715
5716// end catch_interfaces_reporter.h
5717#include <algorithm>
5718#include <cstring>
5719#include <cfloat>
5720#include <cstdio>
5721#include <cassert>
5722#include <memory>
5723#include <ostream>
5724
5725namespace Catch {
5726 void prepareExpandedExpression(AssertionResult& result);
5727
5728 // Returns double formatted as %.3f (format expected on output)
5729 std::string getFormattedDuration( double duration );
5730
5732 bool shouldShowDuration( IConfig const& config, double duration );
5733
5734 std::string serializeFilters( std::vector<std::string> const& container );
5735
5736 template<typename DerivedT>
5737 struct StreamingReporterBase : IStreamingReporter {
5738
5739 StreamingReporterBase( ReporterConfig const& _config )
5740 : m_config( _config.fullConfig() ),
5741 stream( _config.stream() )
5742 {
5743 m_reporterPrefs.shouldRedirectStdOut = false;
5744 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5745 CATCH_ERROR( "Verbosity level not supported by this reporter" );
5746 }
5747
5748 ReporterPreferences getPreferences() const override {
5749 return m_reporterPrefs;
5750 }
5751
5752 static std::set<Verbosity> getSupportedVerbosities() {
5753 return { Verbosity::Normal };
5754 }
5755
5756 ~StreamingReporterBase() override = default;
5757
5758 void noMatchingTestCases(std::string const&) override {}
5759
5760 void reportInvalidArguments(std::string const&) override {}
5761
5762 void testRunStarting(TestRunInfo const& _testRunInfo) override {
5763 currentTestRunInfo = _testRunInfo;
5764 }
5765
5766 void testGroupStarting(GroupInfo const& _groupInfo) override {
5767 currentGroupInfo = _groupInfo;
5768 }
5769
5770 void testCaseStarting(TestCaseInfo const& _testInfo) override {
5771 currentTestCaseInfo = _testInfo;
5772 }
5773 void sectionStarting(SectionInfo const& _sectionInfo) override {
5774 m_sectionStack.push_back(_sectionInfo);
5775 }
5776
5777 void sectionEnded(SectionStats const& /* _sectionStats */) override {
5778 m_sectionStack.pop_back();
5779 }
5780 void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
5781 currentTestCaseInfo.reset();
5782 }
5783 void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
5784 currentGroupInfo.reset();
5785 }
5786 void testRunEnded(TestRunStats const& /* _testRunStats */) override {
5787 currentTestCaseInfo.reset();
5788 currentGroupInfo.reset();
5789 currentTestRunInfo.reset();
5790 }
5791
5792 void skipTest(TestCaseInfo const&) override {
5793 // Don't do anything with this by default.
5794 // It can optionally be overridden in the derived class.
5795 }
5796
5797 IConfigPtr m_config;
5798 std::ostream& stream;
5799
5800 LazyStat<TestRunInfo> currentTestRunInfo;
5801 LazyStat<GroupInfo> currentGroupInfo;
5802 LazyStat<TestCaseInfo> currentTestCaseInfo;
5803
5804 std::vector<SectionInfo> m_sectionStack;
5805 ReporterPreferences m_reporterPrefs;
5806 };
5807
5808 template<typename DerivedT>
5809 struct CumulativeReporterBase : IStreamingReporter {
5810 template<typename T, typename ChildNodeT>
5811 struct Node {
5812 explicit Node( T const& _value ) : value( _value ) {}
5813 virtual ~Node() {}
5814
5815 using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
5816 T value;
5817 ChildNodes children;
5818 };
5819 struct SectionNode {
5820 explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
5821 virtual ~SectionNode() = default;
5822
5823 bool operator == (SectionNode const& other) const {
5824 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
5825 }
5826 bool operator == (std::shared_ptr<SectionNode> const& other) const {
5827 return operator==(*other);
5828 }
5829
5830 SectionStats stats;
5831 using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
5832 using Assertions = std::vector<AssertionStats>;
5833 ChildSections childSections;
5834 Assertions assertions;
5835 std::string stdOut;
5836 std::string stdErr;
5837 };
5838
5839 struct BySectionInfo {
5840 BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
5841 BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
5842 bool operator() (std::shared_ptr<SectionNode> const& node) const {
5843 return ((node->stats.sectionInfo.name == m_other.name) &&
5844 (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
5845 }
5846 void operator=(BySectionInfo const&) = delete;
5847
5848 private:
5849 SectionInfo const& m_other;
5850 };
5851
5852 using TestCaseNode = Node<TestCaseStats, SectionNode>;
5853 using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
5854 using TestRunNode = Node<TestRunStats, TestGroupNode>;
5855
5856 CumulativeReporterBase( ReporterConfig const& _config )
5857 : m_config( _config.fullConfig() ),
5858 stream( _config.stream() )
5859 {
5860 m_reporterPrefs.shouldRedirectStdOut = false;
5861 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5862 CATCH_ERROR( "Verbosity level not supported by this reporter" );
5863 }
5864 ~CumulativeReporterBase() override = default;
5865
5866 ReporterPreferences getPreferences() const override {
5867 return m_reporterPrefs;
5868 }
5869
5870 static std::set<Verbosity> getSupportedVerbosities() {
5871 return { Verbosity::Normal };
5872 }
5873
5874 void testRunStarting( TestRunInfo const& ) override {}
5875 void testGroupStarting( GroupInfo const& ) override {}
5876
5877 void testCaseStarting( TestCaseInfo const& ) override {}
5878
5879 void sectionStarting( SectionInfo const& sectionInfo ) override {
5880 SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
5881 std::shared_ptr<SectionNode> node;
5882 if( m_sectionStack.empty() ) {
5883 if( !m_rootSection )
5884 m_rootSection = std::make_shared<SectionNode>( incompleteStats );
5885 node = m_rootSection;
5886 }
5887 else {
5888 SectionNode& parentNode = *m_sectionStack.back();
5889 auto it =
5890 std::find_if( parentNode.childSections.begin(),
5891 parentNode.childSections.end(),
5892 BySectionInfo( sectionInfo ) );
5893 if( it == parentNode.childSections.end() ) {
5894 node = std::make_shared<SectionNode>( incompleteStats );
5895 parentNode.childSections.push_back( node );
5896 }
5897 else
5898 node = *it;
5899 }
5900 m_sectionStack.push_back( node );
5901 m_deepestSection = std::move(node);
5902 }
5903
5904 void assertionStarting(AssertionInfo const&) override {}
5905
5906 bool assertionEnded(AssertionStats const& assertionStats) override {
5907 assert(!m_sectionStack.empty());
5908 // AssertionResult holds a pointer to a temporary DecomposedExpression,
5909 // which getExpandedExpression() calls to build the expression string.
5910 // Our section stack copy of the assertionResult will likely outlive the
5911 // temporary, so it must be expanded or discarded now to avoid calling
5912 // a destroyed object later.
5913 prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
5914 SectionNode& sectionNode = *m_sectionStack.back();
5915 sectionNode.assertions.push_back(assertionStats);
5916 return true;
5917 }
5918 void sectionEnded(SectionStats const& sectionStats) override {
5919 assert(!m_sectionStack.empty());
5920 SectionNode& node = *m_sectionStack.back();
5921 node.stats = sectionStats;
5922 m_sectionStack.pop_back();
5923 }
5924 void testCaseEnded(TestCaseStats const& testCaseStats) override {
5925 auto node = std::make_shared<TestCaseNode>(testCaseStats);
5926 assert(m_sectionStack.size() == 0);
5927 node->children.push_back(m_rootSection);
5928 m_testCases.push_back(node);
5929 m_rootSection.reset();
5930
5931 assert(m_deepestSection);
5932 m_deepestSection->stdOut = testCaseStats.stdOut;
5933 m_deepestSection->stdErr = testCaseStats.stdErr;
5934 }
5935 void testGroupEnded(TestGroupStats const& testGroupStats) override {
5936 auto node = std::make_shared<TestGroupNode>(testGroupStats);
5937 node->children.swap(m_testCases);
5938 m_testGroups.push_back(node);
5939 }
5940 void testRunEnded(TestRunStats const& testRunStats) override {
5941 auto node = std::make_shared<TestRunNode>(testRunStats);
5942 node->children.swap(m_testGroups);
5943 m_testRuns.push_back(node);
5944 testRunEndedCumulative();
5945 }
5946 virtual void testRunEndedCumulative() = 0;
5947
5948 void skipTest(TestCaseInfo const&) override {}
5949
5950 IConfigPtr m_config;
5951 std::ostream& stream;
5952 std::vector<AssertionStats> m_assertions;
5953 std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
5954 std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
5955 std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
5956
5957 std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
5958
5959 std::shared_ptr<SectionNode> m_rootSection;
5960 std::shared_ptr<SectionNode> m_deepestSection;
5961 std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
5962 ReporterPreferences m_reporterPrefs;
5963 };
5964
5965 template<char C>
5966 char const* getLineOfChars() {
5967 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
5968 if( !*line ) {
5969 std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
5970 line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
5971 }
5972 return line;
5973 }
5974
5975 struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
5976 TestEventListenerBase( ReporterConfig const& _config );
5977
5978 static std::set<Verbosity> getSupportedVerbosities();
5979
5980 void assertionStarting(AssertionInfo const&) override;
5981 bool assertionEnded(AssertionStats const&) override;
5982 };
5983
5984} // end namespace Catch
5985
5986// end catch_reporter_bases.hpp
5987// start catch_console_colour.h
5988
5989namespace Catch {
5990
5991 struct Colour {
5992 enum Code {
5993 None = 0,
5994
5995 White,
5996 Red,
5997 Green,
5998 Blue,
5999 Cyan,
6000 Yellow,
6001 Grey,
6002
6003 Bright = 0x10,
6004
6005 BrightRed = Bright | Red,
6006 BrightGreen = Bright | Green,
6007 LightGrey = Bright | Grey,
6008 BrightWhite = Bright | White,
6009 BrightYellow = Bright | Yellow,
6010
6011 // By intention
6012 FileName = LightGrey,
6013 Warning = BrightYellow,
6014 ResultError = BrightRed,
6015 ResultSuccess = BrightGreen,
6016 ResultExpectedFailure = Warning,
6017
6018 Error = BrightRed,
6019 Success = Green,
6020
6021 OriginalExpression = Cyan,
6022 ReconstructedExpression = BrightYellow,
6023
6024 SecondaryText = LightGrey,
6025 Headers = White
6026 };
6027
6028 // Use constructed object for RAII guard
6029 Colour( Code _colourCode );
6030 Colour( Colour&& other ) noexcept;
6031 Colour& operator=( Colour&& other ) noexcept;
6032 ~Colour();
6033
6034 // Use static method for one-shot changes
6035 static void use( Code _colourCode );
6036
6037 private:
6038 bool m_moved = false;
6039 };
6040
6041 std::ostream& operator << ( std::ostream& os, Colour const& );
6042
6043} // end namespace Catch
6044
6045// end catch_console_colour.h
6046// start catch_reporter_registrars.hpp
6047
6048
6049namespace Catch {
6050
6051 template<typename T>
6052 class ReporterRegistrar {
6053
6054 class ReporterFactory : public IReporterFactory {
6055
6056 IStreamingReporterPtr create( ReporterConfig const& config ) const override {
6057 return std::unique_ptr<T>( new T( config ) );
6058 }
6059
6060 std::string getDescription() const override {
6061 return T::getDescription();
6062 }
6063 };
6064
6065 public:
6066
6067 explicit ReporterRegistrar( std::string const& name ) {
6068 getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
6069 }
6070 };
6071
6072 template<typename T>
6073 class ListenerRegistrar {
6074
6075 class ListenerFactory : public IReporterFactory {
6076
6077 IStreamingReporterPtr create( ReporterConfig const& config ) const override {
6078 return std::unique_ptr<T>( new T( config ) );
6079 }
6080 std::string getDescription() const override {
6081 return std::string();
6082 }
6083 };
6084
6085 public:
6086
6087 ListenerRegistrar() {
6088 getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
6089 }
6090 };
6091}
6092
6093#if !defined(CATCH_CONFIG_DISABLE)
6094
6095#define CATCH_REGISTER_REPORTER( name, reporterType ) \
6096 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6097 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6098 namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
6099 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6100
6101#define CATCH_REGISTER_LISTENER( listenerType ) \
6102 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION \
6103 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
6104 namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
6105 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
6106#else // CATCH_CONFIG_DISABLE
6107
6108#define CATCH_REGISTER_REPORTER(name, reporterType)
6109#define CATCH_REGISTER_LISTENER(listenerType)
6110
6111#endif // CATCH_CONFIG_DISABLE
6112
6113// end catch_reporter_registrars.hpp
6114// Allow users to base their work off existing reporters
6115// start catch_reporter_compact.h
6116
6117namespace Catch {
6118
6119 struct CompactReporter : StreamingReporterBase<CompactReporter> {
6120
6121 using StreamingReporterBase::StreamingReporterBase;
6122
6123 ~CompactReporter() override;
6124
6125 static std::string getDescription();
6126
6127 void noMatchingTestCases(std::string const& spec) override;
6128
6129 void assertionStarting(AssertionInfo const&) override;
6130
6131 bool assertionEnded(AssertionStats const& _assertionStats) override;
6132
6133 void sectionEnded(SectionStats const& _sectionStats) override;
6134
6135 void testRunEnded(TestRunStats const& _testRunStats) override;
6136
6137 };
6138
6139} // end namespace Catch
6140
6141// end catch_reporter_compact.h
6142// start catch_reporter_console.h
6143
6144#if defined(_MSC_VER)
6145#pragma warning(push)
6146#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
6147 // Note that 4062 (not all labels are handled
6148 // and default is missing) is enabled
6149#endif
6150
6151namespace Catch {
6152 // Fwd decls
6153 struct SummaryColumn;
6154 class TablePrinter;
6155
6156 struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
6157 std::unique_ptr<TablePrinter> m_tablePrinter;
6158
6159 ConsoleReporter(ReporterConfig const& config);
6160 ~ConsoleReporter() override;
6161 static std::string getDescription();
6162
6163 void noMatchingTestCases(std::string const& spec) override;
6164
6165 void reportInvalidArguments(std::string const&arg) override;
6166
6167 void assertionStarting(AssertionInfo const&) override;
6168
6169 bool assertionEnded(AssertionStats const& _assertionStats) override;
6170
6171 void sectionStarting(SectionInfo const& _sectionInfo) override;
6172 void sectionEnded(SectionStats const& _sectionStats) override;
6173
6174#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6175 void benchmarkPreparing(std::string const& name) override;
6176 void benchmarkStarting(BenchmarkInfo const& info) override;
6177 void benchmarkEnded(BenchmarkStats<> const& stats) override;
6178 void benchmarkFailed(std::string const& error) override;
6179#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6180
6181 void testCaseEnded(TestCaseStats const& _testCaseStats) override;
6182 void testGroupEnded(TestGroupStats const& _testGroupStats) override;
6183 void testRunEnded(TestRunStats const& _testRunStats) override;
6184 void testRunStarting(TestRunInfo const& _testRunInfo) override;
6185 private:
6186
6187 void lazyPrint();
6188
6189 void lazyPrintWithoutClosingBenchmarkTable();
6190 void lazyPrintRunInfo();
6191 void lazyPrintGroupInfo();
6192 void printTestCaseAndSectionHeader();
6193
6194 void printClosedHeader(std::string const& _name);
6195 void printOpenHeader(std::string const& _name);
6196
6197 // if string has a : in first line will set indent to follow it on
6198 // subsequent lines
6199 void printHeaderString(std::string const& _string, std::size_t indent = 0);
6200
6201 void printTotals(Totals const& totals);
6202 void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
6203
6204 void printTotalsDivider(Totals const& totals);
6205 void printSummaryDivider();
6206 void printTestFilters();
6207
6208 private:
6209 bool m_headerPrinted = false;
6210 };
6211
6212} // end namespace Catch
6213
6214#if defined(_MSC_VER)
6215#pragma warning(pop)
6216#endif
6217
6218// end catch_reporter_console.h
6219// start catch_reporter_junit.h
6220
6221// start catch_xmlwriter.h
6222
6223#include <vector>
6224
6225namespace Catch {
6226 enum class XmlFormatting {
6227 None = 0x00,
6228 Indent = 0x01,
6229 Newline = 0x02,
6230 };
6231
6232 XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs);
6233 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs);
6234
6235 class XmlEncode {
6236 public:
6237 enum ForWhat { ForTextNodes, ForAttributes };
6238
6239 XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
6240
6241 void encodeTo( std::ostream& os ) const;
6242
6243 friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
6244
6245 private:
6246 std::string m_str;
6247 ForWhat m_forWhat;
6248 };
6249
6250 class XmlWriter {
6251 public:
6252
6253 class ScopedElement {
6254 public:
6255 ScopedElement( XmlWriter* writer, XmlFormatting fmt );
6256
6257 ScopedElement( ScopedElement&& other ) noexcept;
6258 ScopedElement& operator=( ScopedElement&& other ) noexcept;
6259
6260 ~ScopedElement();
6261
6262 ScopedElement& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent );
6263
6264 template<typename T>
6265 ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
6266 m_writer->writeAttribute( name, attribute );
6267 return *this;
6268 }
6269
6270 private:
6271 mutable XmlWriter* m_writer = nullptr;
6272 XmlFormatting m_fmt;
6273 };
6274
6275 XmlWriter( std::ostream& os = Catch::cout() );
6276 ~XmlWriter();
6277
6278 XmlWriter( XmlWriter const& ) = delete;
6279 XmlWriter& operator=( XmlWriter const& ) = delete;
6280
6281 XmlWriter& startElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6282
6283 ScopedElement scopedElement( std::string const& name, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6284
6285 XmlWriter& endElement(XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6286
6287 XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
6288
6289 XmlWriter& writeAttribute( std::string const& name, bool attribute );
6290
6291 template<typename T>
6292 XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
6293 ReusableStringStream rss;
6294 rss << attribute;
6295 return writeAttribute( name, rss.str() );
6296 }
6297
6298 XmlWriter& writeText( std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6299
6300 XmlWriter& writeComment(std::string const& text, XmlFormatting fmt = XmlFormatting::Newline | XmlFormatting::Indent);
6301
6302 void writeStylesheetRef( std::string const& url );
6303
6304 XmlWriter& writeBlankLine();
6305
6306 void ensureTagClosed();
6307
6308 private:
6309
6310 void applyFormatting(XmlFormatting fmt);
6311
6312 void writeDeclaration();
6313
6314 void newlineIfNecessary();
6315
6316 bool m_tagIsOpen = false;
6317 bool m_needsNewline = false;
6318 std::vector<std::string> m_tags;
6319 std::string m_indent;
6320 std::ostream& m_os;
6321 };
6322
6323}
6324
6325// end catch_xmlwriter.h
6326namespace Catch {
6327
6328 class JunitReporter : public CumulativeReporterBase<JunitReporter> {
6329 public:
6330 JunitReporter(ReporterConfig const& _config);
6331
6332 ~JunitReporter() override;
6333
6334 static std::string getDescription();
6335
6336 void noMatchingTestCases(std::string const& /*spec*/) override;
6337
6338 void testRunStarting(TestRunInfo const& runInfo) override;
6339
6340 void testGroupStarting(GroupInfo const& groupInfo) override;
6341
6342 void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
6343 bool assertionEnded(AssertionStats const& assertionStats) override;
6344
6345 void testCaseEnded(TestCaseStats const& testCaseStats) override;
6346
6347 void testGroupEnded(TestGroupStats const& testGroupStats) override;
6348
6349 void testRunEndedCumulative() override;
6350
6351 void writeGroup(TestGroupNode const& groupNode, double suiteTime);
6352
6353 void writeTestCase(TestCaseNode const& testCaseNode);
6354
6355 void writeSection( std::string const& className,
6356 std::string const& rootName,
6357 SectionNode const& sectionNode,
6358 bool testOkToFail );
6359
6360 void writeAssertions(SectionNode const& sectionNode);
6361 void writeAssertion(AssertionStats const& stats);
6362
6363 XmlWriter xml;
6364 Timer suiteTimer;
6365 std::string stdOutForSuite;
6366 std::string stdErrForSuite;
6367 unsigned int unexpectedExceptions = 0;
6368 bool m_okToFail = false;
6369 };
6370
6371} // end namespace Catch
6372
6373// end catch_reporter_junit.h
6374// start catch_reporter_xml.h
6375
6376namespace Catch {
6377 class XmlReporter : public StreamingReporterBase<XmlReporter> {
6378 public:
6379 XmlReporter(ReporterConfig const& _config);
6380
6381 ~XmlReporter() override;
6382
6383 static std::string getDescription();
6384
6385 virtual std::string getStylesheetRef() const;
6386
6387 void writeSourceInfo(SourceLineInfo const& sourceInfo);
6388
6389 public: // StreamingReporterBase
6390
6391 void noMatchingTestCases(std::string const& s) override;
6392
6393 void testRunStarting(TestRunInfo const& testInfo) override;
6394
6395 void testGroupStarting(GroupInfo const& groupInfo) override;
6396
6397 void testCaseStarting(TestCaseInfo const& testInfo) override;
6398
6399 void sectionStarting(SectionInfo const& sectionInfo) override;
6400
6401 void assertionStarting(AssertionInfo const&) override;
6402
6403 bool assertionEnded(AssertionStats const& assertionStats) override;
6404
6405 void sectionEnded(SectionStats const& sectionStats) override;
6406
6407 void testCaseEnded(TestCaseStats const& testCaseStats) override;
6408
6409 void testGroupEnded(TestGroupStats const& testGroupStats) override;
6410
6411 void testRunEnded(TestRunStats const& testRunStats) override;
6412
6413#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6414 void benchmarkPreparing(std::string const& name) override;
6415 void benchmarkStarting(BenchmarkInfo const&) override;
6416 void benchmarkEnded(BenchmarkStats<> const&) override;
6417 void benchmarkFailed(std::string const&) override;
6418#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
6419
6420 private:
6421 Timer m_testCaseTimer;
6422 XmlWriter m_xml;
6423 int m_sectionDepth = 0;
6424 };
6425
6426} // end namespace Catch
6427
6428// end catch_reporter_xml.h
6429
6430// end catch_external_interfaces.h
6431#endif
6432
6433#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
6434// start catch_benchmarking_all.hpp
6435
6436// A proxy header that includes all of the benchmarking headers to allow
6437// concise include of the benchmarking features. You should prefer the
6438// individual includes in standard use.
6439
6440// start catch_benchmark.hpp
6441
6442 // Benchmark
6443
6444// start catch_chronometer.hpp
6445
6446// User-facing chronometer
6447
6448
6449// start catch_clock.hpp
6450
6451// Clocks
6452
6453
6454#include <chrono>
6455#include <ratio>
6456
6457namespace Catch {
6458 namespace Benchmark {
6459 template <typename Clock>
6460 using ClockDuration = typename Clock::duration;
6461 template <typename Clock>
6462 using FloatDuration = std::chrono::duration<double, typename Clock::period>;
6463
6464 template <typename Clock>
6465 using TimePoint = typename Clock::time_point;
6466
6467 using default_clock = std::chrono::steady_clock;
6468
6469 template <typename Clock>
6470 struct now {
6471 TimePoint<Clock> operator()() const {
6472 return Clock::now();
6473 }
6474 };
6475
6476 using fp_seconds = std::chrono::duration<double, std::ratio<1>>;
6477 } // namespace Benchmark
6478} // namespace Catch
6479
6480// end catch_clock.hpp
6481// start catch_optimizer.hpp
6482
6483 // Hinting the optimizer
6484
6485
6486#if defined(_MSC_VER)
6487# include <atomic> // atomic_thread_fence
6488#endif
6489
6490namespace Catch {
6491 namespace Benchmark {
6492#if defined(__GNUC__) || defined(__clang__)
6493 template <typename T>
6494 inline void keep_memory(T* p) {
6495 asm volatile("" : : "g"(p) : "memory");
6496 }
6497 inline void keep_memory() {
6498 asm volatile("" : : : "memory");
6499 }
6500
6501 namespace Detail {
6502 inline void optimizer_barrier() { keep_memory(); }
6503 } // namespace Detail
6504#elif defined(_MSC_VER)
6505
6506#pragma optimize("", off)
6507 template <typename T>
6508 inline void keep_memory(T* p) {
6509 // thanks @milleniumbug
6510 *reinterpret_cast<char volatile*>(p) = *reinterpret_cast<char const volatile*>(p);
6511 }
6512 // TODO equivalent keep_memory()
6513#pragma optimize("", on)
6514
6515 namespace Detail {
6516 inline void optimizer_barrier() {
6517 std::atomic_thread_fence(std::memory_order_seq_cst);
6518 }
6519 } // namespace Detail
6520
6521#endif
6522
6523 template <typename T>
6524 inline void deoptimize_value(T&& x) {
6525 keep_memory(&x);
6526 }
6527
6528 template <typename Fn, typename... Args>
6529 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<!std::is_same<void, decltype(fn(args...))>::value>::type {
6530 deoptimize_value(std::forward<Fn>(fn) (std::forward<Args...>(args...)));
6531 }
6532
6533 template <typename Fn, typename... Args>
6534 inline auto invoke_deoptimized(Fn&& fn, Args&&... args) -> typename std::enable_if<std::is_same<void, decltype(fn(args...))>::value>::type {
6535 std::forward<Fn>(fn) (std::forward<Args...>(args...));
6536 }
6537 } // namespace Benchmark
6538} // namespace Catch
6539
6540// end catch_optimizer.hpp
6541// start catch_complete_invoke.hpp
6542
6543// Invoke with a special case for void
6544
6545
6546#include <type_traits>
6547#include <utility>
6548
6549namespace Catch {
6550 namespace Benchmark {
6551 namespace Detail {
6552 template <typename T>
6553 struct CompleteType { using type = T; };
6554 template <>
6555 struct CompleteType<void> { struct type {}; };
6556
6557 template <typename T>
6558 using CompleteType_t = typename CompleteType<T>::type;
6559
6560 template <typename Result>
6561 struct CompleteInvoker {
6562 template <typename Fun, typename... Args>
6563 static Result invoke(Fun&& fun, Args&&... args) {
6564 return std::forward<Fun>(fun)(std::forward<Args>(args)...);
6565 }
6566 };
6567 template <>
6568 struct CompleteInvoker<void> {
6569 template <typename Fun, typename... Args>
6570 static CompleteType_t<void> invoke(Fun&& fun, Args&&... args) {
6571 std::forward<Fun>(fun)(std::forward<Args>(args)...);
6572 return {};
6573 }
6574 };
6575
6576 // invoke and not return void :(
6577 template <typename Fun, typename... Args>
6578 CompleteType_t<FunctionReturnType<Fun, Args...>> complete_invoke(Fun&& fun, Args&&... args) {
6579 return CompleteInvoker<FunctionReturnType<Fun, Args...>>::invoke(std::forward<Fun>(fun), std::forward<Args>(args)...);
6580 }
6581
6582 const std::string benchmarkErrorMsg = "a benchmark failed to run successfully";
6583 } // namespace Detail
6584
6585 template <typename Fun>
6586 Detail::CompleteType_t<FunctionReturnType<Fun>> user_code(Fun&& fun) {
6587 CATCH_TRY{
6588 return Detail::complete_invoke(std::forward<Fun>(fun));
6589 } CATCH_CATCH_ALL{
6590 getResultCapture().benchmarkFailed(translateActiveException());
6591 CATCH_RUNTIME_ERROR(Detail::benchmarkErrorMsg);
6592 }
6593 }
6594 } // namespace Benchmark
6595} // namespace Catch
6596
6597// end catch_complete_invoke.hpp
6598namespace Catch {
6599 namespace Benchmark {
6600 namespace Detail {
6601 struct ChronometerConcept {
6602 virtual void start() = 0;
6603 virtual void finish() = 0;
6604 virtual ~ChronometerConcept() = default;
6605 };
6606 template <typename Clock>
6607 struct ChronometerModel final : public ChronometerConcept {
6608 void start() override { started = Clock::now(); }
6609 void finish() override { finished = Clock::now(); }
6610
6611 ClockDuration<Clock> elapsed() const { return finished - started; }
6612
6613 TimePoint<Clock> started;
6614 TimePoint<Clock> finished;
6615 };
6616 } // namespace Detail
6617
6618 struct Chronometer {
6619 public:
6620 template <typename Fun>
6621 void measure(Fun&& fun) { measure(std::forward<Fun>(fun), is_callable<Fun(int)>()); }
6622
6623 int runs() const { return k; }
6624
6625 Chronometer(Detail::ChronometerConcept& meter, int k)
6626 : impl(&meter)
6627 , k(k) {}
6628
6629 private:
6630 template <typename Fun>
6631 void measure(Fun&& fun, std::false_type) {
6632 measure([&fun](int) { return fun(); }, std::true_type());
6633 }
6634
6635 template <typename Fun>
6636 void measure(Fun&& fun, std::true_type) {
6637 Detail::optimizer_barrier();
6638 impl->start();
6639 for (int i = 0; i < k; ++i) invoke_deoptimized(fun, i);
6640 impl->finish();
6641 Detail::optimizer_barrier();
6642 }
6643
6644 Detail::ChronometerConcept* impl;
6645 int k;
6646 };
6647 } // namespace Benchmark
6648} // namespace Catch
6649
6650// end catch_chronometer.hpp
6651// start catch_environment.hpp
6652
6653// Environment information
6654
6655
6656namespace Catch {
6657 namespace Benchmark {
6658 template <typename Duration>
6659 struct EnvironmentEstimate {
6660 Duration mean;
6661 OutlierClassification outliers;
6662
6663 template <typename Duration2>
6664 operator EnvironmentEstimate<Duration2>() const {
6665 return { mean, outliers };
6666 }
6667 };
6668 template <typename Clock>
6669 struct Environment {
6670 using clock_type = Clock;
6671 EnvironmentEstimate<FloatDuration<Clock>> clock_resolution;
6672 EnvironmentEstimate<FloatDuration<Clock>> clock_cost;
6673 };
6674 } // namespace Benchmark
6675} // namespace Catch
6676
6677// end catch_environment.hpp
6678// start catch_execution_plan.hpp
6679
6680 // Execution plan
6681
6682
6683// start catch_benchmark_function.hpp
6684
6685 // Dumb std::function implementation for consistent call overhead
6686
6687
6688#include <cassert>
6689#include <type_traits>
6690#include <utility>
6691#include <memory>
6692
6693namespace Catch {
6694 namespace Benchmark {
6695 namespace Detail {
6696 template <typename T>
6697 using Decay = typename std::decay<T>::type;
6698 template <typename T, typename U>
6699 struct is_related
6700 : std::is_same<Decay<T>, Decay<U>> {};
6701
6709 struct BenchmarkFunction {
6710 private:
6711 struct callable {
6712 virtual void call(Chronometer meter) const = 0;
6713 virtual callable* clone() const = 0;
6714 virtual ~callable() = default;
6715 };
6716 template <typename Fun>
6717 struct model : public callable {
6718 model(Fun&& fun) : fun(std::move(fun)) {}
6719 model(Fun const& fun) : fun(fun) {}
6720
6721 model<Fun>* clone() const override { return new model<Fun>(*this); }
6722
6723 void call(Chronometer meter) const override {
6724 call(meter, is_callable<Fun(Chronometer)>());
6725 }
6726 void call(Chronometer meter, std::true_type) const {
6727 fun(meter);
6728 }
6729 void call(Chronometer meter, std::false_type) const {
6730 meter.measure(fun);
6731 }
6732
6733 Fun fun;
6734 };
6735
6736 struct do_nothing { void operator()() const {} };
6737
6738 template <typename T>
6739 BenchmarkFunction(model<T>* c) : f(c) {}
6740
6741 public:
6742 BenchmarkFunction()
6743 : f(new model<do_nothing>{ {} }) {}
6744
6745 template <typename Fun,
6746 typename std::enable_if<!is_related<Fun, BenchmarkFunction>::value, int>::type = 0>
6747 BenchmarkFunction(Fun&& fun)
6748 : f(new model<typename std::decay<Fun>::type>(std::forward<Fun>(fun))) {}
6749
6750 BenchmarkFunction(BenchmarkFunction&& that)
6751 : f(std::move(that.f)) {}
6752
6753 BenchmarkFunction(BenchmarkFunction const& that)
6754 : f(that.f->clone()) {}
6755
6756 BenchmarkFunction& operator=(BenchmarkFunction&& that) {
6757 f = std::move(that.f);
6758 return *this;
6759 }
6760
6761 BenchmarkFunction& operator=(BenchmarkFunction const& that) {
6762 f.reset(that.f->clone());
6763 return *this;
6764 }
6765
6766 void operator()(Chronometer meter) const { f->call(meter); }
6767
6768 private:
6769 std::unique_ptr<callable> f;
6770 };
6771 } // namespace Detail
6772 } // namespace Benchmark
6773} // namespace Catch
6774
6775// end catch_benchmark_function.hpp
6776// start catch_repeat.hpp
6777
6778// repeat algorithm
6779
6780
6781#include <type_traits>
6782#include <utility>
6783
6784namespace Catch {
6785 namespace Benchmark {
6786 namespace Detail {
6787 template <typename Fun>
6788 struct repeater {
6789 void operator()(int k) const {
6790 for (int i = 0; i < k; ++i) {
6791 fun();
6792 }
6793 }
6794 Fun fun;
6795 };
6796 template <typename Fun>
6797 repeater<typename std::decay<Fun>::type> repeat(Fun&& fun) {
6798 return { std::forward<Fun>(fun) };
6799 }
6800 } // namespace Detail
6801 } // namespace Benchmark
6802} // namespace Catch
6803
6804// end catch_repeat.hpp
6805// start catch_run_for_at_least.hpp
6806
6807// Run a function for a minimum amount of time
6808
6809
6810// start catch_measure.hpp
6811
6812// Measure
6813
6814
6815// start catch_timing.hpp
6816
6817// Timing
6818
6819
6820#include <tuple>
6821#include <type_traits>
6822
6823namespace Catch {
6824 namespace Benchmark {
6825 template <typename Duration, typename Result>
6826 struct Timing {
6827 Duration elapsed;
6828 Result result;
6829 int iterations;
6830 };
6831 template <typename Clock, typename Func, typename... Args>
6832 using TimingOf = Timing<ClockDuration<Clock>, Detail::CompleteType_t<FunctionReturnType<Func, Args...>>>;
6833 } // namespace Benchmark
6834} // namespace Catch
6835
6836// end catch_timing.hpp
6837#include <utility>
6838
6839namespace Catch {
6840 namespace Benchmark {
6841 namespace Detail {
6842 template <typename Clock, typename Fun, typename... Args>
6843 TimingOf<Clock, Fun, Args...> measure(Fun&& fun, Args&&... args) {
6844 auto start = Clock::now();
6845 auto&& r = Detail::complete_invoke(fun, std::forward<Args>(args)...);
6846 auto end = Clock::now();
6847 auto delta = end - start;
6848 return { delta, std::forward<decltype(r)>(r), 1 };
6849 }
6850 } // namespace Detail
6851 } // namespace Benchmark
6852} // namespace Catch
6853
6854// end catch_measure.hpp
6855#include <utility>
6856#include <type_traits>
6857
6858namespace Catch {
6859 namespace Benchmark {
6860 namespace Detail {
6861 template <typename Clock, typename Fun>
6862 TimingOf<Clock, Fun, int> measure_one(Fun&& fun, int iters, std::false_type) {
6863 return Detail::measure<Clock>(fun, iters);
6864 }
6865 template <typename Clock, typename Fun>
6866 TimingOf<Clock, Fun, Chronometer> measure_one(Fun&& fun, int iters, std::true_type) {
6867 Detail::ChronometerModel<Clock> meter;
6868 auto&& result = Detail::complete_invoke(fun, Chronometer(meter, iters));
6869
6870 return { meter.elapsed(), std::move(result), iters };
6871 }
6872
6873 template <typename Clock, typename Fun>
6874 using run_for_at_least_argument_t = typename std::conditional<is_callable<Fun(Chronometer)>::value, Chronometer, int>::type;
6875
6876 struct optimized_away_error : std::exception {
6877 const char* what() const noexcept override {
6878 return "could not measure benchmark, maybe it was optimized away";
6879 }
6880 };
6881
6882 template <typename Clock, typename Fun>
6883 TimingOf<Clock, Fun, run_for_at_least_argument_t<Clock, Fun>> run_for_at_least(ClockDuration<Clock> how_long, int seed, Fun&& fun) {
6884 auto iters = seed;
6885 while (iters < (1 << 30)) {
6886 auto&& Timing = measure_one<Clock>(fun, iters, is_callable<Fun(Chronometer)>());
6887
6888 if (Timing.elapsed >= how_long) {
6889 return { Timing.elapsed, std::move(Timing.result), iters };
6890 }
6891 iters *= 2;
6892 }
6893 Catch::throw_exception(optimized_away_error{});
6894 }
6895 } // namespace Detail
6896 } // namespace Benchmark
6897} // namespace Catch
6898
6899// end catch_run_for_at_least.hpp
6900#include <algorithm>
6901#include <iterator>
6902
6903namespace Catch {
6904 namespace Benchmark {
6905 template <typename Duration>
6906 struct ExecutionPlan {
6907 int iterations_per_sample;
6908 Duration estimated_duration;
6909 Detail::BenchmarkFunction benchmark;
6910 Duration warmup_time;
6911 int warmup_iterations;
6912
6913 template <typename Duration2>
6914 operator ExecutionPlan<Duration2>() const {
6915 return { iterations_per_sample, estimated_duration, benchmark, warmup_time, warmup_iterations };
6916 }
6917
6918 template <typename Clock>
6919 std::vector<FloatDuration<Clock>> run(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
6920 // warmup a bit
6921 Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_iterations, Detail::repeat(now<Clock>{}));
6922
6923 std::vector<FloatDuration<Clock>> times;
6924 times.reserve(cfg.benchmarkSamples());
6925 std::generate_n(std::back_inserter(times), cfg.benchmarkSamples(), [this, env] {
6926 Detail::ChronometerModel<Clock> model;
6927 this->benchmark(Chronometer(model, iterations_per_sample));
6928 auto sample_time = model.elapsed() - env.clock_cost.mean;
6929 if (sample_time < FloatDuration<Clock>::zero()) sample_time = FloatDuration<Clock>::zero();
6930 return sample_time / iterations_per_sample;
6931 });
6932 return times;
6933 }
6934 };
6935 } // namespace Benchmark
6936} // namespace Catch
6937
6938// end catch_execution_plan.hpp
6939// start catch_estimate_clock.hpp
6940
6941 // Environment measurement
6942
6943
6944// start catch_stats.hpp
6945
6946// Statistical analysis tools
6947
6948
6949#include <algorithm>
6950#include <functional>
6951#include <vector>
6952#include <iterator>
6953#include <numeric>
6954#include <tuple>
6955#include <cmath>
6956#include <utility>
6957#include <cstddef>
6958#include <random>
6959
6960namespace Catch {
6961 namespace Benchmark {
6962 namespace Detail {
6963 using sample = std::vector<double>;
6964
6965 double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last);
6966
6967 template <typename Iterator>
6968 OutlierClassification classify_outliers(Iterator first, Iterator last) {
6969 std::vector<double> copy(first, last);
6970
6971 auto q1 = weighted_average_quantile(1, 4, copy.begin(), copy.end());
6972 auto q3 = weighted_average_quantile(3, 4, copy.begin(), copy.end());
6973 auto iqr = q3 - q1;
6974 auto los = q1 - (iqr * 3.);
6975 auto lom = q1 - (iqr * 1.5);
6976 auto him = q3 + (iqr * 1.5);
6977 auto his = q3 + (iqr * 3.);
6978
6979 OutlierClassification o;
6980 for (; first != last; ++first) {
6981 auto&& t = *first;
6982 if (t < los) ++o.low_severe;
6983 else if (t < lom) ++o.low_mild;
6984 else if (t > his) ++o.high_severe;
6985 else if (t > him) ++o.high_mild;
6986 ++o.samples_seen;
6987 }
6988 return o;
6989 }
6990
6991 template <typename Iterator>
6992 double mean(Iterator first, Iterator last) {
6993 auto count = last - first;
6994 double sum = std::accumulate(first, last, 0.);
6995 return sum / count;
6996 }
6997
6998 template <typename URng, typename Iterator, typename Estimator>
6999 sample resample(URng& rng, int resamples, Iterator first, Iterator last, Estimator& estimator) {
7000 auto n = last - first;
7001 std::uniform_int_distribution<decltype(n)> dist(0, n - 1);
7002
7003 sample out;
7004 out.reserve(resamples);
7005 std::generate_n(std::back_inserter(out), resamples, [n, first, &estimator, &dist, &rng] {
7006 std::vector<double> resampled;
7007 resampled.reserve(n);
7008 std::generate_n(std::back_inserter(resampled), n, [first, &dist, &rng] { return first[dist(rng)]; });
7009 return estimator(resampled.begin(), resampled.end());
7010 });
7011 std::sort(out.begin(), out.end());
7012 return out;
7013 }
7014
7015 template <typename Estimator, typename Iterator>
7016 sample jackknife(Estimator&& estimator, Iterator first, Iterator last) {
7017 auto n = last - first;
7018 auto second = std::next(first);
7019 sample results;
7020 results.reserve(n);
7021
7022 for (auto it = first; it != last; ++it) {
7023 std::iter_swap(it, first);
7024 results.push_back(estimator(second, last));
7025 }
7026
7027 return results;
7028 }
7029
7030 inline double normal_cdf(double x) {
7031 return std::erfc(-x / std::sqrt(2.0)) / 2.0;
7032 }
7033
7034 double erfc_inv(double x);
7035
7036 double normal_quantile(double p);
7037
7038 template <typename Iterator, typename Estimator>
7039 Estimate<double> bootstrap(double confidence_level, Iterator first, Iterator last, sample const& resample, Estimator&& estimator) {
7040 auto n_samples = last - first;
7041
7042 double point = estimator(first, last);
7043 // Degenerate case with a single sample
7044 if (n_samples == 1) return { point, point, point, confidence_level };
7045
7046 sample jack = jackknife(estimator, first, last);
7047 double jack_mean = mean(jack.begin(), jack.end());
7048 double sum_squares, sum_cubes;
7049 std::tie(sum_squares, sum_cubes) = std::accumulate(jack.begin(), jack.end(), std::make_pair(0., 0.), [jack_mean](std::pair<double, double> sqcb, double x) -> std::pair<double, double> {
7050 auto d = jack_mean - x;
7051 auto d2 = d * d;
7052 auto d3 = d2 * d;
7053 return { sqcb.first + d2, sqcb.second + d3 };
7054 });
7055
7056 double accel = sum_cubes / (6 * std::pow(sum_squares, 1.5));
7057 int n = static_cast<int>(resample.size());
7058 double prob_n = std::count_if(resample.begin(), resample.end(), [point](double x) { return x < point; }) / (double)n;
7059 // degenerate case with uniform samples
7060 if (prob_n == 0) return { point, point, point, confidence_level };
7061
7062 double bias = normal_quantile(prob_n);
7063 double z1 = normal_quantile((1. - confidence_level) / 2.);
7064
7065 auto cumn = [n](double x) -> int {
7066 return std::lround(normal_cdf(x) * n); };
7067 auto a = [bias, accel](double b) { return bias + b / (1. - accel * b); };
7068 double b1 = bias + z1;
7069 double b2 = bias - z1;
7070 double a1 = a(b1);
7071 double a2 = a(b2);
7072 auto lo = (std::max)(cumn(a1), 0);
7073 auto hi = (std::min)(cumn(a2), n - 1);
7074
7075 return { point, resample[lo], resample[hi], confidence_level };
7076 }
7077
7078 double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n);
7079
7080 struct bootstrap_analysis {
7081 Estimate<double> mean;
7082 Estimate<double> standard_deviation;
7083 double outlier_variance;
7084 };
7085
7086 bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last);
7087 } // namespace Detail
7088 } // namespace Benchmark
7089} // namespace Catch
7090
7091// end catch_stats.hpp
7092#include <algorithm>
7093#include <iterator>
7094#include <tuple>
7095#include <vector>
7096#include <cmath>
7097
7098namespace Catch {
7099 namespace Benchmark {
7100 namespace Detail {
7101 template <typename Clock>
7102 std::vector<double> resolution(int k) {
7103 std::vector<TimePoint<Clock>> times;
7104 times.reserve(k + 1);
7105 std::generate_n(std::back_inserter(times), k + 1, now<Clock>{});
7106
7107 std::vector<double> deltas;
7108 deltas.reserve(k);
7109 std::transform(std::next(times.begin()), times.end(), times.begin(),
7110 std::back_inserter(deltas),
7111 [](TimePoint<Clock> a, TimePoint<Clock> b) { return static_cast<double>((a - b).count()); });
7112
7113 return deltas;
7114 }
7115
7116 const auto warmup_iterations = 10000;
7117 const auto warmup_time = std::chrono::milliseconds(100);
7118 const auto minimum_ticks = 1000;
7119 const auto warmup_seed = 10000;
7120 const auto clock_resolution_estimation_time = std::chrono::milliseconds(500);
7121 const auto clock_cost_estimation_time_limit = std::chrono::seconds(1);
7122 const auto clock_cost_estimation_tick_limit = 100000;
7123 const auto clock_cost_estimation_time = std::chrono::milliseconds(10);
7124 const auto clock_cost_estimation_iterations = 10000;
7125
7126 template <typename Clock>
7127 int warmup() {
7128 return run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(warmup_time), warmup_seed, &resolution<Clock>)
7129 .iterations;
7130 }
7131 template <typename Clock>
7132 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_resolution(int iterations) {
7133 auto r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_resolution_estimation_time), iterations, &resolution<Clock>)
7134 .result;
7135 return {
7136 FloatDuration<Clock>(mean(r.begin(), r.end())),
7137 classify_outliers(r.begin(), r.end()),
7138 };
7139 }
7140 template <typename Clock>
7141 EnvironmentEstimate<FloatDuration<Clock>> estimate_clock_cost(FloatDuration<Clock> resolution) {
7142 auto time_limit = (std::min)(
7143 resolution * clock_cost_estimation_tick_limit,
7144 FloatDuration<Clock>(clock_cost_estimation_time_limit));
7145 auto time_clock = [](int k) {
7146 return Detail::measure<Clock>([k] {
7147 for (int i = 0; i < k; ++i) {
7148 volatile auto ignored = Clock::now();
7149 (void)ignored;
7150 }
7151 }).elapsed;
7152 };
7153 time_clock(1);
7154 int iters = clock_cost_estimation_iterations;
7155 auto&& r = run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(clock_cost_estimation_time), iters, time_clock);
7156 std::vector<double> times;
7157 int nsamples = static_cast<int>(std::ceil(time_limit / r.elapsed));
7158 times.reserve(nsamples);
7159 std::generate_n(std::back_inserter(times), nsamples, [time_clock, &r] {
7160 return static_cast<double>((time_clock(r.iterations) / r.iterations).count());
7161 });
7162 return {
7163 FloatDuration<Clock>(mean(times.begin(), times.end())),
7164 classify_outliers(times.begin(), times.end()),
7165 };
7166 }
7167
7168 template <typename Clock>
7169 Environment<FloatDuration<Clock>> measure_environment() {
7170 static Environment<FloatDuration<Clock>>* env = nullptr;
7171 if (env) {
7172 return *env;
7173 }
7174
7175 auto iters = Detail::warmup<Clock>();
7176 auto resolution = Detail::estimate_clock_resolution<Clock>(iters);
7177 auto cost = Detail::estimate_clock_cost<Clock>(resolution.mean);
7178
7179 env = new Environment<FloatDuration<Clock>>{ resolution, cost };
7180 return *env;
7181 }
7182 } // namespace Detail
7183 } // namespace Benchmark
7184} // namespace Catch
7185
7186// end catch_estimate_clock.hpp
7187// start catch_analyse.hpp
7188
7189 // Run and analyse one benchmark
7190
7191
7192// start catch_sample_analysis.hpp
7193
7194// Benchmark results
7195
7196
7197#include <algorithm>
7198#include <vector>
7199#include <string>
7200#include <iterator>
7201
7202namespace Catch {
7203 namespace Benchmark {
7204 template <typename Duration>
7205 struct SampleAnalysis {
7206 std::vector<Duration> samples;
7207 Estimate<Duration> mean;
7208 Estimate<Duration> standard_deviation;
7209 OutlierClassification outliers;
7210 double outlier_variance;
7211
7212 template <typename Duration2>
7213 operator SampleAnalysis<Duration2>() const {
7214 std::vector<Duration2> samples2;
7215 samples2.reserve(samples.size());
7216 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](Duration d) { return Duration2(d); });
7217 return {
7218 std::move(samples2),
7219 mean,
7220 standard_deviation,
7221 outliers,
7222 outlier_variance,
7223 };
7224 }
7225 };
7226 } // namespace Benchmark
7227} // namespace Catch
7228
7229// end catch_sample_analysis.hpp
7230#include <algorithm>
7231#include <iterator>
7232#include <vector>
7233
7234namespace Catch {
7235 namespace Benchmark {
7236 namespace Detail {
7237 template <typename Duration, typename Iterator>
7238 SampleAnalysis<Duration> analyse(const IConfig &cfg, Environment<Duration>, Iterator first, Iterator last) {
7239 if (!cfg.benchmarkNoAnalysis()) {
7240 std::vector<double> samples;
7241 samples.reserve(last - first);
7242 std::transform(first, last, std::back_inserter(samples), [](Duration d) { return d.count(); });
7243
7244 auto analysis = Catch::Benchmark::Detail::analyse_samples(cfg.benchmarkConfidenceInterval(), cfg.benchmarkResamples(), samples.begin(), samples.end());
7245 auto outliers = Catch::Benchmark::Detail::classify_outliers(samples.begin(), samples.end());
7246
7247 auto wrap_estimate = [](Estimate<double> e) {
7248 return Estimate<Duration> {
7249 Duration(e.point),
7250 Duration(e.lower_bound),
7251 Duration(e.upper_bound),
7252 e.confidence_interval,
7253 };
7254 };
7255 std::vector<Duration> samples2;
7256 samples2.reserve(samples.size());
7257 std::transform(samples.begin(), samples.end(), std::back_inserter(samples2), [](double d) { return Duration(d); });
7258 return {
7259 std::move(samples2),
7260 wrap_estimate(analysis.mean),
7261 wrap_estimate(analysis.standard_deviation),
7262 outliers,
7263 analysis.outlier_variance,
7264 };
7265 } else {
7266 std::vector<Duration> samples;
7267 samples.reserve(last - first);
7268
7269 Duration mean = Duration(0);
7270 int i = 0;
7271 for (auto it = first; it < last; ++it, ++i) {
7272 samples.push_back(Duration(*it));
7273 mean += Duration(*it);
7274 }
7275 mean /= i;
7276
7277 return {
7278 std::move(samples),
7279 Estimate<Duration>{mean, mean, mean, 0.0},
7280 Estimate<Duration>{Duration(0), Duration(0), Duration(0), 0.0},
7281 OutlierClassification{},
7282 0.0
7283 };
7284 }
7285 }
7286 } // namespace Detail
7287 } // namespace Benchmark
7288} // namespace Catch
7289
7290// end catch_analyse.hpp
7291#include <algorithm>
7292#include <functional>
7293#include <string>
7294#include <vector>
7295#include <cmath>
7296
7297namespace Catch {
7298 namespace Benchmark {
7299 struct Benchmark {
7300 Benchmark(std::string &&name)
7301 : name(std::move(name)) {}
7302
7303 template <class FUN>
7304 Benchmark(std::string &&name, FUN &&func)
7305 : fun(std::move(func)), name(std::move(name)) {}
7306
7307 template <typename Clock>
7308 ExecutionPlan<FloatDuration<Clock>> prepare(const IConfig &cfg, Environment<FloatDuration<Clock>> env) const {
7309 auto min_time = env.clock_resolution.mean * Detail::minimum_ticks;
7310 auto run_time = std::max(min_time, std::chrono::duration_cast<decltype(min_time)>(cfg.benchmarkWarmupTime()));
7311 auto&& test = Detail::run_for_at_least<Clock>(std::chrono::duration_cast<ClockDuration<Clock>>(run_time), 1, fun);
7312 int new_iters = static_cast<int>(std::ceil(min_time * test.iterations / test.elapsed));
7313 return { new_iters, test.elapsed / test.iterations * new_iters * cfg.benchmarkSamples(), fun, std::chrono::duration_cast<FloatDuration<Clock>>(cfg.benchmarkWarmupTime()), Detail::warmup_iterations };
7314 }
7315
7316 template <typename Clock = default_clock>
7317 void run() {
7318 IConfigPtr cfg = getCurrentContext().getConfig();
7319
7320 auto env = Detail::measure_environment<Clock>();
7321
7322 getResultCapture().benchmarkPreparing(name);
7323 CATCH_TRY{
7324 auto plan = user_code([&] {
7325 return prepare<Clock>(*cfg, env);
7326 });
7327
7328 BenchmarkInfo info {
7329 name,
7330 plan.estimated_duration.count(),
7331 plan.iterations_per_sample,
7332 cfg->benchmarkSamples(),
7333 cfg->benchmarkResamples(),
7334 env.clock_resolution.mean.count(),
7335 env.clock_cost.mean.count()
7336 };
7337
7338 getResultCapture().benchmarkStarting(info);
7339
7340 auto samples = user_code([&] {
7341 return plan.template run<Clock>(*cfg, env);
7342 });
7343
7344 auto analysis = Detail::analyse(*cfg, env, samples.begin(), samples.end());
7345 BenchmarkStats<FloatDuration<Clock>> stats{ info, analysis.samples, analysis.mean, analysis.standard_deviation, analysis.outliers, analysis.outlier_variance };
7346 getResultCapture().benchmarkEnded(stats);
7347
7348 } CATCH_CATCH_ALL{
7349 if (translateActiveException() != Detail::benchmarkErrorMsg) // benchmark errors have been reported, otherwise rethrow.
7350 std::rethrow_exception(std::current_exception());
7351 }
7352 }
7353
7354 // sets lambda to be used in fun *and* executes benchmark!
7355 template <typename Fun,
7356 typename std::enable_if<!Detail::is_related<Fun, Benchmark>::value, int>::type = 0>
7357 Benchmark & operator=(Fun func) {
7358 fun = Detail::BenchmarkFunction(func);
7359 run();
7360 return *this;
7361 }
7362
7363 explicit operator bool() {
7364 return true;
7365 }
7366
7367 private:
7368 Detail::BenchmarkFunction fun;
7369 std::string name;
7370 };
7371 }
7372} // namespace Catch
7373
7374#define INTERNAL_CATCH_GET_1_ARG(arg1, arg2, ...) arg1
7375#define INTERNAL_CATCH_GET_2_ARG(arg1, arg2, ...) arg2
7376
7377#define INTERNAL_CATCH_BENCHMARK(BenchmarkName, name, benchmarkIndex)\
7378 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7379 BenchmarkName = [&](int benchmarkIndex)
7380
7381#define INTERNAL_CATCH_BENCHMARK_ADVANCED(BenchmarkName, name)\
7382 if( Catch::Benchmark::Benchmark BenchmarkName{name} ) \
7383 BenchmarkName = [&]
7384
7385// end catch_benchmark.hpp
7386// start catch_constructor.hpp
7387
7388// Constructor and destructor helpers
7389
7390
7391#include <type_traits>
7392
7393namespace Catch {
7394 namespace Benchmark {
7395 namespace Detail {
7396 template <typename T, bool Destruct>
7397 struct ObjectStorage
7398 {
7399 ObjectStorage() : data() {}
7400
7401 ObjectStorage(const ObjectStorage& other)
7402 {
7403 new(&data) T(other.stored_object());
7404 }
7405
7406 ObjectStorage(ObjectStorage&& other)
7407 {
7408 new(&data) T(std::move(other.stored_object()));
7409 }
7410
7411 ~ObjectStorage() { destruct_on_exit<T>(); }
7412
7413 template <typename... Args>
7414 void construct(Args&&... args)
7415 {
7416 new (&data) T(std::forward<Args>(args)...);
7417 }
7418
7419 template <bool AllowManualDestruction = !Destruct>
7420 typename std::enable_if<AllowManualDestruction>::type destruct()
7421 {
7422 stored_object().~T();
7423 }
7424
7425 private:
7426 // If this is a constructor benchmark, destruct the underlying object
7427 template <typename U>
7428 void destruct_on_exit(typename std::enable_if<Destruct, U>::type* = 0) { destruct<true>(); }
7429 // Otherwise, don't
7430 template <typename U>
7431 void destruct_on_exit(typename std::enable_if<!Destruct, U>::type* = 0) { }
7432
7433 T& stored_object() {
7434 return *static_cast<T*>(static_cast<void*>(&data));
7435 }
7436
7437 T const& stored_object() const {
7438 return *static_cast<T*>(static_cast<void*>(&data));
7439 }
7440
7441 struct { alignas(T) unsigned char data[sizeof(T)]; } data;
7442 };
7443 }
7444
7445 template <typename T>
7446 using storage_for = Detail::ObjectStorage<T, true>;
7447
7448 template <typename T>
7449 using destructable_object = Detail::ObjectStorage<T, false>;
7450 }
7451}
7452
7453// end catch_constructor.hpp
7454// end catch_benchmarking_all.hpp
7455#endif
7456
7457#endif // ! CATCH_CONFIG_IMPL_ONLY
7458
7459#ifdef CATCH_IMPL
7460// start catch_impl.hpp
7461
7462#ifdef __clang__
7463#pragma clang diagnostic push
7464#pragma clang diagnostic ignored "-Wweak-vtables"
7465#endif
7466
7467// Keep these here for external reporters
7468// start catch_test_case_tracker.h
7469
7470#include <string>
7471#include <vector>
7472#include <memory>
7473
7474namespace Catch {
7475namespace TestCaseTracking {
7476
7477 struct NameAndLocation {
7478 std::string name;
7479 SourceLineInfo location;
7480
7481 NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
7482 friend bool operator==(NameAndLocation const& lhs, NameAndLocation const& rhs) {
7483 return lhs.name == rhs.name
7484 && lhs.location == rhs.location;
7485 }
7486 };
7487
7488 class ITracker;
7489
7490 using ITrackerPtr = std::shared_ptr<ITracker>;
7491
7492 class ITracker {
7493 NameAndLocation m_nameAndLocation;
7494
7495 public:
7496 ITracker(NameAndLocation const& nameAndLoc) :
7497 m_nameAndLocation(nameAndLoc)
7498 {}
7499
7500 // static queries
7501 NameAndLocation const& nameAndLocation() const {
7502 return m_nameAndLocation;
7503 }
7504
7505 virtual ~ITracker();
7506
7507 // dynamic queries
7508 virtual bool isComplete() const = 0; // Successfully completed or failed
7509 virtual bool isSuccessfullyCompleted() const = 0;
7510 virtual bool isOpen() const = 0; // Started but not complete
7511 virtual bool hasChildren() const = 0;
7512 virtual bool hasStarted() const = 0;
7513
7514 virtual ITracker& parent() = 0;
7515
7516 // actions
7517 virtual void close() = 0; // Successfully complete
7518 virtual void fail() = 0;
7519 virtual void markAsNeedingAnotherRun() = 0;
7520
7521 virtual void addChild( ITrackerPtr const& child ) = 0;
7522 virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
7523 virtual void openChild() = 0;
7524
7525 // Debug/ checking
7526 virtual bool isSectionTracker() const = 0;
7527 virtual bool isGeneratorTracker() const = 0;
7528 };
7529
7530 class TrackerContext {
7531
7532 enum RunState {
7533 NotStarted,
7534 Executing,
7535 CompletedCycle
7536 };
7537
7538 ITrackerPtr m_rootTracker;
7539 ITracker* m_currentTracker = nullptr;
7540 RunState m_runState = NotStarted;
7541
7542 public:
7543
7544 ITracker& startRun();
7545 void endRun();
7546
7547 void startCycle();
7548 void completeCycle();
7549
7550 bool completedCycle() const;
7551 ITracker& currentTracker();
7552 void setCurrentTracker( ITracker* tracker );
7553 };
7554
7555 class TrackerBase : public ITracker {
7556 protected:
7557 enum CycleState {
7558 NotStarted,
7559 Executing,
7560 ExecutingChildren,
7561 NeedsAnotherRun,
7562 CompletedSuccessfully,
7563 Failed
7564 };
7565
7566 using Children = std::vector<ITrackerPtr>;
7567 TrackerContext& m_ctx;
7568 ITracker* m_parent;
7569 Children m_children;
7570 CycleState m_runState = NotStarted;
7571
7572 public:
7573 TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7574
7575 bool isComplete() const override;
7576 bool isSuccessfullyCompleted() const override;
7577 bool isOpen() const override;
7578 bool hasChildren() const override;
7579 bool hasStarted() const override {
7580 return m_runState != NotStarted;
7581 }
7582
7583 void addChild( ITrackerPtr const& child ) override;
7584
7585 ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
7586 ITracker& parent() override;
7587
7588 void openChild() override;
7589
7590 bool isSectionTracker() const override;
7591 bool isGeneratorTracker() const override;
7592
7593 void open();
7594
7595 void close() override;
7596 void fail() override;
7597 void markAsNeedingAnotherRun() override;
7598
7599 private:
7600 void moveToParent();
7601 void moveToThis();
7602 };
7603
7604 class SectionTracker : public TrackerBase {
7605 std::vector<std::string> m_filters;
7606 std::string m_trimmed_name;
7607 public:
7608 SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
7609
7610 bool isSectionTracker() const override;
7611
7612 bool isComplete() const override;
7613
7614 static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
7615
7616 void tryOpen();
7617
7618 void addInitialFilters( std::vector<std::string> const& filters );
7619 void addNextFilters( std::vector<std::string> const& filters );
7621 std::vector<std::string> const& getFilters() const;
7623 std::string const& trimmedName() const;
7624 };
7625
7626} // namespace TestCaseTracking
7627
7628using TestCaseTracking::ITracker;
7629using TestCaseTracking::TrackerContext;
7630using TestCaseTracking::SectionTracker;
7631
7632} // namespace Catch
7633
7634// end catch_test_case_tracker.h
7635
7636// start catch_leak_detector.h
7637
7638namespace Catch {
7639
7640 struct LeakDetector {
7641 LeakDetector();
7642 ~LeakDetector();
7643 };
7644
7645}
7646// end catch_leak_detector.h
7647// Cpp files will be included in the single-header file here
7648// start catch_stats.cpp
7649
7650// Statistical analysis tools
7651
7652#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
7653
7654#include <cassert>
7655#include <random>
7656
7657#if defined(CATCH_CONFIG_USE_ASYNC)
7658#include <future>
7659#endif
7660
7661namespace {
7662 double erf_inv(double x) {
7663 // Code accompanying the article "Approximating the erfinv function" in GPU Computing Gems, Volume 2
7664 double w, p;
7665
7666 w = -log((1.0 - x) * (1.0 + x));
7667
7668 if (w < 6.250000) {
7669 w = w - 3.125000;
7670 p = -3.6444120640178196996e-21;
7671 p = -1.685059138182016589e-19 + p * w;
7672 p = 1.2858480715256400167e-18 + p * w;
7673 p = 1.115787767802518096e-17 + p * w;
7674 p = -1.333171662854620906e-16 + p * w;
7675 p = 2.0972767875968561637e-17 + p * w;
7676 p = 6.6376381343583238325e-15 + p * w;
7677 p = -4.0545662729752068639e-14 + p * w;
7678 p = -8.1519341976054721522e-14 + p * w;
7679 p = 2.6335093153082322977e-12 + p * w;
7680 p = -1.2975133253453532498e-11 + p * w;
7681 p = -5.4154120542946279317e-11 + p * w;
7682 p = 1.051212273321532285e-09 + p * w;
7683 p = -4.1126339803469836976e-09 + p * w;
7684 p = -2.9070369957882005086e-08 + p * w;
7685 p = 4.2347877827932403518e-07 + p * w;
7686 p = -1.3654692000834678645e-06 + p * w;
7687 p = -1.3882523362786468719e-05 + p * w;
7688 p = 0.0001867342080340571352 + p * w;
7689 p = -0.00074070253416626697512 + p * w;
7690 p = -0.0060336708714301490533 + p * w;
7691 p = 0.24015818242558961693 + p * w;
7692 p = 1.6536545626831027356 + p * w;
7693 } else if (w < 16.000000) {
7694 w = sqrt(w) - 3.250000;
7695 p = 2.2137376921775787049e-09;
7696 p = 9.0756561938885390979e-08 + p * w;
7697 p = -2.7517406297064545428e-07 + p * w;
7698 p = 1.8239629214389227755e-08 + p * w;
7699 p = 1.5027403968909827627e-06 + p * w;
7700 p = -4.013867526981545969e-06 + p * w;
7701 p = 2.9234449089955446044e-06 + p * w;
7702 p = 1.2475304481671778723e-05 + p * w;
7703 p = -4.7318229009055733981e-05 + p * w;
7704 p = 6.8284851459573175448e-05 + p * w;
7705 p = 2.4031110387097893999e-05 + p * w;
7706 p = -0.0003550375203628474796 + p * w;
7707 p = 0.00095328937973738049703 + p * w;
7708 p = -0.0016882755560235047313 + p * w;
7709 p = 0.0024914420961078508066 + p * w;
7710 p = -0.0037512085075692412107 + p * w;
7711 p = 0.005370914553590063617 + p * w;
7712 p = 1.0052589676941592334 + p * w;
7713 p = 3.0838856104922207635 + p * w;
7714 } else {
7715 w = sqrt(w) - 5.000000;
7716 p = -2.7109920616438573243e-11;
7717 p = -2.5556418169965252055e-10 + p * w;
7718 p = 1.5076572693500548083e-09 + p * w;
7719 p = -3.7894654401267369937e-09 + p * w;
7720 p = 7.6157012080783393804e-09 + p * w;
7721 p = -1.4960026627149240478e-08 + p * w;
7722 p = 2.9147953450901080826e-08 + p * w;
7723 p = -6.7711997758452339498e-08 + p * w;
7724 p = 2.2900482228026654717e-07 + p * w;
7725 p = -9.9298272942317002539e-07 + p * w;
7726 p = 4.5260625972231537039e-06 + p * w;
7727 p = -1.9681778105531670567e-05 + p * w;
7728 p = 7.5995277030017761139e-05 + p * w;
7729 p = -0.00021503011930044477347 + p * w;
7730 p = -0.00013871931833623122026 + p * w;
7731 p = 1.0103004648645343977 + p * w;
7732 p = 4.8499064014085844221 + p * w;
7733 }
7734 return p * x;
7735 }
7736
7737 double standard_deviation(std::vector<double>::iterator first, std::vector<double>::iterator last) {
7738 auto m = Catch::Benchmark::Detail::mean(first, last);
7739 double variance = std::accumulate(first, last, 0., [m](double a, double b) {
7740 double diff = b - m;
7741 return a + diff * diff;
7742 }) / (last - first);
7743 return std::sqrt(variance);
7744 }
7745
7746}
7747
7748namespace Catch {
7749 namespace Benchmark {
7750 namespace Detail {
7751
7752 double weighted_average_quantile(int k, int q, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7753 auto count = last - first;
7754 double idx = (count - 1) * k / static_cast<double>(q);
7755 int j = static_cast<int>(idx);
7756 double g = idx - j;
7757 std::nth_element(first, first + j, last);
7758 auto xj = first[j];
7759 if (g == 0) return xj;
7760
7761 auto xj1 = *std::min_element(first + (j + 1), last);
7762 return xj + g * (xj1 - xj);
7763 }
7764
7765 double erfc_inv(double x) {
7766 return erf_inv(1.0 - x);
7767 }
7768
7769 double normal_quantile(double p) {
7770 static const double ROOT_TWO = std::sqrt(2.0);
7771
7772 double result = 0.0;
7773 assert(p >= 0 && p <= 1);
7774 if (p < 0 || p > 1) {
7775 return result;
7776 }
7777
7778 result = -erfc_inv(2.0 * p);
7779 // result *= normal distribution standard deviation (1.0) * sqrt(2)
7780 result *= /*sd * */ ROOT_TWO;
7781 // result += normal disttribution mean (0)
7782 return result;
7783 }
7784
7785 double outlier_variance(Estimate<double> mean, Estimate<double> stddev, int n) {
7786 double sb = stddev.point;
7787 double mn = mean.point / n;
7788 double mg_min = mn / 2.;
7789 double sg = (std::min)(mg_min / 4., sb / std::sqrt(n));
7790 double sg2 = sg * sg;
7791 double sb2 = sb * sb;
7792
7793 auto c_max = [n, mn, sb2, sg2](double x) -> double {
7794 double k = mn - x;
7795 double d = k * k;
7796 double nd = n * d;
7797 double k0 = -n * nd;
7798 double k1 = sb2 - n * sg2 + nd;
7799 double det = k1 * k1 - 4 * sg2 * k0;
7800 return (int)(-2. * k0 / (k1 + std::sqrt(det)));
7801 };
7802
7803 auto var_out = [n, sb2, sg2](double c) {
7804 double nc = n - c;
7805 return (nc / n) * (sb2 - nc * sg2);
7806 };
7807
7808 return (std::min)(var_out(1), var_out((std::min)(c_max(0.), c_max(mg_min)))) / sb2;
7809 }
7810
7811 bootstrap_analysis analyse_samples(double confidence_level, int n_resamples, std::vector<double>::iterator first, std::vector<double>::iterator last) {
7812 CATCH_INTERNAL_START_WARNINGS_SUPPRESSION
7813 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
7814 static std::random_device entropy;
7815 CATCH_INTERNAL_STOP_WARNINGS_SUPPRESSION
7816
7817 auto n = static_cast<int>(last - first); // seriously, one can't use integral types without hell in C++
7818
7819 auto mean = &Detail::mean<std::vector<double>::iterator>;
7820 auto stddev = &standard_deviation;
7821
7822#if defined(CATCH_CONFIG_USE_ASYNC)
7823 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7824 auto seed = entropy();
7825 return std::async(std::launch::async, [=] {
7826 std::mt19937 rng(seed);
7827 auto resampled = resample(rng, n_resamples, first, last, f);
7828 return bootstrap(confidence_level, first, last, resampled, f);
7829 });
7830 };
7831
7832 auto mean_future = Estimate(mean);
7833 auto stddev_future = Estimate(stddev);
7834
7835 auto mean_estimate = mean_future.get();
7836 auto stddev_estimate = stddev_future.get();
7837#else
7838 auto Estimate = [=](double(*f)(std::vector<double>::iterator, std::vector<double>::iterator)) {
7839 auto seed = entropy();
7840 std::mt19937 rng(seed);
7841 auto resampled = resample(rng, n_resamples, first, last, f);
7842 return bootstrap(confidence_level, first, last, resampled, f);
7843 };
7844
7845 auto mean_estimate = Estimate(mean);
7846 auto stddev_estimate = Estimate(stddev);
7847#endif // CATCH_USE_ASYNC
7848
7849 double outlier_variance = Detail::outlier_variance(mean_estimate, stddev_estimate, n);
7850
7851 return { mean_estimate, stddev_estimate, outlier_variance };
7852 }
7853 } // namespace Detail
7854 } // namespace Benchmark
7855} // namespace Catch
7856
7857#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
7858// end catch_stats.cpp
7859// start catch_approx.cpp
7860
7861#include <cmath>
7862#include <limits>
7863
7864namespace {
7865
7866// Performs equivalent check of std::fabs(lhs - rhs) <= margin
7867// But without the subtraction to allow for INFINITY in comparison
7868bool marginComparison(double lhs, double rhs, double margin) {
7869 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
7870}
7871
7872}
7873
7874namespace Catch {
7875namespace Detail {
7876
7877 Approx::Approx ( double value )
7878 : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
7879 m_margin( 0.0 ),
7880 m_scale( 0.0 ),
7881 m_value( value )
7882 {}
7883
7884 Approx Approx::custom() {
7885 return Approx( 0 );
7886 }
7887
7888 Approx Approx::operator-() const {
7889 auto temp(*this);
7890 temp.m_value = -temp.m_value;
7891 return temp;
7892 }
7893
7894 std::string Approx::toString() const {
7895 ReusableStringStream rss;
7896 rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
7897 return rss.str();
7898 }
7899
7900 bool Approx::equalityComparisonImpl(const double other) const {
7901 // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
7902 // Thanks to Richard Harris for his help refining the scaled margin value
7903 return marginComparison(m_value, other, m_margin)
7904 || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(std::isinf(m_value)? 0 : m_value)));
7905 }
7906
7907 void Approx::setMargin(double newMargin) {
7908 CATCH_ENFORCE(newMargin >= 0,
7909 "Invalid Approx::margin: " << newMargin << '.'
7910 << " Approx::Margin has to be non-negative.");
7911 m_margin = newMargin;
7912 }
7913
7914 void Approx::setEpsilon(double newEpsilon) {
7915 CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
7916 "Invalid Approx::epsilon: " << newEpsilon << '.'
7917 << " Approx::epsilon has to be in [0, 1]");
7918 m_epsilon = newEpsilon;
7919 }
7920
7921} // end namespace Detail
7922
7923namespace literals {
7924 Detail::Approx operator "" _a(long double val) {
7925 return Detail::Approx(val);
7926 }
7927 Detail::Approx operator "" _a(unsigned long long val) {
7928 return Detail::Approx(val);
7929 }
7930} // end namespace literals
7931
7932std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
7933 return value.toString();
7934}
7935
7936} // end namespace Catch
7937// end catch_approx.cpp
7938// start catch_assertionhandler.cpp
7939
7940// start catch_debugger.h
7941
7942namespace Catch {
7943 bool isDebuggerActive();
7944}
7945
7946#ifdef CATCH_PLATFORM_MAC
7947
7948 #if defined(__i386__) || defined(__x86_64__)
7949 #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
7950 #elif defined(__aarch64__)
7951 #define CATCH_TRAP() __asm__(".inst 0xd43e0000")
7952 #endif
7953
7954#elif defined(CATCH_PLATFORM_IPHONE)
7955
7956 // use inline assembler
7957 #if defined(__i386__) || defined(__x86_64__)
7958 #define CATCH_TRAP() __asm__("int $3")
7959 #elif defined(__aarch64__)
7960 #define CATCH_TRAP() __asm__(".inst 0xd4200000")
7961 #elif defined(__arm__) && !defined(__thumb__)
7962 #define CATCH_TRAP() __asm__(".inst 0xe7f001f0")
7963 #elif defined(__arm__) && defined(__thumb__)
7964 #define CATCH_TRAP() __asm__(".inst 0xde01")
7965 #endif
7966
7967#elif defined(CATCH_PLATFORM_LINUX)
7968 // If we can use inline assembler, do it because this allows us to break
7969 // directly at the location of the failing check instead of breaking inside
7970 // raise() called from it, i.e. one stack frame below.
7971 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
7972 #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
7973 #else // Fall back to the generic way.
7974 #include <signal.h>
7975
7976 #define CATCH_TRAP() raise(SIGTRAP)
7977 #endif
7978#elif defined(_MSC_VER)
7979 #define CATCH_TRAP() __debugbreak()
7980#elif defined(__MINGW32__)
7981 extern "C" __declspec(dllimport) void __stdcall DebugBreak();
7982 #define CATCH_TRAP() DebugBreak()
7983#endif
7984
7985#ifndef CATCH_BREAK_INTO_DEBUGGER
7986 #ifdef CATCH_TRAP
7987 #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
7988 #else
7989 #define CATCH_BREAK_INTO_DEBUGGER() []{}()
7990 #endif
7991#endif
7992
7993// end catch_debugger.h
7994// start catch_run_context.h
7995
7996// start catch_fatal_condition.h
7997
7998#include <cassert>
7999
8000namespace Catch {
8001
8002 // Wrapper for platform-specific fatal error (signals/SEH) handlers
8003 //
8004 // Tries to be cooperative with other handlers, and not step over
8005 // other handlers. This means that unknown structured exceptions
8006 // are passed on, previous signal handlers are called, and so on.
8007 //
8008 // Can only be instantiated once, and assumes that once a signal
8009 // is caught, the binary will end up terminating. Thus, there
8010 class FatalConditionHandler {
8011 bool m_started = false;
8012
8013 // Install/disengage implementation for specific platform.
8014 // Should be if-defed to work on current platform, can assume
8015 // engage-disengage 1:1 pairing.
8016 void engage_platform();
8017 void disengage_platform();
8018 public:
8019 // Should also have platform-specific implementations as needed
8020 FatalConditionHandler();
8021 ~FatalConditionHandler();
8022
8023 void engage() {
8024 assert(!m_started && "Handler cannot be installed twice.");
8025 m_started = true;
8026 engage_platform();
8027 }
8028
8029 void disengage() {
8030 assert(m_started && "Handler cannot be uninstalled without being installed first");
8031 m_started = false;
8032 disengage_platform();
8033 }
8034 };
8035
8037 class FatalConditionHandlerGuard {
8038 FatalConditionHandler* m_handler;
8039 public:
8040 FatalConditionHandlerGuard(FatalConditionHandler* handler):
8041 m_handler(handler) {
8042 m_handler->engage();
8043 }
8044 ~FatalConditionHandlerGuard() {
8045 m_handler->disengage();
8046 }
8047 };
8048
8049} // end namespace Catch
8050
8051// end catch_fatal_condition.h
8052#include <string>
8053
8054namespace Catch {
8055
8056 struct IMutableContext;
8057
8059
8060 class RunContext : public IResultCapture, public IRunner {
8061
8062 public:
8063 RunContext( RunContext const& ) = delete;
8064 RunContext& operator =( RunContext const& ) = delete;
8065
8066 explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
8067
8068 ~RunContext() override;
8069
8070 void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
8071 void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
8072
8073 Totals runTest(TestCase const& testCase);
8074
8075 IConfigPtr config() const;
8076 IStreamingReporter& reporter() const;
8077
8078 public: // IResultCapture
8079
8080 // Assertion handlers
8081 void handleExpr
8082 ( AssertionInfo const& info,
8083 ITransientExpression const& expr,
8084 AssertionReaction& reaction ) override;
8085 void handleMessage
8086 ( AssertionInfo const& info,
8087 ResultWas::OfType resultType,
8088 StringRef const& message,
8089 AssertionReaction& reaction ) override;
8090 void handleUnexpectedExceptionNotThrown
8091 ( AssertionInfo const& info,
8092 AssertionReaction& reaction ) override;
8093 void handleUnexpectedInflightException
8094 ( AssertionInfo const& info,
8095 std::string const& message,
8096 AssertionReaction& reaction ) override;
8097 void handleIncomplete
8098 ( AssertionInfo const& info ) override;
8099 void handleNonExpr
8100 ( AssertionInfo const &info,
8101 ResultWas::OfType resultType,
8102 AssertionReaction &reaction ) override;
8103
8104 bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
8105
8106 void sectionEnded( SectionEndInfo const& endInfo ) override;
8107 void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
8108
8109 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
8110
8111#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
8112 void benchmarkPreparing( std::string const& name ) override;
8113 void benchmarkStarting( BenchmarkInfo const& info ) override;
8114 void benchmarkEnded( BenchmarkStats<> const& stats ) override;
8115 void benchmarkFailed( std::string const& error ) override;
8116#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
8117
8118 void pushScopedMessage( MessageInfo const& message ) override;
8119 void popScopedMessage( MessageInfo const& message ) override;
8120
8121 void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
8122
8123 std::string getCurrentTestName() const override;
8124
8125 const AssertionResult* getLastResult() const override;
8126
8127 void exceptionEarlyReported() override;
8128
8129 void handleFatalErrorCondition( StringRef message ) override;
8130
8131 bool lastAssertionPassed() override;
8132
8133 void assertionPassed() override;
8134
8135 public:
8136 // !TBD We need to do this another way!
8137 bool aborting() const final;
8138
8139 private:
8140
8141 void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
8142 void invokeActiveTestCase();
8143
8144 void resetAssertionInfo();
8145 bool testForMissingAssertions( Counts& assertions );
8146
8147 void assertionEnded( AssertionResult const& result );
8148 void reportExpr
8149 ( AssertionInfo const &info,
8150 ResultWas::OfType resultType,
8151 ITransientExpression const *expr,
8152 bool negated );
8153
8154 void populateReaction( AssertionReaction& reaction );
8155
8156 private:
8157
8158 void handleUnfinishedSections();
8159
8160 TestRunInfo m_runInfo;
8161 IMutableContext& m_context;
8162 TestCase const* m_activeTestCase = nullptr;
8163 ITracker* m_testCaseTracker = nullptr;
8164 Option<AssertionResult> m_lastResult;
8165
8166 IConfigPtr m_config;
8167 Totals m_totals;
8168 IStreamingReporterPtr m_reporter;
8169 std::vector<MessageInfo> m_messages;
8170 std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
8171 AssertionInfo m_lastAssertionInfo;
8172 std::vector<SectionEndInfo> m_unfinishedSections;
8173 std::vector<ITracker*> m_activeSections;
8174 TrackerContext m_trackerContext;
8175 FatalConditionHandler m_fatalConditionhandler;
8176 bool m_lastAssertionPassed = false;
8177 bool m_shouldReportUnexpected = true;
8178 bool m_includeSuccessfulResults;
8179 };
8180
8181 void seedRng(IConfig const& config);
8182 unsigned int rngSeed();
8183} // end namespace Catch
8184
8185// end catch_run_context.h
8186namespace Catch {
8187
8188 namespace {
8189 auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
8190 expr.streamReconstructedExpression( os );
8191 return os;
8192 }
8193 }
8194
8195 LazyExpression::LazyExpression( bool isNegated )
8196 : m_isNegated( isNegated )
8197 {}
8198
8199 LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
8200
8201 LazyExpression::operator bool() const {
8202 return m_transientExpression != nullptr;
8203 }
8204
8205 auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
8206 if( lazyExpr.m_isNegated )
8207 os << "!";
8208
8209 if( lazyExpr ) {
8210 if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
8211 os << "(" << *lazyExpr.m_transientExpression << ")";
8212 else
8213 os << *lazyExpr.m_transientExpression;
8214 }
8215 else {
8216 os << "{** error - unchecked empty expression requested **}";
8217 }
8218 return os;
8219 }
8220
8221 AssertionHandler::AssertionHandler
8222 ( StringRef const& macroName,
8223 SourceLineInfo const& lineInfo,
8224 StringRef capturedExpression,
8225 ResultDisposition::Flags resultDisposition )
8226 : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
8227 m_resultCapture( getResultCapture() )
8228 {}
8229
8230 void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
8231 m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
8232 }
8233 void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
8234 m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
8235 }
8236
8237 auto AssertionHandler::allowThrows() const -> bool {
8238 return getCurrentContext().getConfig()->allowThrows();
8239 }
8240
8241 void AssertionHandler::complete() {
8242 setCompleted();
8243 if( m_reaction.shouldDebugBreak ) {
8244
8245 // If you find your debugger stopping you here then go one level up on the
8246 // call-stack for the code that caused it (typically a failed assertion)
8247
8248 // (To go back to the test and change execution, jump over the throw, next)
8249 CATCH_BREAK_INTO_DEBUGGER();
8250 }
8251 if (m_reaction.shouldThrow) {
8252#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
8254#else
8255 CATCH_ERROR( "Test failure requires aborting test!" );
8256#endif
8257 }
8258 }
8259 void AssertionHandler::setCompleted() {
8260 m_completed = true;
8261 }
8262
8263 void AssertionHandler::handleUnexpectedInflightException() {
8264 m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
8265 }
8266
8267 void AssertionHandler::handleExceptionThrownAsExpected() {
8268 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8269 }
8270 void AssertionHandler::handleExceptionNotThrownAsExpected() {
8271 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8272 }
8273
8274 void AssertionHandler::handleUnexpectedExceptionNotThrown() {
8275 m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
8276 }
8277
8278 void AssertionHandler::handleThrowingCallSkipped() {
8279 m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
8280 }
8281
8282 // This is the overload that takes a string and infers the Equals matcher from it
8283 // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
8284 void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
8285 handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
8286 }
8287
8288} // namespace Catch
8289// end catch_assertionhandler.cpp
8290// start catch_assertionresult.cpp
8291
8292namespace Catch {
8293 AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
8294 lazyExpression(_lazyExpression),
8295 resultType(_resultType) {}
8296
8297 std::string AssertionResultData::reconstructExpression() const {
8298
8299 if( reconstructedExpression.empty() ) {
8300 if( lazyExpression ) {
8301 ReusableStringStream rss;
8302 rss << lazyExpression;
8303 reconstructedExpression = rss.str();
8304 }
8305 }
8306 return reconstructedExpression;
8307 }
8308
8309 AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
8310 : m_info( info ),
8311 m_resultData( data )
8312 {}
8313
8314 // Result was a success
8315 bool AssertionResult::succeeded() const {
8316 return Catch::isOk( m_resultData.resultType );
8317 }
8318
8319 // Result was a success, or failure is suppressed
8320 bool AssertionResult::isOk() const {
8321 return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
8322 }
8323
8324 ResultWas::OfType AssertionResult::getResultType() const {
8325 return m_resultData.resultType;
8326 }
8327
8328 bool AssertionResult::hasExpression() const {
8329 return !m_info.capturedExpression.empty();
8330 }
8331
8332 bool AssertionResult::hasMessage() const {
8333 return !m_resultData.message.empty();
8334 }
8335
8336 std::string AssertionResult::getExpression() const {
8337 // Possibly overallocating by 3 characters should be basically free
8338 std::string expr; expr.reserve(m_info.capturedExpression.size() + 3);
8339 if (isFalseTest(m_info.resultDisposition)) {
8340 expr += "!(";
8341 }
8342 expr += m_info.capturedExpression;
8343 if (isFalseTest(m_info.resultDisposition)) {
8344 expr += ')';
8345 }
8346 return expr;
8347 }
8348
8349 std::string AssertionResult::getExpressionInMacro() const {
8350 std::string expr;
8351 if( m_info.macroName.empty() )
8352 expr = static_cast<std::string>(m_info.capturedExpression);
8353 else {
8354 expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
8355 expr += m_info.macroName;
8356 expr += "( ";
8357 expr += m_info.capturedExpression;
8358 expr += " )";
8359 }
8360 return expr;
8361 }
8362
8363 bool AssertionResult::hasExpandedExpression() const {
8364 return hasExpression() && getExpandedExpression() != getExpression();
8365 }
8366
8367 std::string AssertionResult::getExpandedExpression() const {
8368 std::string expr = m_resultData.reconstructExpression();
8369 return expr.empty()
8370 ? getExpression()
8371 : expr;
8372 }
8373
8374 std::string AssertionResult::getMessage() const {
8375 return m_resultData.message;
8376 }
8377 SourceLineInfo AssertionResult::getSourceInfo() const {
8378 return m_info.lineInfo;
8379 }
8380
8381 StringRef AssertionResult::getTestMacroName() const {
8382 return m_info.macroName;
8383 }
8384
8385} // end namespace Catch
8386// end catch_assertionresult.cpp
8387// start catch_capture_matchers.cpp
8388
8389namespace Catch {
8390
8391 using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
8392
8393 // This is the general overload that takes a any string matcher
8394 // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
8395 // the Equals matcher (so the header does not mention matchers)
8396 void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
8397 std::string exceptionMessage = Catch::translateActiveException();
8398 MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
8399 handler.handleExpr( expr );
8400 }
8401
8402} // namespace Catch
8403// end catch_capture_matchers.cpp
8404// start catch_commandline.cpp
8405
8406// start catch_commandline.h
8407
8408// start catch_clara.h
8409
8410// Use Catch's value for console width (store Clara's off to the side, if present)
8411#ifdef CLARA_CONFIG_CONSOLE_WIDTH
8412#define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8413#undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8414#endif
8415#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
8416
8417#ifdef __clang__
8418#pragma clang diagnostic push
8419#pragma clang diagnostic ignored "-Wweak-vtables"
8420#pragma clang diagnostic ignored "-Wexit-time-destructors"
8421#pragma clang diagnostic ignored "-Wshadow"
8422#endif
8423
8424// start clara.hpp
8425// Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
8426//
8427// Distributed under the Boost Software License, Version 1.0. (See accompanying
8428// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8429//
8430// See https://github.com/philsquared/Clara for more details
8431
8432// Clara v1.1.5
8433
8434
8435#ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8436#define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
8437#endif
8438
8439#ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8440#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
8441#endif
8442
8443#ifndef CLARA_CONFIG_OPTIONAL_TYPE
8444#ifdef __has_include
8445#if __has_include(<optional>) && __cplusplus >= 201703L
8446#include <optional>
8447#define CLARA_CONFIG_OPTIONAL_TYPE std::optional
8448#endif
8449#endif
8450#endif
8451
8452// ----------- #included from clara_textflow.hpp -----------
8453
8454// TextFlowCpp
8455//
8456// A single-header library for wrapping and laying out basic text, by Phil Nash
8457//
8458// Distributed under the Boost Software License, Version 1.0. (See accompanying
8459// file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
8460//
8461// This project is hosted at https://github.com/philsquared/textflowcpp
8462
8463
8464#include <cassert>
8465#include <ostream>
8466#include <sstream>
8467#include <vector>
8468
8469#ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
8470#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
8471#endif
8472
8473namespace Catch {
8474namespace clara {
8475namespace TextFlow {
8476
8477inline auto isWhitespace(char c) -> bool {
8478 static std::string chars = " \t\n\r";
8479 return chars.find(c) != std::string::npos;
8480}
8481inline auto isBreakableBefore(char c) -> bool {
8482 static std::string chars = "[({<|";
8483 return chars.find(c) != std::string::npos;
8484}
8485inline auto isBreakableAfter(char c) -> bool {
8486 static std::string chars = "])}>.,:;*+-=&/\\";
8487 return chars.find(c) != std::string::npos;
8488}
8489
8490class Columns;
8491
8492class Column {
8493 std::vector<std::string> m_strings;
8494 size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
8495 size_t m_indent = 0;
8496 size_t m_initialIndent = std::string::npos;
8497
8498public:
8499 class iterator {
8500 friend Column;
8501
8502 Column const& m_column;
8503 size_t m_stringIndex = 0;
8504 size_t m_pos = 0;
8505
8506 size_t m_len = 0;
8507 size_t m_end = 0;
8508 bool m_suffix = false;
8509
8510 iterator(Column const& column, size_t stringIndex)
8511 : m_column(column),
8512 m_stringIndex(stringIndex) {}
8513
8514 auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
8515
8516 auto isBoundary(size_t at) const -> bool {
8517 assert(at > 0);
8518 assert(at <= line().size());
8519
8520 return at == line().size() ||
8521 (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
8522 isBreakableBefore(line()[at]) ||
8523 isBreakableAfter(line()[at - 1]);
8524 }
8525
8526 void calcLength() {
8527 assert(m_stringIndex < m_column.m_strings.size());
8528
8529 m_suffix = false;
8530 auto width = m_column.m_width - indent();
8531 m_end = m_pos;
8532 if (line()[m_pos] == '\n') {
8533 ++m_end;
8534 }
8535 while (m_end < line().size() && line()[m_end] != '\n')
8536 ++m_end;
8537
8538 if (m_end < m_pos + width) {
8539 m_len = m_end - m_pos;
8540 } else {
8541 size_t len = width;
8542 while (len > 0 && !isBoundary(m_pos + len))
8543 --len;
8544 while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
8545 --len;
8546
8547 if (len > 0) {
8548 m_len = len;
8549 } else {
8550 m_suffix = true;
8551 m_len = width - 1;
8552 }
8553 }
8554 }
8555
8556 auto indent() const -> size_t {
8557 auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
8558 return initial == std::string::npos ? m_column.m_indent : initial;
8559 }
8560
8561 auto addIndentAndSuffix(std::string const &plain) const -> std::string {
8562 return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
8563 }
8564
8565 public:
8566 using difference_type = std::ptrdiff_t;
8567 using value_type = std::string;
8568 using pointer = value_type * ;
8569 using reference = value_type & ;
8570 using iterator_category = std::forward_iterator_tag;
8571
8572 explicit iterator(Column const& column) : m_column(column) {
8573 assert(m_column.m_width > m_column.m_indent);
8574 assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
8575 calcLength();
8576 if (m_len == 0)
8577 m_stringIndex++; // Empty string
8578 }
8579
8580 auto operator *() const -> std::string {
8581 assert(m_stringIndex < m_column.m_strings.size());
8582 assert(m_pos <= m_end);
8583 return addIndentAndSuffix(line().substr(m_pos, m_len));
8584 }
8585
8586 auto operator ++() -> iterator& {
8587 m_pos += m_len;
8588 if (m_pos < line().size() && line()[m_pos] == '\n')
8589 m_pos += 1;
8590 else
8591 while (m_pos < line().size() && isWhitespace(line()[m_pos]))
8592 ++m_pos;
8593
8594 if (m_pos == line().size()) {
8595 m_pos = 0;
8596 ++m_stringIndex;
8597 }
8598 if (m_stringIndex < m_column.m_strings.size())
8599 calcLength();
8600 return *this;
8601 }
8602 auto operator ++(int) -> iterator {
8603 iterator prev(*this);
8604 operator++();
8605 return prev;
8606 }
8607
8608 auto operator ==(iterator const& other) const -> bool {
8609 return
8610 m_pos == other.m_pos &&
8611 m_stringIndex == other.m_stringIndex &&
8612 &m_column == &other.m_column;
8613 }
8614 auto operator !=(iterator const& other) const -> bool {
8615 return !operator==(other);
8616 }
8617 };
8618 using const_iterator = iterator;
8619
8620 explicit Column(std::string const& text) { m_strings.push_back(text); }
8621
8622 auto width(size_t newWidth) -> Column& {
8623 assert(newWidth > 0);
8624 m_width = newWidth;
8625 return *this;
8626 }
8627 auto indent(size_t newIndent) -> Column& {
8628 m_indent = newIndent;
8629 return *this;
8630 }
8631 auto initialIndent(size_t newIndent) -> Column& {
8632 m_initialIndent = newIndent;
8633 return *this;
8634 }
8635
8636 auto width() const -> size_t { return m_width; }
8637 auto begin() const -> iterator { return iterator(*this); }
8638 auto end() const -> iterator { return { *this, m_strings.size() }; }
8639
8640 inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
8641 bool first = true;
8642 for (auto line : col) {
8643 if (first)
8644 first = false;
8645 else
8646 os << "\n";
8647 os << line;
8648 }
8649 return os;
8650 }
8651
8652 auto operator + (Column const& other)->Columns;
8653
8654 auto toString() const -> std::string {
8655 std::ostringstream oss;
8656 oss << *this;
8657 return oss.str();
8658 }
8659};
8660
8661class Spacer : public Column {
8662
8663public:
8664 explicit Spacer(size_t spaceWidth) : Column("") {
8665 width(spaceWidth);
8666 }
8667};
8668
8669class Columns {
8670 std::vector<Column> m_columns;
8671
8672public:
8673
8674 class iterator {
8675 friend Columns;
8676 struct EndTag {};
8677
8678 std::vector<Column> const& m_columns;
8679 std::vector<Column::iterator> m_iterators;
8680 size_t m_activeIterators;
8681
8682 iterator(Columns const& columns, EndTag)
8683 : m_columns(columns.m_columns),
8684 m_activeIterators(0) {
8685 m_iterators.reserve(m_columns.size());
8686
8687 for (auto const& col : m_columns)
8688 m_iterators.push_back(col.end());
8689 }
8690
8691 public:
8692 using difference_type = std::ptrdiff_t;
8693 using value_type = std::string;
8694 using pointer = value_type * ;
8695 using reference = value_type & ;
8696 using iterator_category = std::forward_iterator_tag;
8697
8698 explicit iterator(Columns const& columns)
8699 : m_columns(columns.m_columns),
8700 m_activeIterators(m_columns.size()) {
8701 m_iterators.reserve(m_columns.size());
8702
8703 for (auto const& col : m_columns)
8704 m_iterators.push_back(col.begin());
8705 }
8706
8707 auto operator ==(iterator const& other) const -> bool {
8708 return m_iterators == other.m_iterators;
8709 }
8710 auto operator !=(iterator const& other) const -> bool {
8711 return m_iterators != other.m_iterators;
8712 }
8713 auto operator *() const -> std::string {
8714 std::string row, padding;
8715
8716 for (size_t i = 0; i < m_columns.size(); ++i) {
8717 auto width = m_columns[i].width();
8718 if (m_iterators[i] != m_columns[i].end()) {
8719 std::string col = *m_iterators[i];
8720 row += padding + col;
8721 if (col.size() < width)
8722 padding = std::string(width - col.size(), ' ');
8723 else
8724 padding = "";
8725 } else {
8726 padding += std::string(width, ' ');
8727 }
8728 }
8729 return row;
8730 }
8731 auto operator ++() -> iterator& {
8732 for (size_t i = 0; i < m_columns.size(); ++i) {
8733 if (m_iterators[i] != m_columns[i].end())
8734 ++m_iterators[i];
8735 }
8736 return *this;
8737 }
8738 auto operator ++(int) -> iterator {
8739 iterator prev(*this);
8740 operator++();
8741 return prev;
8742 }
8743 };
8744 using const_iterator = iterator;
8745
8746 auto begin() const -> iterator { return iterator(*this); }
8747 auto end() const -> iterator { return { *this, iterator::EndTag() }; }
8748
8749 auto operator += (Column const& col) -> Columns& {
8750 m_columns.push_back(col);
8751 return *this;
8752 }
8753 auto operator + (Column const& col) -> Columns {
8754 Columns combined = *this;
8755 combined += col;
8756 return combined;
8757 }
8758
8759 inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
8760
8761 bool first = true;
8762 for (auto line : cols) {
8763 if (first)
8764 first = false;
8765 else
8766 os << "\n";
8767 os << line;
8768 }
8769 return os;
8770 }
8771
8772 auto toString() const -> std::string {
8773 std::ostringstream oss;
8774 oss << *this;
8775 return oss.str();
8776 }
8777};
8778
8779inline auto Column::operator + (Column const& other) -> Columns {
8780 Columns cols;
8781 cols += *this;
8782 cols += other;
8783 return cols;
8784}
8785}
8786
8787}
8788}
8789
8790// ----------- end of #include from clara_textflow.hpp -----------
8791// ........... back in clara.hpp
8792
8793#include <cctype>
8794#include <string>
8795#include <memory>
8796#include <set>
8797#include <algorithm>
8798
8799#if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
8800#define CATCH_PLATFORM_WINDOWS
8801#endif
8802
8803namespace Catch { namespace clara {
8804namespace detail {
8805
8806 // Traits for extracting arg and return type of lambdas (for single argument lambdas)
8807 template<typename L>
8808 struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
8809
8810 template<typename ClassT, typename ReturnT, typename... Args>
8811 struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
8812 static const bool isValid = false;
8813 };
8814
8815 template<typename ClassT, typename ReturnT, typename ArgT>
8816 struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
8817 static const bool isValid = true;
8818 using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
8819 using ReturnType = ReturnT;
8820 };
8821
8822 class TokenStream;
8823
8824 // Transport for raw args (copied from main args, or supplied via init list for testing)
8825 class Args {
8826 friend TokenStream;
8827 std::string m_exeName;
8828 std::vector<std::string> m_args;
8829
8830 public:
8831 Args( int argc, char const* const* argv )
8832 : m_exeName(argv[0]),
8833 m_args(argv + 1, argv + argc) {}
8834
8835 Args( std::initializer_list<std::string> args )
8836 : m_exeName( *args.begin() ),
8837 m_args( args.begin()+1, args.end() )
8838 {}
8839
8840 auto exeName() const -> std::string {
8841 return m_exeName;
8842 }
8843 };
8844
8845 // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
8846 // may encode an option + its argument if the : or = form is used
8847 enum class TokenType {
8848 Option, Argument
8849 };
8850 struct Token {
8851 TokenType type;
8852 std::string token;
8853 };
8854
8855 inline auto isOptPrefix( char c ) -> bool {
8856 return c == '-'
8857#ifdef CATCH_PLATFORM_WINDOWS
8858 || c == '/'
8859#endif
8860 ;
8861 }
8862
8863 // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
8864 class TokenStream {
8865 using Iterator = std::vector<std::string>::const_iterator;
8866 Iterator it;
8867 Iterator itEnd;
8868 std::vector<Token> m_tokenBuffer;
8869
8870 void loadBuffer() {
8871 m_tokenBuffer.resize( 0 );
8872
8873 // Skip any empty strings
8874 while( it != itEnd && it->empty() )
8875 ++it;
8876
8877 if( it != itEnd ) {
8878 auto const &next = *it;
8879 if( isOptPrefix( next[0] ) ) {
8880 auto delimiterPos = next.find_first_of( " :=" );
8881 if( delimiterPos != std::string::npos ) {
8882 m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
8883 m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
8884 } else {
8885 if( next[1] != '-' && next.size() > 2 ) {
8886 std::string opt = "- ";
8887 for( size_t i = 1; i < next.size(); ++i ) {
8888 opt[1] = next[i];
8889 m_tokenBuffer.push_back( { TokenType::Option, opt } );
8890 }
8891 } else {
8892 m_tokenBuffer.push_back( { TokenType::Option, next } );
8893 }
8894 }
8895 } else {
8896 m_tokenBuffer.push_back( { TokenType::Argument, next } );
8897 }
8898 }
8899 }
8900
8901 public:
8902 explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
8903
8904 TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
8905 loadBuffer();
8906 }
8907
8908 explicit operator bool() const {
8909 return !m_tokenBuffer.empty() || it != itEnd;
8910 }
8911
8912 auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
8913
8914 auto operator*() const -> Token {
8915 assert( !m_tokenBuffer.empty() );
8916 return m_tokenBuffer.front();
8917 }
8918
8919 auto operator->() const -> Token const * {
8920 assert( !m_tokenBuffer.empty() );
8921 return &m_tokenBuffer.front();
8922 }
8923
8924 auto operator++() -> TokenStream & {
8925 if( m_tokenBuffer.size() >= 2 ) {
8926 m_tokenBuffer.erase( m_tokenBuffer.begin() );
8927 } else {
8928 if( it != itEnd )
8929 ++it;
8930 loadBuffer();
8931 }
8932 return *this;
8933 }
8934 };
8935
8936 class ResultBase {
8937 public:
8938 enum Type {
8939 Ok, LogicError, RuntimeError
8940 };
8941
8942 protected:
8943 ResultBase( Type type ) : m_type( type ) {}
8944 virtual ~ResultBase() = default;
8945
8946 virtual void enforceOk() const = 0;
8947
8948 Type m_type;
8949 };
8950
8951 template<typename T>
8952 class ResultValueBase : public ResultBase {
8953 public:
8954 auto value() const -> T const & {
8955 enforceOk();
8956 return m_value;
8957 }
8958
8959 protected:
8960 ResultValueBase( Type type ) : ResultBase( type ) {}
8961
8962 ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
8963 if( m_type == ResultBase::Ok )
8964 new( &m_value ) T( other.m_value );
8965 }
8966
8967 ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
8968 new( &m_value ) T( value );
8969 }
8970
8971 auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
8972 if( m_type == ResultBase::Ok )
8973 m_value.~T();
8974 ResultBase::operator=(other);
8975 if( m_type == ResultBase::Ok )
8976 new( &m_value ) T( other.m_value );
8977 return *this;
8978 }
8979
8980 ~ResultValueBase() override {
8981 if( m_type == Ok )
8982 m_value.~T();
8983 }
8984
8985 union {
8986 T m_value;
8987 };
8988 };
8989
8990 template<>
8991 class ResultValueBase<void> : public ResultBase {
8992 protected:
8993 using ResultBase::ResultBase;
8994 };
8995
8996 template<typename T = void>
8997 class BasicResult : public ResultValueBase<T> {
8998 public:
8999 template<typename U>
9000 explicit BasicResult( BasicResult<U> const &other )
9001 : ResultValueBase<T>( other.type() ),
9002 m_errorMessage( other.errorMessage() )
9003 {
9004 assert( type() != ResultBase::Ok );
9005 }
9006
9007 template<typename U>
9008 static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
9009 static auto ok() -> BasicResult { return { ResultBase::Ok }; }
9010 static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
9011 static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
9012
9013 explicit operator bool() const { return m_type == ResultBase::Ok; }
9014 auto type() const -> ResultBase::Type { return m_type; }
9015 auto errorMessage() const -> std::string { return m_errorMessage; }
9016
9017 protected:
9018 void enforceOk() const override {
9019
9020 // Errors shouldn't reach this point, but if they do
9021 // the actual error message will be in m_errorMessage
9022 assert( m_type != ResultBase::LogicError );
9023 assert( m_type != ResultBase::RuntimeError );
9024 if( m_type != ResultBase::Ok )
9025 std::abort();
9026 }
9027
9028 std::string m_errorMessage; // Only populated if resultType is an error
9029
9030 BasicResult( ResultBase::Type type, std::string const &message )
9031 : ResultValueBase<T>(type),
9032 m_errorMessage(message)
9033 {
9034 assert( m_type != ResultBase::Ok );
9035 }
9036
9037 using ResultValueBase<T>::ResultValueBase;
9038 using ResultBase::m_type;
9039 };
9040
9041 enum class ParseResultType {
9042 Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
9043 };
9044
9045 class ParseState {
9046 public:
9047
9048 ParseState( ParseResultType type, TokenStream const &remainingTokens )
9049 : m_type(type),
9050 m_remainingTokens( remainingTokens )
9051 {}
9052
9053 auto type() const -> ParseResultType { return m_type; }
9054 auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
9055
9056 private:
9057 ParseResultType m_type;
9058 TokenStream m_remainingTokens;
9059 };
9060
9061 using Result = BasicResult<void>;
9062 using ParserResult = BasicResult<ParseResultType>;
9063 using InternalParseResult = BasicResult<ParseState>;
9064
9065 struct HelpColumns {
9066 std::string left;
9067 std::string right;
9068 };
9069
9070 template<typename T>
9071 inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
9072 std::stringstream ss;
9073 ss << source;
9074 ss >> target;
9075 if( ss.fail() )
9076 return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
9077 else
9078 return ParserResult::ok( ParseResultType::Matched );
9079 }
9080 inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
9081 target = source;
9082 return ParserResult::ok( ParseResultType::Matched );
9083 }
9084 inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
9085 std::string srcLC = source;
9086 std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( unsigned char c ) { return static_cast<char>( std::tolower(c) ); } );
9087 if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
9088 target = true;
9089 else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
9090 target = false;
9091 else
9092 return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
9093 return ParserResult::ok( ParseResultType::Matched );
9094 }
9095#ifdef CLARA_CONFIG_OPTIONAL_TYPE
9096 template<typename T>
9097 inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
9098 T temp;
9099 auto result = convertInto( source, temp );
9100 if( result )
9101 target = std::move(temp);
9102 return result;
9103 }
9104#endif // CLARA_CONFIG_OPTIONAL_TYPE
9105
9106 struct NonCopyable {
9107 NonCopyable() = default;
9108 NonCopyable( NonCopyable const & ) = delete;
9109 NonCopyable( NonCopyable && ) = delete;
9110 NonCopyable &operator=( NonCopyable const & ) = delete;
9111 NonCopyable &operator=( NonCopyable && ) = delete;
9112 };
9113
9114 struct BoundRef : NonCopyable {
9115 virtual ~BoundRef() = default;
9116 virtual auto isContainer() const -> bool { return false; }
9117 virtual auto isFlag() const -> bool { return false; }
9118 };
9119 struct BoundValueRefBase : BoundRef {
9120 virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
9121 };
9122 struct BoundFlagRefBase : BoundRef {
9123 virtual auto setFlag( bool flag ) -> ParserResult = 0;
9124 virtual auto isFlag() const -> bool { return true; }
9125 };
9126
9127 template<typename T>
9128 struct BoundValueRef : BoundValueRefBase {
9129 T &m_ref;
9130
9131 explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
9132
9133 auto setValue( std::string const &arg ) -> ParserResult override {
9134 return convertInto( arg, m_ref );
9135 }
9136 };
9137
9138 template<typename T>
9139 struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
9140 std::vector<T> &m_ref;
9141
9142 explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
9143
9144 auto isContainer() const -> bool override { return true; }
9145
9146 auto setValue( std::string const &arg ) -> ParserResult override {
9147 T temp;
9148 auto result = convertInto( arg, temp );
9149 if( result )
9150 m_ref.push_back( temp );
9151 return result;
9152 }
9153 };
9154
9155 struct BoundFlagRef : BoundFlagRefBase {
9156 bool &m_ref;
9157
9158 explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
9159
9160 auto setFlag( bool flag ) -> ParserResult override {
9161 m_ref = flag;
9162 return ParserResult::ok( ParseResultType::Matched );
9163 }
9164 };
9165
9166 template<typename ReturnType>
9167 struct LambdaInvoker {
9168 static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
9169
9170 template<typename L, typename ArgType>
9171 static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
9172 return lambda( arg );
9173 }
9174 };
9175
9176 template<>
9177 struct LambdaInvoker<void> {
9178 template<typename L, typename ArgType>
9179 static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
9180 lambda( arg );
9181 return ParserResult::ok( ParseResultType::Matched );
9182 }
9183 };
9184
9185 template<typename ArgType, typename L>
9186 inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
9187 ArgType temp{};
9188 auto result = convertInto( arg, temp );
9189 return !result
9190 ? result
9191 : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
9192 }
9193
9194 template<typename L>
9195 struct BoundLambda : BoundValueRefBase {
9196 L m_lambda;
9197
9198 static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
9199 explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
9200
9201 auto setValue( std::string const &arg ) -> ParserResult override {
9202 return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
9203 }
9204 };
9205
9206 template<typename L>
9207 struct BoundFlagLambda : BoundFlagRefBase {
9208 L m_lambda;
9209
9210 static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
9211 static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
9212
9213 explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
9214
9215 auto setFlag( bool flag ) -> ParserResult override {
9216 return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
9217 }
9218 };
9219
9220 enum class Optionality { Optional, Required };
9221
9222 struct Parser;
9223
9224 class ParserBase {
9225 public:
9226 virtual ~ParserBase() = default;
9227 virtual auto validate() const -> Result { return Result::ok(); }
9228 virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
9229 virtual auto cardinality() const -> size_t { return 1; }
9230
9231 auto parse( Args const &args ) const -> InternalParseResult {
9232 return parse( args.exeName(), TokenStream( args ) );
9233 }
9234 };
9235
9236 template<typename DerivedT>
9237 class ComposableParserImpl : public ParserBase {
9238 public:
9239 template<typename T>
9240 auto operator|( T const &other ) const -> Parser;
9241
9242 template<typename T>
9243 auto operator+( T const &other ) const -> Parser;
9244 };
9245
9246 // Common code and state for Args and Opts
9247 template<typename DerivedT>
9248 class ParserRefImpl : public ComposableParserImpl<DerivedT> {
9249 protected:
9250 Optionality m_optionality = Optionality::Optional;
9251 std::shared_ptr<BoundRef> m_ref;
9252 std::string m_hint;
9253 std::string m_description;
9254
9255 explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
9256
9257 public:
9258 template<typename T>
9259 ParserRefImpl( T &ref, std::string const &hint )
9260 : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
9261 m_hint( hint )
9262 {}
9263
9264 template<typename LambdaT>
9265 ParserRefImpl( LambdaT const &ref, std::string const &hint )
9266 : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
9267 m_hint(hint)
9268 {}
9269
9270 auto operator()( std::string const &description ) -> DerivedT & {
9271 m_description = description;
9272 return static_cast<DerivedT &>( *this );
9273 }
9274
9275 auto optional() -> DerivedT & {
9276 m_optionality = Optionality::Optional;
9277 return static_cast<DerivedT &>( *this );
9278 };
9279
9280 auto required() -> DerivedT & {
9281 m_optionality = Optionality::Required;
9282 return static_cast<DerivedT &>( *this );
9283 };
9284
9285 auto isOptional() const -> bool {
9286 return m_optionality == Optionality::Optional;
9287 }
9288
9289 auto cardinality() const -> size_t override {
9290 if( m_ref->isContainer() )
9291 return 0;
9292 else
9293 return 1;
9294 }
9295
9296 auto hint() const -> std::string { return m_hint; }
9297 };
9298
9299 class ExeName : public ComposableParserImpl<ExeName> {
9300 std::shared_ptr<std::string> m_name;
9301 std::shared_ptr<BoundValueRefBase> m_ref;
9302
9303 template<typename LambdaT>
9304 static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
9305 return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
9306 }
9307
9308 public:
9309 ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
9310
9311 explicit ExeName( std::string &ref ) : ExeName() {
9312 m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
9313 }
9314
9315 template<typename LambdaT>
9316 explicit ExeName( LambdaT const& lambda ) : ExeName() {
9317 m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
9318 }
9319
9320 // The exe name is not parsed out of the normal tokens, but is handled specially
9321 auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
9322 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9323 }
9324
9325 auto name() const -> std::string { return *m_name; }
9326 auto set( std::string const& newName ) -> ParserResult {
9327
9328 auto lastSlash = newName.find_last_of( "\\/" );
9329 auto filename = ( lastSlash == std::string::npos )
9330 ? newName
9331 : newName.substr( lastSlash+1 );
9332
9333 *m_name = filename;
9334 if( m_ref )
9335 return m_ref->setValue( filename );
9336 else
9337 return ParserResult::ok( ParseResultType::Matched );
9338 }
9339 };
9340
9341 class Arg : public ParserRefImpl<Arg> {
9342 public:
9343 using ParserRefImpl::ParserRefImpl;
9344
9345 auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
9346 auto validationResult = validate();
9347 if( !validationResult )
9348 return InternalParseResult( validationResult );
9349
9350 auto remainingTokens = tokens;
9351 auto const &token = *remainingTokens;
9352 if( token.type != TokenType::Argument )
9353 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9354
9355 assert( !m_ref->isFlag() );
9356 auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
9357
9358 auto result = valueRef->setValue( remainingTokens->token );
9359 if( !result )
9360 return InternalParseResult( result );
9361 else
9362 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9363 }
9364 };
9365
9366 inline auto normaliseOpt( std::string const &optName ) -> std::string {
9367#ifdef CATCH_PLATFORM_WINDOWS
9368 if( optName[0] == '/' )
9369 return "-" + optName.substr( 1 );
9370 else
9371#endif
9372 return optName;
9373 }
9374
9375 class Opt : public ParserRefImpl<Opt> {
9376 protected:
9377 std::vector<std::string> m_optNames;
9378
9379 public:
9380 template<typename LambdaT>
9381 explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
9382
9383 explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
9384
9385 template<typename LambdaT>
9386 Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
9387
9388 template<typename T>
9389 Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
9390
9391 auto operator[]( std::string const &optName ) -> Opt & {
9392 m_optNames.push_back( optName );
9393 return *this;
9394 }
9395
9396 auto getHelpColumns() const -> std::vector<HelpColumns> {
9397 std::ostringstream oss;
9398 bool first = true;
9399 for( auto const &opt : m_optNames ) {
9400 if (first)
9401 first = false;
9402 else
9403 oss << ", ";
9404 oss << opt;
9405 }
9406 if( !m_hint.empty() )
9407 oss << " <" << m_hint << ">";
9408 return { { oss.str(), m_description } };
9409 }
9410
9411 auto isMatch( std::string const &optToken ) const -> bool {
9412 auto normalisedToken = normaliseOpt( optToken );
9413 for( auto const &name : m_optNames ) {
9414 if( normaliseOpt( name ) == normalisedToken )
9415 return true;
9416 }
9417 return false;
9418 }
9419
9420 using ParserBase::parse;
9421
9422 auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
9423 auto validationResult = validate();
9424 if( !validationResult )
9425 return InternalParseResult( validationResult );
9426
9427 auto remainingTokens = tokens;
9428 if( remainingTokens && remainingTokens->type == TokenType::Option ) {
9429 auto const &token = *remainingTokens;
9430 if( isMatch(token.token ) ) {
9431 if( m_ref->isFlag() ) {
9432 auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
9433 auto result = flagRef->setFlag( true );
9434 if( !result )
9435 return InternalParseResult( result );
9436 if( result.value() == ParseResultType::ShortCircuitAll )
9437 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9438 } else {
9439 auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
9440 ++remainingTokens;
9441 if( !remainingTokens )
9442 return InternalParseResult::runtimeError( "Expected argument following " + token.token );
9443 auto const &argToken = *remainingTokens;
9444 if( argToken.type != TokenType::Argument )
9445 return InternalParseResult::runtimeError( "Expected argument following " + token.token );
9446 auto result = valueRef->setValue( argToken.token );
9447 if( !result )
9448 return InternalParseResult( result );
9449 if( result.value() == ParseResultType::ShortCircuitAll )
9450 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
9451 }
9452 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
9453 }
9454 }
9455 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
9456 }
9457
9458 auto validate() const -> Result override {
9459 if( m_optNames.empty() )
9460 return Result::logicError( "No options supplied to Opt" );
9461 for( auto const &name : m_optNames ) {
9462 if( name.empty() )
9463 return Result::logicError( "Option name cannot be empty" );
9464#ifdef CATCH_PLATFORM_WINDOWS
9465 if( name[0] != '-' && name[0] != '/' )
9466 return Result::logicError( "Option name must begin with '-' or '/'" );
9467#else
9468 if( name[0] != '-' )
9469 return Result::logicError( "Option name must begin with '-'" );
9470#endif
9471 }
9472 return ParserRefImpl::validate();
9473 }
9474 };
9475
9476 struct Help : Opt {
9477 Help( bool &showHelpFlag )
9478 : Opt([&]( bool flag ) {
9479 showHelpFlag = flag;
9480 return ParserResult::ok( ParseResultType::ShortCircuitAll );
9481 })
9482 {
9483 static_cast<Opt &>( *this )
9484 ("display usage information")
9485 ["-?"]["-h"]["--help"]
9486 .optional();
9487 }
9488 };
9489
9490 struct Parser : ParserBase {
9491
9492 mutable ExeName m_exeName;
9493 std::vector<Opt> m_options;
9494 std::vector<Arg> m_args;
9495
9496 auto operator|=( ExeName const &exeName ) -> Parser & {
9497 m_exeName = exeName;
9498 return *this;
9499 }
9500
9501 auto operator|=( Arg const &arg ) -> Parser & {
9502 m_args.push_back(arg);
9503 return *this;
9504 }
9505
9506 auto operator|=( Opt const &opt ) -> Parser & {
9507 m_options.push_back(opt);
9508 return *this;
9509 }
9510
9511 auto operator|=( Parser const &other ) -> Parser & {
9512 m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
9513 m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
9514 return *this;
9515 }
9516
9517 template<typename T>
9518 auto operator|( T const &other ) const -> Parser {
9519 return Parser( *this ) |= other;
9520 }
9521
9522 // Forward deprecated interface with '+' instead of '|'
9523 template<typename T>
9524 auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
9525 template<typename T>
9526 auto operator+( T const &other ) const -> Parser { return operator|( other ); }
9527
9528 auto getHelpColumns() const -> std::vector<HelpColumns> {
9529 std::vector<HelpColumns> cols;
9530 for (auto const &o : m_options) {
9531 auto childCols = o.getHelpColumns();
9532 cols.insert( cols.end(), childCols.begin(), childCols.end() );
9533 }
9534 return cols;
9535 }
9536
9537 void writeToStream( std::ostream &os ) const {
9538 if (!m_exeName.name().empty()) {
9539 os << "usage:\n" << " " << m_exeName.name() << " ";
9540 bool required = true, first = true;
9541 for( auto const &arg : m_args ) {
9542 if (first)
9543 first = false;
9544 else
9545 os << " ";
9546 if( arg.isOptional() && required ) {
9547 os << "[";
9548 required = false;
9549 }
9550 os << "<" << arg.hint() << ">";
9551 if( arg.cardinality() == 0 )
9552 os << " ... ";
9553 }
9554 if( !required )
9555 os << "]";
9556 if( !m_options.empty() )
9557 os << " options";
9558 os << "\n\nwhere options are:" << std::endl;
9559 }
9560
9561 auto rows = getHelpColumns();
9562 size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
9563 size_t optWidth = 0;
9564 for( auto const &cols : rows )
9565 optWidth = (std::max)(optWidth, cols.left.size() + 2);
9566
9567 optWidth = (std::min)(optWidth, consoleWidth/2);
9568
9569 for( auto const &cols : rows ) {
9570 auto row =
9571 TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
9572 TextFlow::Spacer(4) +
9573 TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
9574 os << row << std::endl;
9575 }
9576 }
9577
9578 friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
9579 parser.writeToStream( os );
9580 return os;
9581 }
9582
9583 auto validate() const -> Result override {
9584 for( auto const &opt : m_options ) {
9585 auto result = opt.validate();
9586 if( !result )
9587 return result;
9588 }
9589 for( auto const &arg : m_args ) {
9590 auto result = arg.validate();
9591 if( !result )
9592 return result;
9593 }
9594 return Result::ok();
9595 }
9596
9597 using ParserBase::parse;
9598
9599 auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
9600
9601 struct ParserInfo {
9602 ParserBase const* parser = nullptr;
9603 size_t count = 0;
9604 };
9605 const size_t totalParsers = m_options.size() + m_args.size();
9606 assert( totalParsers < 512 );
9607 // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
9608 ParserInfo parseInfos[512];
9609
9610 {
9611 size_t i = 0;
9612 for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
9613 for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
9614 }
9615
9616 m_exeName.set( exeName );
9617
9618 auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
9619 while( result.value().remainingTokens() ) {
9620 bool tokenParsed = false;
9621
9622 for( size_t i = 0; i < totalParsers; ++i ) {
9623 auto& parseInfo = parseInfos[i];
9624 if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
9625 result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
9626 if (!result)
9627 return result;
9628 if (result.value().type() != ParseResultType::NoMatch) {
9629 tokenParsed = true;
9630 ++parseInfo.count;
9631 break;
9632 }
9633 }
9634 }
9635
9636 if( result.value().type() == ParseResultType::ShortCircuitAll )
9637 return result;
9638 if( !tokenParsed )
9639 return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
9640 }
9641 // !TBD Check missing required options
9642 return result;
9643 }
9644 };
9645
9646 template<typename DerivedT>
9647 template<typename T>
9648 auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
9649 return Parser() | static_cast<DerivedT const &>( *this ) | other;
9650 }
9651} // namespace detail
9652
9653// A Combined parser
9654using detail::Parser;
9655
9656// A parser for options
9657using detail::Opt;
9658
9659// A parser for arguments
9660using detail::Arg;
9661
9662// Wrapper for argc, argv from main()
9663using detail::Args;
9664
9665// Specifies the name of the executable
9666using detail::ExeName;
9667
9668// Convenience wrapper for option parser that specifies the help option
9669using detail::Help;
9670
9671// enum of result types from a parse
9672using detail::ParseResultType;
9673
9674// Result type for parser operation
9675using detail::ParserResult;
9676
9677}} // namespace Catch::clara
9678
9679// end clara.hpp
9680#ifdef __clang__
9681#pragma clang diagnostic pop
9682#endif
9683
9684// Restore Clara's value for console width, if present
9685#ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9686#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9687#undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
9688#endif
9689
9690// end catch_clara.h
9691namespace Catch {
9692
9693 clara::Parser makeCommandLineParser( ConfigData& config );
9694
9695} // end namespace Catch
9696
9697// end catch_commandline.h
9698#include <fstream>
9699#include <ctime>
9700
9701namespace Catch {
9702
9703 clara::Parser makeCommandLineParser( ConfigData& config ) {
9704
9705 using namespace clara;
9706
9707 auto const setWarning = [&]( std::string const& warning ) {
9708 auto warningSet = [&]() {
9709 if( warning == "NoAssertions" )
9710 return WarnAbout::NoAssertions;
9711
9712 if ( warning == "NoTests" )
9713 return WarnAbout::NoTests;
9714
9715 return WarnAbout::Nothing;
9716 }();
9717
9718 if (warningSet == WarnAbout::Nothing)
9719 return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
9720 config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
9721 return ParserResult::ok( ParseResultType::Matched );
9722 };
9723 auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
9724 std::ifstream f( filename.c_str() );
9725 if( !f.is_open() )
9726 return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
9727
9728 std::string line;
9729 while( std::getline( f, line ) ) {
9730 line = trim(line);
9731 if( !line.empty() && !startsWith( line, '#' ) ) {
9732 if( !startsWith( line, '"' ) )
9733 line = '"' + line + '"';
9734 config.testsOrTags.push_back( line );
9735 config.testsOrTags.emplace_back( "," );
9736 }
9737 }
9738 //Remove comma in the end
9739 if(!config.testsOrTags.empty())
9740 config.testsOrTags.erase( config.testsOrTags.end()-1 );
9741
9742 return ParserResult::ok( ParseResultType::Matched );
9743 };
9744 auto const setTestOrder = [&]( std::string const& order ) {
9745 if( startsWith( "declared", order ) )
9746 config.runOrder = RunTests::InDeclarationOrder;
9747 else if( startsWith( "lexical", order ) )
9748 config.runOrder = RunTests::InLexicographicalOrder;
9749 else if( startsWith( "random", order ) )
9750 config.runOrder = RunTests::InRandomOrder;
9751 else
9752 return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
9753 return ParserResult::ok( ParseResultType::Matched );
9754 };
9755 auto const setRngSeed = [&]( std::string const& seed ) {
9756 if( seed != "time" )
9757 return clara::detail::convertInto( seed, config.rngSeed );
9758 config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
9759 return ParserResult::ok( ParseResultType::Matched );
9760 };
9761 auto const setColourUsage = [&]( std::string const& useColour ) {
9762 auto mode = toLower( useColour );
9763
9764 if( mode == "yes" )
9765 config.useColour = UseColour::Yes;
9766 else if( mode == "no" )
9767 config.useColour = UseColour::No;
9768 else if( mode == "auto" )
9769 config.useColour = UseColour::Auto;
9770 else
9771 return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
9772 return ParserResult::ok( ParseResultType::Matched );
9773 };
9774 auto const setWaitForKeypress = [&]( std::string const& keypress ) {
9775 auto keypressLc = toLower( keypress );
9776 if (keypressLc == "never")
9777 config.waitForKeypress = WaitForKeypress::Never;
9778 else if( keypressLc == "start" )
9779 config.waitForKeypress = WaitForKeypress::BeforeStart;
9780 else if( keypressLc == "exit" )
9781 config.waitForKeypress = WaitForKeypress::BeforeExit;
9782 else if( keypressLc == "both" )
9783 config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
9784 else
9785 return ParserResult::runtimeError( "keypress argument must be one of: never, start, exit or both. '" + keypress + "' not recognised" );
9786 return ParserResult::ok( ParseResultType::Matched );
9787 };
9788 auto const setVerbosity = [&]( std::string const& verbosity ) {
9789 auto lcVerbosity = toLower( verbosity );
9790 if( lcVerbosity == "quiet" )
9791 config.verbosity = Verbosity::Quiet;
9792 else if( lcVerbosity == "normal" )
9793 config.verbosity = Verbosity::Normal;
9794 else if( lcVerbosity == "high" )
9795 config.verbosity = Verbosity::High;
9796 else
9797 return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
9798 return ParserResult::ok( ParseResultType::Matched );
9799 };
9800 auto const setReporter = [&]( std::string const& reporter ) {
9801 IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
9802
9803 auto lcReporter = toLower( reporter );
9804 auto result = factories.find( lcReporter );
9805
9806 if( factories.end() != result )
9807 config.reporterName = lcReporter;
9808 else
9809 return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
9810 return ParserResult::ok( ParseResultType::Matched );
9811 };
9812
9813 auto cli
9814 = ExeName( config.processName )
9815 | Help( config.showHelp )
9816 | Opt( config.listTests )
9817 ["-l"]["--list-tests"]
9818 ( "list all/matching test cases" )
9819 | Opt( config.listTags )
9820 ["-t"]["--list-tags"]
9821 ( "list all/matching tags" )
9822 | Opt( config.showSuccessfulTests )
9823 ["-s"]["--success"]
9824 ( "include successful tests in output" )
9825 | Opt( config.shouldDebugBreak )
9826 ["-b"]["--break"]
9827 ( "break into debugger on failure" )
9828 | Opt( config.noThrow )
9829 ["-e"]["--nothrow"]
9830 ( "skip exception tests" )
9831 | Opt( config.showInvisibles )
9832 ["-i"]["--invisibles"]
9833 ( "show invisibles (tabs, newlines)" )
9834 | Opt( config.outputFilename, "filename" )
9835 ["-o"]["--out"]
9836 ( "output filename" )
9837 | Opt( setReporter, "name" )
9838 ["-r"]["--reporter"]
9839 ( "reporter to use (defaults to console)" )
9840 | Opt( config.name, "name" )
9841 ["-n"]["--name"]
9842 ( "suite name" )
9843 | Opt( [&]( bool ){ config.abortAfter = 1; } )
9844 ["-a"]["--abort"]
9845 ( "abort at first failure" )
9846 | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
9847 ["-x"]["--abortx"]
9848 ( "abort after x failures" )
9849 | Opt( setWarning, "warning name" )
9850 ["-w"]["--warn"]
9851 ( "enable warnings" )
9852 | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
9853 ["-d"]["--durations"]
9854 ( "show test durations" )
9855 | Opt( config.minDuration, "seconds" )
9856 ["-D"]["--min-duration"]
9857 ( "show test durations for tests taking at least the given number of seconds" )
9858 | Opt( loadTestNamesFromFile, "filename" )
9859 ["-f"]["--input-file"]
9860 ( "load test names to run from a file" )
9861 | Opt( config.filenamesAsTags )
9862 ["-#"]["--filenames-as-tags"]
9863 ( "adds a tag for the filename" )
9864 | Opt( config.sectionsToRun, "section name" )
9865 ["-c"]["--section"]
9866 ( "specify section to run" )
9867 | Opt( setVerbosity, "quiet|normal|high" )
9868 ["-v"]["--verbosity"]
9869 ( "set output verbosity" )
9870 | Opt( config.listTestNamesOnly )
9871 ["--list-test-names-only"]
9872 ( "list all/matching test cases names only" )
9873 | Opt( config.listReporters )
9874 ["--list-reporters"]
9875 ( "list all reporters" )
9876 | Opt( setTestOrder, "decl|lex|rand" )
9877 ["--order"]
9878 ( "test case order (defaults to decl)" )
9879 | Opt( setRngSeed, "'time'|number" )
9880 ["--rng-seed"]
9881 ( "set a specific seed for random numbers" )
9882 | Opt( setColourUsage, "yes|no" )
9883 ["--use-colour"]
9884 ( "should output be colourised" )
9885 | Opt( config.libIdentify )
9886 ["--libidentify"]
9887 ( "report name and version according to libidentify standard" )
9888 | Opt( setWaitForKeypress, "never|start|exit|both" )
9889 ["--wait-for-keypress"]
9890 ( "waits for a keypress before exiting" )
9891 | Opt( config.benchmarkSamples, "samples" )
9892 ["--benchmark-samples"]
9893 ( "number of samples to collect (default: 100)" )
9894 | Opt( config.benchmarkResamples, "resamples" )
9895 ["--benchmark-resamples"]
9896 ( "number of resamples for the bootstrap (default: 100000)" )
9897 | Opt( config.benchmarkConfidenceInterval, "confidence interval" )
9898 ["--benchmark-confidence-interval"]
9899 ( "confidence interval for the bootstrap (between 0 and 1, default: 0.95)" )
9900 | Opt( config.benchmarkNoAnalysis )
9901 ["--benchmark-no-analysis"]
9902 ( "perform only measurements; do not perform any analysis" )
9903 | Opt( config.benchmarkWarmupTime, "benchmarkWarmupTime" )
9904 ["--benchmark-warmup-time"]
9905 ( "amount of time in milliseconds spent on warming up each test (default: 100)" )
9906 | Arg( config.testsOrTags, "test name|pattern|tags" )
9907 ( "which test or tests to use" );
9908
9909 return cli;
9910 }
9911
9912} // end namespace Catch
9913// end catch_commandline.cpp
9914// start catch_common.cpp
9915
9916#include <cstring>
9917#include <ostream>
9918
9919namespace Catch {
9920
9921 bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
9922 return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
9923 }
9924 bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
9925 // We can assume that the same file will usually have the same pointer.
9926 // Thus, if the pointers are the same, there is no point in calling the strcmp
9927 return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
9928 }
9929
9930 std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
9931#ifndef __GNUG__
9932 os << info.file << '(' << info.line << ')';
9933#else
9934 os << info.file << ':' << info.line;
9935#endif
9936 return os;
9937 }
9938
9939 std::string StreamEndStop::operator+() const {
9940 return std::string();
9941 }
9942
9943 NonCopyable::NonCopyable() = default;
9944 NonCopyable::~NonCopyable() = default;
9945
9946}
9947// end catch_common.cpp
9948// start catch_config.cpp
9949
9950namespace Catch {
9951
9952 Config::Config( ConfigData const& data )
9953 : m_data( data ),
9954 m_stream( openStream() )
9955 {
9956 // We need to trim filter specs to avoid trouble with superfluous
9957 // whitespace (esp. important for bdd macros, as those are manually
9958 // aligned with whitespace).
9959
9960 for (auto& elem : m_data.testsOrTags) {
9961 elem = trim(elem);
9962 }
9963 for (auto& elem : m_data.sectionsToRun) {
9964 elem = trim(elem);
9965 }
9966
9967 TestSpecParser parser(ITagAliasRegistry::get());
9968 if (!m_data.testsOrTags.empty()) {
9969 m_hasTestFilters = true;
9970 for (auto const& testOrTags : m_data.testsOrTags) {
9971 parser.parse(testOrTags);
9972 }
9973 }
9974 m_testSpec = parser.testSpec();
9975 }
9976
9977 std::string const& Config::getFilename() const {
9978 return m_data.outputFilename ;
9979 }
9980
9981 bool Config::listTests() const { return m_data.listTests; }
9982 bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
9983 bool Config::listTags() const { return m_data.listTags; }
9984 bool Config::listReporters() const { return m_data.listReporters; }
9985
9986 std::string Config::getProcessName() const { return m_data.processName; }
9987 std::string const& Config::getReporterName() const { return m_data.reporterName; }
9988
9989 std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
9990 std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
9991
9992 TestSpec const& Config::testSpec() const { return m_testSpec; }
9993 bool Config::hasTestFilters() const { return m_hasTestFilters; }
9994
9995 bool Config::showHelp() const { return m_data.showHelp; }
9996
9997 // IConfig interface
9998 bool Config::allowThrows() const { return !m_data.noThrow; }
9999 std::ostream& Config::stream() const { return m_stream->stream(); }
10000 std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
10001 bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
10002 bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
10003 bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
10004 ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
10005 double Config::minDuration() const { return m_data.minDuration; }
10006 RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
10007 unsigned int Config::rngSeed() const { return m_data.rngSeed; }
10008 UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
10009 bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
10010 int Config::abortAfter() const { return m_data.abortAfter; }
10011 bool Config::showInvisibles() const { return m_data.showInvisibles; }
10012 Verbosity Config::verbosity() const { return m_data.verbosity; }
10013
10014 bool Config::benchmarkNoAnalysis() const { return m_data.benchmarkNoAnalysis; }
10015 int Config::benchmarkSamples() const { return m_data.benchmarkSamples; }
10016 double Config::benchmarkConfidenceInterval() const { return m_data.benchmarkConfidenceInterval; }
10017 unsigned int Config::benchmarkResamples() const { return m_data.benchmarkResamples; }
10018 std::chrono::milliseconds Config::benchmarkWarmupTime() const { return std::chrono::milliseconds(m_data.benchmarkWarmupTime); }
10019
10020 IStream const* Config::openStream() {
10021 return Catch::makeStream(m_data.outputFilename);
10022 }
10023
10024} // end namespace Catch
10025// end catch_config.cpp
10026// start catch_console_colour.cpp
10027
10028#if defined(__clang__)
10029# pragma clang diagnostic push
10030# pragma clang diagnostic ignored "-Wexit-time-destructors"
10031#endif
10032
10033// start catch_errno_guard.h
10034
10035namespace Catch {
10036
10037 class ErrnoGuard {
10038 public:
10039 ErrnoGuard();
10040 ~ErrnoGuard();
10041 private:
10042 int m_oldErrno;
10043 };
10044
10045}
10046
10047// end catch_errno_guard.h
10048// start catch_windows_h_proxy.h
10049
10050
10051#if defined(CATCH_PLATFORM_WINDOWS)
10052
10053#if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
10054# define CATCH_DEFINED_NOMINMAX
10055# define NOMINMAX
10056#endif
10057#if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
10058# define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10059# define WIN32_LEAN_AND_MEAN
10060#endif
10061
10062#ifdef __AFXDLL
10063#include <AfxWin.h>
10064#else
10065#include <windows.h>
10066#endif
10067
10068#ifdef CATCH_DEFINED_NOMINMAX
10069# undef NOMINMAX
10070#endif
10071#ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
10072# undef WIN32_LEAN_AND_MEAN
10073#endif
10074
10075#endif // defined(CATCH_PLATFORM_WINDOWS)
10076
10077// end catch_windows_h_proxy.h
10078#include <sstream>
10079
10080namespace Catch {
10081 namespace {
10082
10083 struct IColourImpl {
10084 virtual ~IColourImpl() = default;
10085 virtual void use( Colour::Code _colourCode ) = 0;
10086 };
10087
10088 struct NoColourImpl : IColourImpl {
10089 void use( Colour::Code ) override {}
10090
10091 static IColourImpl* instance() {
10092 static NoColourImpl s_instance;
10093 return &s_instance;
10094 }
10095 };
10096
10097 } // anon namespace
10098} // namespace Catch
10099
10100#if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
10101# ifdef CATCH_PLATFORM_WINDOWS
10102# define CATCH_CONFIG_COLOUR_WINDOWS
10103# else
10104# define CATCH_CONFIG_COLOUR_ANSI
10105# endif
10106#endif
10107
10108#if defined ( CATCH_CONFIG_COLOUR_WINDOWS )
10109
10110namespace Catch {
10111namespace {
10112
10113 class Win32ColourImpl : public IColourImpl {
10114 public:
10115 Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
10116 {
10117 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
10118 GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
10119 originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
10120 originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
10121 }
10122
10123 void use( Colour::Code _colourCode ) override {
10124 switch( _colourCode ) {
10125 case Colour::None: return setTextAttribute( originalForegroundAttributes );
10126 case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10127 case Colour::Red: return setTextAttribute( FOREGROUND_RED );
10128 case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
10129 case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
10130 case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
10131 case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
10132 case Colour::Grey: return setTextAttribute( 0 );
10133
10134 case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
10135 case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
10136 case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
10137 case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
10138 case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
10139
10140 case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
10141
10142 default:
10143 CATCH_ERROR( "Unknown colour requested" );
10144 }
10145 }
10146
10147 private:
10148 void setTextAttribute( WORD _textAttribute ) {
10149 SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
10150 }
10151 HANDLE stdoutHandle;
10152 WORD originalForegroundAttributes;
10153 WORD originalBackgroundAttributes;
10154 };
10155
10156 IColourImpl* platformColourInstance() {
10157 static Win32ColourImpl s_instance;
10158
10159 IConfigPtr config = getCurrentContext().getConfig();
10160 UseColour::YesOrNo colourMode = config
10161 ? config->useColour()
10162 : UseColour::Auto;
10163 if( colourMode == UseColour::Auto )
10164 colourMode = UseColour::Yes;
10165 return colourMode == UseColour::Yes
10166 ? &s_instance
10167 : NoColourImpl::instance();
10168 }
10169
10170} // end anon namespace
10171} // end namespace Catch
10172
10173#elif defined( CATCH_CONFIG_COLOUR_ANSI )
10174
10175#include <unistd.h>
10176
10177namespace Catch {
10178namespace {
10179
10180 // use POSIX/ ANSI console terminal codes
10181 // Thanks to Adam Strzelecki for original contribution
10182 // (http://github.com/nanoant)
10183 // https://github.com/philsquared/Catch/pull/131
10184 class PosixColourImpl : public IColourImpl {
10185 public:
10186 void use( Colour::Code _colourCode ) override {
10187 switch( _colourCode ) {
10188 case Colour::None:
10189 case Colour::White: return setColour( "[0m" );
10190 case Colour::Red: return setColour( "[0;31m" );
10191 case Colour::Green: return setColour( "[0;32m" );
10192 case Colour::Blue: return setColour( "[0;34m" );
10193 case Colour::Cyan: return setColour( "[0;36m" );
10194 case Colour::Yellow: return setColour( "[0;33m" );
10195 case Colour::Grey: return setColour( "[1;30m" );
10196
10197 case Colour::LightGrey: return setColour( "[0;37m" );
10198 case Colour::BrightRed: return setColour( "[1;31m" );
10199 case Colour::BrightGreen: return setColour( "[1;32m" );
10200 case Colour::BrightWhite: return setColour( "[1;37m" );
10201 case Colour::BrightYellow: return setColour( "[1;33m" );
10202
10203 case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
10204 default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
10205 }
10206 }
10207 static IColourImpl* instance() {
10208 static PosixColourImpl s_instance;
10209 return &s_instance;
10210 }
10211
10212 private:
10213 void setColour( const char* _escapeCode ) {
10214 getCurrentContext().getConfig()->stream()
10215 << '\033' << _escapeCode;
10216 }
10217 };
10218
10219 bool useColourOnPlatform() {
10220 return
10221#if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10222 !isDebuggerActive() &&
10223#endif
10224#if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
10225 isatty(STDOUT_FILENO)
10226#else
10227 false
10228#endif
10229 ;
10230 }
10231 IColourImpl* platformColourInstance() {
10232 ErrnoGuard guard;
10233 IConfigPtr config = getCurrentContext().getConfig();
10234 UseColour::YesOrNo colourMode = config
10235 ? config->useColour()
10236 : UseColour::Auto;
10237 if( colourMode == UseColour::Auto )
10238 colourMode = useColourOnPlatform()
10239 ? UseColour::Yes
10240 : UseColour::No;
10241 return colourMode == UseColour::Yes
10242 ? PosixColourImpl::instance()
10243 : NoColourImpl::instance();
10244 }
10245
10246} // end anon namespace
10247} // end namespace Catch
10248
10249#else // not Windows or ANSI ///////////////////////////////////////////////
10250
10251namespace Catch {
10252
10253 static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
10254
10255} // end namespace Catch
10256
10257#endif // Windows/ ANSI/ None
10258
10259namespace Catch {
10260
10261 Colour::Colour( Code _colourCode ) { use( _colourCode ); }
10262 Colour::Colour( Colour&& other ) noexcept {
10263 m_moved = other.m_moved;
10264 other.m_moved = true;
10265 }
10266 Colour& Colour::operator=( Colour&& other ) noexcept {
10267 m_moved = other.m_moved;
10268 other.m_moved = true;
10269 return *this;
10270 }
10271
10272 Colour::~Colour(){ if( !m_moved ) use( None ); }
10273
10274 void Colour::use( Code _colourCode ) {
10275 static IColourImpl* impl = platformColourInstance();
10276 // Strictly speaking, this cannot possibly happen.
10277 // However, under some conditions it does happen (see #1626),
10278 // and this change is small enough that we can let practicality
10279 // triumph over purity in this case.
10280 if (impl != nullptr) {
10281 impl->use( _colourCode );
10282 }
10283 }
10284
10285 std::ostream& operator << ( std::ostream& os, Colour const& ) {
10286 return os;
10287 }
10288
10289} // end namespace Catch
10290
10291#if defined(__clang__)
10292# pragma clang diagnostic pop
10293#endif
10294
10295// end catch_console_colour.cpp
10296// start catch_context.cpp
10297
10298namespace Catch {
10299
10300 class Context : public IMutableContext, NonCopyable {
10301
10302 public: // IContext
10303 IResultCapture* getResultCapture() override {
10304 return m_resultCapture;
10305 }
10306 IRunner* getRunner() override {
10307 return m_runner;
10308 }
10309
10310 IConfigPtr const& getConfig() const override {
10311 return m_config;
10312 }
10313
10314 ~Context() override;
10315
10316 public: // IMutableContext
10317 void setResultCapture( IResultCapture* resultCapture ) override {
10318 m_resultCapture = resultCapture;
10319 }
10320 void setRunner( IRunner* runner ) override {
10321 m_runner = runner;
10322 }
10323 void setConfig( IConfigPtr const& config ) override {
10324 m_config = config;
10325 }
10326
10327 friend IMutableContext& getCurrentMutableContext();
10328
10329 private:
10330 IConfigPtr m_config;
10331 IRunner* m_runner = nullptr;
10332 IResultCapture* m_resultCapture = nullptr;
10333 };
10334
10335 IMutableContext *IMutableContext::currentContext = nullptr;
10336
10337 void IMutableContext::createContext()
10338 {
10339 currentContext = new Context();
10340 }
10341
10342 void cleanUpContext() {
10343 delete IMutableContext::currentContext;
10344 IMutableContext::currentContext = nullptr;
10345 }
10346 IContext::~IContext() = default;
10347 IMutableContext::~IMutableContext() = default;
10348 Context::~Context() = default;
10349
10350 SimplePcg32& rng() {
10351 static SimplePcg32 s_rng;
10352 return s_rng;
10353 }
10354
10355}
10356// end catch_context.cpp
10357// start catch_debug_console.cpp
10358
10359// start catch_debug_console.h
10360
10361#include <string>
10362
10363namespace Catch {
10364 void writeToDebugConsole( std::string const& text );
10365}
10366
10367// end catch_debug_console.h
10368#if defined(CATCH_CONFIG_ANDROID_LOGWRITE)
10369#include <android/log.h>
10370
10371 namespace Catch {
10372 void writeToDebugConsole( std::string const& text ) {
10373 __android_log_write( ANDROID_LOG_DEBUG, "Catch", text.c_str() );
10374 }
10375 }
10376
10377#elif defined(CATCH_PLATFORM_WINDOWS)
10378
10379 namespace Catch {
10380 void writeToDebugConsole( std::string const& text ) {
10381 ::OutputDebugStringA( text.c_str() );
10382 }
10383 }
10384
10385#else
10386
10387 namespace Catch {
10388 void writeToDebugConsole( std::string const& text ) {
10389 // !TBD: Need a version for Mac/ XCode and other IDEs
10390 Catch::cout() << text;
10391 }
10392 }
10393
10394#endif // Platform
10395// end catch_debug_console.cpp
10396// start catch_debugger.cpp
10397
10398#if defined(CATCH_PLATFORM_MAC) || defined(CATCH_PLATFORM_IPHONE)
10399
10400# include <cassert>
10401# include <sys/types.h>
10402# include <unistd.h>
10403# include <cstddef>
10404# include <ostream>
10405
10406#ifdef __apple_build_version__
10407 // These headers will only compile with AppleClang (XCode)
10408 // For other compilers (Clang, GCC, ... ) we need to exclude them
10409# include <sys/sysctl.h>
10410#endif
10411
10412 namespace Catch {
10413 #ifdef __apple_build_version__
10414 // The following function is taken directly from the following technical note:
10415 // https://developer.apple.com/library/archive/qa/qa1361/_index.html
10416
10417 // Returns true if the current process is being debugged (either
10418 // running under the debugger or has a debugger attached post facto).
10419 bool isDebuggerActive(){
10420 int mib[4];
10421 struct kinfo_proc info;
10422 std::size_t size;
10423
10424 // Initialize the flags so that, if sysctl fails for some bizarre
10425 // reason, we get a predictable result.
10426
10427 info.kp_proc.p_flag = 0;
10428
10429 // Initialize mib, which tells sysctl the info we want, in this case
10430 // we're looking for information about a specific process ID.
10431
10432 mib[0] = CTL_KERN;
10433 mib[1] = KERN_PROC;
10434 mib[2] = KERN_PROC_PID;
10435 mib[3] = getpid();
10436
10437 // Call sysctl.
10438
10439 size = sizeof(info);
10440 if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
10441 Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
10442 return false;
10443 }
10444
10445 // We're being debugged if the P_TRACED flag is set.
10446
10447 return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
10448 }
10449 #else
10450 bool isDebuggerActive() {
10451 // We need to find another way to determine this for non-appleclang compilers on macOS
10452 return false;
10453 }
10454 #endif
10455 } // namespace Catch
10456
10457#elif defined(CATCH_PLATFORM_LINUX)
10458 #include <fstream>
10459 #include <string>
10460
10461 namespace Catch{
10462 // The standard POSIX way of detecting a debugger is to attempt to
10463 // ptrace() the process, but this needs to be done from a child and not
10464 // this process itself to still allow attaching to this process later
10465 // if wanted, so is rather heavy. Under Linux we have the PID of the
10466 // "debugger" (which doesn't need to be gdb, of course, it could also
10467 // be strace, for example) in /proc/$PID/status, so just get it from
10468 // there instead.
10469 bool isDebuggerActive(){
10470 // Libstdc++ has a bug, where std::ifstream sets errno to 0
10471 // This way our users can properly assert over errno values
10472 ErrnoGuard guard;
10473 std::ifstream in("/proc/self/status");
10474 for( std::string line; std::getline(in, line); ) {
10475 static const int PREFIX_LEN = 11;
10476 if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
10477 // We're traced if the PID is not 0 and no other PID starts
10478 // with 0 digit, so it's enough to check for just a single
10479 // character.
10480 return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
10481 }
10482 }
10483
10484 return false;
10485 }
10486 } // namespace Catch
10487#elif defined(_MSC_VER)
10488 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10489 namespace Catch {
10490 bool isDebuggerActive() {
10491 return IsDebuggerPresent() != 0;
10492 }
10493 }
10494#elif defined(__MINGW32__)
10495 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
10496 namespace Catch {
10497 bool isDebuggerActive() {
10498 return IsDebuggerPresent() != 0;
10499 }
10500 }
10501#else
10502 namespace Catch {
10503 bool isDebuggerActive() { return false; }
10504 }
10505#endif // Platform
10506// end catch_debugger.cpp
10507// start catch_decomposer.cpp
10508
10509namespace Catch {
10510
10511 ITransientExpression::~ITransientExpression() = default;
10512
10513 void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
10514 if( lhs.size() + rhs.size() < 40 &&
10515 lhs.find('\n') == std::string::npos &&
10516 rhs.find('\n') == std::string::npos )
10517 os << lhs << " " << op << " " << rhs;
10518 else
10519 os << lhs << "\n" << op << "\n" << rhs;
10520 }
10521}
10522// end catch_decomposer.cpp
10523// start catch_enforce.cpp
10524
10525#include <stdexcept>
10526
10527namespace Catch {
10528#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
10529 [[noreturn]]
10530 void throw_exception(std::exception const& e) {
10531 Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
10532 << "The message was: " << e.what() << '\n';
10533 std::terminate();
10534 }
10535#endif
10536
10537 [[noreturn]]
10538 void throw_logic_error(std::string const& msg) {
10539 throw_exception(std::logic_error(msg));
10540 }
10541
10542 [[noreturn]]
10543 void throw_domain_error(std::string const& msg) {
10544 throw_exception(std::domain_error(msg));
10545 }
10546
10547 [[noreturn]]
10548 void throw_runtime_error(std::string const& msg) {
10549 throw_exception(std::runtime_error(msg));
10550 }
10551
10552} // namespace Catch;
10553// end catch_enforce.cpp
10554// start catch_enum_values_registry.cpp
10555// start catch_enum_values_registry.h
10556
10557#include <vector>
10558#include <memory>
10559
10560namespace Catch {
10561
10562 namespace Detail {
10563
10564 std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
10565
10566 class EnumValuesRegistry : public IMutableEnumValuesRegistry {
10567
10568 std::vector<std::unique_ptr<EnumInfo>> m_enumInfos;
10569
10570 EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
10571 };
10572
10573 std::vector<StringRef> parseEnums( StringRef enums );
10574
10575 } // Detail
10576
10577} // Catch
10578
10579// end catch_enum_values_registry.h
10580
10581#include <map>
10582#include <cassert>
10583
10584namespace Catch {
10585
10586 IMutableEnumValuesRegistry::~IMutableEnumValuesRegistry() {}
10587
10588 namespace Detail {
10589
10590 namespace {
10591 // Extracts the actual name part of an enum instance
10592 // In other words, it returns the Blue part of Bikeshed::Colour::Blue
10593 StringRef extractInstanceName(StringRef enumInstance) {
10594 // Find last occurrence of ":"
10595 size_t name_start = enumInstance.size();
10596 while (name_start > 0 && enumInstance[name_start - 1] != ':') {
10597 --name_start;
10598 }
10599 return enumInstance.substr(name_start, enumInstance.size() - name_start);
10600 }
10601 }
10602
10603 std::vector<StringRef> parseEnums( StringRef enums ) {
10604 auto enumValues = splitStringRef( enums, ',' );
10605 std::vector<StringRef> parsed;
10606 parsed.reserve( enumValues.size() );
10607 for( auto const& enumValue : enumValues ) {
10608 parsed.push_back(trim(extractInstanceName(enumValue)));
10609 }
10610 return parsed;
10611 }
10612
10613 EnumInfo::~EnumInfo() {}
10614
10615 StringRef EnumInfo::lookup( int value ) const {
10616 for( auto const& valueToName : m_values ) {
10617 if( valueToName.first == value )
10618 return valueToName.second;
10619 }
10620 return "{** unexpected enum value **}"_sr;
10621 }
10622
10623 std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
10624 std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
10625 enumInfo->m_name = enumName;
10626 enumInfo->m_values.reserve( values.size() );
10627
10628 const auto valueNames = Catch::Detail::parseEnums( allValueNames );
10629 assert( valueNames.size() == values.size() );
10630 std::size_t i = 0;
10631 for( auto value : values )
10632 enumInfo->m_values.emplace_back(value, valueNames[i++]);
10633
10634 return enumInfo;
10635 }
10636
10637 EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
10638 m_enumInfos.push_back(makeEnumInfo(enumName, allValueNames, values));
10639 return *m_enumInfos.back();
10640 }
10641
10642 } // Detail
10643} // Catch
10644
10645// end catch_enum_values_registry.cpp
10646// start catch_errno_guard.cpp
10647
10648#include <cerrno>
10649
10650namespace Catch {
10651 ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
10652 ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
10653}
10654// end catch_errno_guard.cpp
10655// start catch_exception_translator_registry.cpp
10656
10657// start catch_exception_translator_registry.h
10658
10659#include <vector>
10660#include <string>
10661#include <memory>
10662
10663namespace Catch {
10664
10665 class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
10666 public:
10667 ~ExceptionTranslatorRegistry();
10668 virtual void registerTranslator( const IExceptionTranslator* translator );
10669 std::string translateActiveException() const override;
10670 std::string tryTranslators() const;
10671
10672 private:
10673 std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
10674 };
10675}
10676
10677// end catch_exception_translator_registry.h
10678#ifdef __OBJC__
10679#import "Foundation/Foundation.h"
10680#endif
10681
10682namespace Catch {
10683
10684 ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
10685 }
10686
10687 void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
10688 m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
10689 }
10690
10691#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
10692 std::string ExceptionTranslatorRegistry::translateActiveException() const {
10693 try {
10694#ifdef __OBJC__
10695 // In Objective-C try objective-c exceptions first
10696 @try {
10697 return tryTranslators();
10698 }
10699 @catch (NSException *exception) {
10700 return Catch::Detail::stringify( [exception description] );
10701 }
10702#else
10703 // Compiling a mixed mode project with MSVC means that CLR
10704 // exceptions will be caught in (...) as well. However, these
10705 // do not fill-in std::current_exception and thus lead to crash
10706 // when attempting rethrow.
10707 // /EHa switch also causes structured exceptions to be caught
10708 // here, but they fill-in current_exception properly, so
10709 // at worst the output should be a little weird, instead of
10710 // causing a crash.
10711 if (std::current_exception() == nullptr) {
10712 return "Non C++ exception. Possibly a CLR exception.";
10713 }
10714 return tryTranslators();
10715#endif
10716 }
10717 catch( TestFailureException& ) {
10718 std::rethrow_exception(std::current_exception());
10719 }
10720 catch( std::exception& ex ) {
10721 return ex.what();
10722 }
10723 catch( std::string& msg ) {
10724 return msg;
10725 }
10726 catch( const char* msg ) {
10727 return msg;
10728 }
10729 catch(...) {
10730 return "Unknown exception";
10731 }
10732 }
10733
10734 std::string ExceptionTranslatorRegistry::tryTranslators() const {
10735 if (m_translators.empty()) {
10736 std::rethrow_exception(std::current_exception());
10737 } else {
10738 return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
10739 }
10740 }
10741
10742#else // ^^ Exceptions are enabled // Exceptions are disabled vv
10743 std::string ExceptionTranslatorRegistry::translateActiveException() const {
10744 CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10745 }
10746
10747 std::string ExceptionTranslatorRegistry::tryTranslators() const {
10748 CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
10749 }
10750#endif
10751
10752}
10753// end catch_exception_translator_registry.cpp
10754// start catch_fatal_condition.cpp
10755
10756#include <algorithm>
10757
10758#if !defined( CATCH_CONFIG_WINDOWS_SEH ) && !defined( CATCH_CONFIG_POSIX_SIGNALS )
10759
10760namespace Catch {
10761
10762 // If neither SEH nor signal handling is required, the handler impls
10763 // do not have to do anything, and can be empty.
10764 void FatalConditionHandler::engage_platform() {}
10765 void FatalConditionHandler::disengage_platform() {}
10766 FatalConditionHandler::FatalConditionHandler() = default;
10767 FatalConditionHandler::~FatalConditionHandler() = default;
10768
10769} // end namespace Catch
10770
10771#endif // !CATCH_CONFIG_WINDOWS_SEH && !CATCH_CONFIG_POSIX_SIGNALS
10772
10773#if defined( CATCH_CONFIG_WINDOWS_SEH ) && defined( CATCH_CONFIG_POSIX_SIGNALS )
10774#error "Inconsistent configuration: Windows' SEH handling and POSIX signals cannot be enabled at the same time"
10775#endif // CATCH_CONFIG_WINDOWS_SEH && CATCH_CONFIG_POSIX_SIGNALS
10776
10777#if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
10778
10779namespace {
10781 void reportFatal( char const * const message ) {
10782 Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
10783 }
10784
10788 constexpr std::size_t minStackSizeForErrors = 32 * 1024;
10789} // end unnamed namespace
10790
10791#endif // CATCH_CONFIG_WINDOWS_SEH || CATCH_CONFIG_POSIX_SIGNALS
10792
10793#if defined( CATCH_CONFIG_WINDOWS_SEH )
10794
10795namespace Catch {
10796
10797 struct SignalDefs { DWORD id; const char* name; };
10798
10799 // There is no 1-1 mapping between signals and windows exceptions.
10800 // Windows can easily distinguish between SO and SigSegV,
10801 // but SigInt, SigTerm, etc are handled differently.
10802 static SignalDefs signalDefs[] = {
10803 { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
10804 { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
10805 { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
10806 { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
10807 };
10808
10809 static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
10810 for (auto const& def : signalDefs) {
10811 if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
10812 reportFatal(def.name);
10813 }
10814 }
10815 // If its not an exception we care about, pass it along.
10816 // This stops us from eating debugger breaks etc.
10817 return EXCEPTION_CONTINUE_SEARCH;
10818 }
10819
10820 // Since we do not support multiple instantiations, we put these
10821 // into global variables and rely on cleaning them up in outlined
10822 // constructors/destructors
10823 static PVOID exceptionHandlerHandle = nullptr;
10824
10825 // For MSVC, we reserve part of the stack memory for handling
10826 // memory overflow structured exception.
10827 FatalConditionHandler::FatalConditionHandler() {
10828 ULONG guaranteeSize = static_cast<ULONG>(minStackSizeForErrors);
10829 if (!SetThreadStackGuarantee(&guaranteeSize)) {
10830 // We do not want to fully error out, because needing
10831 // the stack reserve should be rare enough anyway.
10832 Catch::cerr()
10833 << "Failed to reserve piece of stack."
10834 << " Stack overflows will not be reported successfully.";
10835 }
10836 }
10837
10838 // We do not attempt to unset the stack guarantee, because
10839 // Windows does not support lowering the stack size guarantee.
10840 FatalConditionHandler::~FatalConditionHandler() = default;
10841
10842 void FatalConditionHandler::engage_platform() {
10843 // Register as first handler in current chain
10844 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
10845 if (!exceptionHandlerHandle) {
10846 CATCH_RUNTIME_ERROR("Could not register vectored exception handler");
10847 }
10848 }
10849
10850 void FatalConditionHandler::disengage_platform() {
10851 if (!RemoveVectoredExceptionHandler(exceptionHandlerHandle)) {
10852 CATCH_RUNTIME_ERROR("Could not unregister vectored exception handler");
10853 }
10854 exceptionHandlerHandle = nullptr;
10855 }
10856
10857} // end namespace Catch
10858
10859#endif // CATCH_CONFIG_WINDOWS_SEH
10860
10861#if defined( CATCH_CONFIG_POSIX_SIGNALS )
10862
10863#include <signal.h>
10864
10865namespace Catch {
10866
10867 struct SignalDefs {
10868 int id;
10869 const char* name;
10870 };
10871
10872 static SignalDefs signalDefs[] = {
10873 { SIGINT, "SIGINT - Terminal interrupt signal" },
10874 { SIGILL, "SIGILL - Illegal instruction signal" },
10875 { SIGFPE, "SIGFPE - Floating point error signal" },
10876 { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
10877 { SIGTERM, "SIGTERM - Termination request signal" },
10878 { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
10879 };
10880
10881// Older GCCs trigger -Wmissing-field-initializers for T foo = {}
10882// which is zero initialization, but not explicit. We want to avoid
10883// that.
10884#if defined(__GNUC__)
10885# pragma GCC diagnostic push
10886# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
10887#endif
10888
10889 static char* altStackMem = nullptr;
10890 static std::size_t altStackSize = 0;
10891 static stack_t oldSigStack{};
10892 static struct sigaction oldSigActions[sizeof(signalDefs) / sizeof(SignalDefs)]{};
10893
10894 static void restorePreviousSignalHandlers() {
10895 // We set signal handlers back to the previous ones. Hopefully
10896 // nobody overwrote them in the meantime, and doesn't expect
10897 // their signal handlers to live past ours given that they
10898 // installed them after ours..
10899 for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
10900 sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
10901 }
10902 // Return the old stack
10903 sigaltstack(&oldSigStack, nullptr);
10904 }
10905
10906 static void handleSignal( int sig ) {
10907 char const * name = "<unknown signal>";
10908 for (auto const& def : signalDefs) {
10909 if (sig == def.id) {
10910 name = def.name;
10911 break;
10912 }
10913 }
10914 // We need to restore previous signal handlers and let them do
10915 // their thing, so that the users can have the debugger break
10916 // when a signal is raised, and so on.
10917 restorePreviousSignalHandlers();
10918 reportFatal( name );
10919 raise( sig );
10920 }
10921
10922 FatalConditionHandler::FatalConditionHandler() {
10923 assert(!altStackMem && "Cannot initialize POSIX signal handler when one already exists");
10924 if (altStackSize == 0) {
10925 altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), minStackSizeForErrors);
10926 }
10927 altStackMem = new char[altStackSize]();
10928 }
10929
10930 FatalConditionHandler::~FatalConditionHandler() {
10931 delete[] altStackMem;
10932 // We signal that another instance can be constructed by zeroing
10933 // out the pointer.
10934 altStackMem = nullptr;
10935 }
10936
10937 void FatalConditionHandler::engage_platform() {
10938 stack_t sigStack;
10939 sigStack.ss_sp = altStackMem;
10940 sigStack.ss_size = altStackSize;
10941 sigStack.ss_flags = 0;
10942 sigaltstack(&sigStack, &oldSigStack);
10943 struct sigaction sa = { };
10944
10945 sa.sa_handler = handleSignal;
10946 sa.sa_flags = SA_ONSTACK;
10947 for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
10948 sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
10949 }
10950 }
10951
10952#if defined(__GNUC__)
10953# pragma GCC diagnostic pop
10954#endif
10955
10956 void FatalConditionHandler::disengage_platform() {
10957 restorePreviousSignalHandlers();
10958 }
10959
10960} // end namespace Catch
10961
10962#endif // CATCH_CONFIG_POSIX_SIGNALS
10963// end catch_fatal_condition.cpp
10964// start catch_generators.cpp
10965
10966#include <limits>
10967#include <set>
10968
10969namespace Catch {
10970
10971IGeneratorTracker::~IGeneratorTracker() {}
10972
10973const char* GeneratorException::what() const noexcept {
10974 return m_msg;
10975}
10976
10977namespace Generators {
10978
10979 GeneratorUntypedBase::~GeneratorUntypedBase() {}
10980
10981 auto acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
10982 return getResultCapture().acquireGeneratorTracker( generatorName, lineInfo );
10983 }
10984
10985} // namespace Generators
10986} // namespace Catch
10987// end catch_generators.cpp
10988// start catch_interfaces_capture.cpp
10989
10990namespace Catch {
10991 IResultCapture::~IResultCapture() = default;
10992}
10993// end catch_interfaces_capture.cpp
10994// start catch_interfaces_config.cpp
10995
10996namespace Catch {
10997 IConfig::~IConfig() = default;
10998}
10999// end catch_interfaces_config.cpp
11000// start catch_interfaces_exception.cpp
11001
11002namespace Catch {
11003 IExceptionTranslator::~IExceptionTranslator() = default;
11004 IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
11005}
11006// end catch_interfaces_exception.cpp
11007// start catch_interfaces_registry_hub.cpp
11008
11009namespace Catch {
11010 IRegistryHub::~IRegistryHub() = default;
11011 IMutableRegistryHub::~IMutableRegistryHub() = default;
11012}
11013// end catch_interfaces_registry_hub.cpp
11014// start catch_interfaces_reporter.cpp
11015
11016// start catch_reporter_listening.h
11017
11018namespace Catch {
11019
11020 class ListeningReporter : public IStreamingReporter {
11021 using Reporters = std::vector<IStreamingReporterPtr>;
11022 Reporters m_listeners;
11023 IStreamingReporterPtr m_reporter = nullptr;
11024 ReporterPreferences m_preferences;
11025
11026 public:
11027 ListeningReporter();
11028
11029 void addListener( IStreamingReporterPtr&& listener );
11030 void addReporter( IStreamingReporterPtr&& reporter );
11031
11032 public: // IStreamingReporter
11033
11034 ReporterPreferences getPreferences() const override;
11035
11036 void noMatchingTestCases( std::string const& spec ) override;
11037
11038 void reportInvalidArguments(std::string const&arg) override;
11039
11040 static std::set<Verbosity> getSupportedVerbosities();
11041
11042#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
11043 void benchmarkPreparing(std::string const& name) override;
11044 void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
11045 void benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) override;
11046 void benchmarkFailed(std::string const&) override;
11047#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
11048
11049 void testRunStarting( TestRunInfo const& testRunInfo ) override;
11050 void testGroupStarting( GroupInfo const& groupInfo ) override;
11051 void testCaseStarting( TestCaseInfo const& testInfo ) override;
11052 void sectionStarting( SectionInfo const& sectionInfo ) override;
11053 void assertionStarting( AssertionInfo const& assertionInfo ) override;
11054
11055 // The return value indicates if the messages buffer should be cleared:
11056 bool assertionEnded( AssertionStats const& assertionStats ) override;
11057 void sectionEnded( SectionStats const& sectionStats ) override;
11058 void testCaseEnded( TestCaseStats const& testCaseStats ) override;
11059 void testGroupEnded( TestGroupStats const& testGroupStats ) override;
11060 void testRunEnded( TestRunStats const& testRunStats ) override;
11061
11062 void skipTest( TestCaseInfo const& testInfo ) override;
11063 bool isMulti() const override;
11064
11065 };
11066
11067} // end namespace Catch
11068
11069// end catch_reporter_listening.h
11070namespace Catch {
11071
11072 ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
11073 : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
11074
11075 ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
11076 : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
11077
11078 std::ostream& ReporterConfig::stream() const { return *m_stream; }
11079 IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
11080
11081 TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
11082
11083 GroupInfo::GroupInfo( std::string const& _name,
11084 std::size_t _groupIndex,
11085 std::size_t _groupsCount )
11086 : name( _name ),
11087 groupIndex( _groupIndex ),
11088 groupsCounts( _groupsCount )
11089 {}
11090
11091 AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
11092 std::vector<MessageInfo> const& _infoMessages,
11093 Totals const& _totals )
11094 : assertionResult( _assertionResult ),
11095 infoMessages( _infoMessages ),
11096 totals( _totals )
11097 {
11098 assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
11099
11100 if( assertionResult.hasMessage() ) {
11101 // Copy message into messages list.
11102 // !TBD This should have been done earlier, somewhere
11103 MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
11104 builder << assertionResult.getMessage();
11105 builder.m_info.message = builder.m_stream.str();
11106
11107 infoMessages.push_back( builder.m_info );
11108 }
11109 }
11110
11111 AssertionStats::~AssertionStats() = default;
11112
11113 SectionStats::SectionStats( SectionInfo const& _sectionInfo,
11114 Counts const& _assertions,
11115 double _durationInSeconds,
11116 bool _missingAssertions )
11117 : sectionInfo( _sectionInfo ),
11118 assertions( _assertions ),
11119 durationInSeconds( _durationInSeconds ),
11120 missingAssertions( _missingAssertions )
11121 {}
11122
11123 SectionStats::~SectionStats() = default;
11124
11125 TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
11126 Totals const& _totals,
11127 std::string const& _stdOut,
11128 std::string const& _stdErr,
11129 bool _aborting )
11130 : testInfo( _testInfo ),
11131 totals( _totals ),
11132 stdOut( _stdOut ),
11133 stdErr( _stdErr ),
11134 aborting( _aborting )
11135 {}
11136
11137 TestCaseStats::~TestCaseStats() = default;
11138
11139 TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
11140 Totals const& _totals,
11141 bool _aborting )
11142 : groupInfo( _groupInfo ),
11143 totals( _totals ),
11144 aborting( _aborting )
11145 {}
11146
11147 TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
11148 : groupInfo( _groupInfo ),
11149 aborting( false )
11150 {}
11151
11152 TestGroupStats::~TestGroupStats() = default;
11153
11154 TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
11155 Totals const& _totals,
11156 bool _aborting )
11157 : runInfo( _runInfo ),
11158 totals( _totals ),
11159 aborting( _aborting )
11160 {}
11161
11162 TestRunStats::~TestRunStats() = default;
11163
11164 void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
11165 bool IStreamingReporter::isMulti() const { return false; }
11166
11167 IReporterFactory::~IReporterFactory() = default;
11168 IReporterRegistry::~IReporterRegistry() = default;
11169
11170} // end namespace Catch
11171// end catch_interfaces_reporter.cpp
11172// start catch_interfaces_runner.cpp
11173
11174namespace Catch {
11175 IRunner::~IRunner() = default;
11176}
11177// end catch_interfaces_runner.cpp
11178// start catch_interfaces_testcase.cpp
11179
11180namespace Catch {
11181 ITestInvoker::~ITestInvoker() = default;
11182 ITestCaseRegistry::~ITestCaseRegistry() = default;
11183}
11184// end catch_interfaces_testcase.cpp
11185// start catch_leak_detector.cpp
11186
11187#ifdef CATCH_CONFIG_WINDOWS_CRTDBG
11188#include <crtdbg.h>
11189
11190namespace Catch {
11191
11192 LeakDetector::LeakDetector() {
11193 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
11194 flag |= _CRTDBG_LEAK_CHECK_DF;
11195 flag |= _CRTDBG_ALLOC_MEM_DF;
11196 _CrtSetDbgFlag(flag);
11197 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
11198 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
11199 // Change this to leaking allocation's number to break there
11200 _CrtSetBreakAlloc(-1);
11201 }
11202}
11203
11204#else
11205
11206 Catch::LeakDetector::LeakDetector() {}
11207
11208#endif
11209
11210Catch::LeakDetector::~LeakDetector() {
11211 Catch::cleanUp();
11212}
11213// end catch_leak_detector.cpp
11214// start catch_list.cpp
11215
11216// start catch_list.h
11217
11218#include <set>
11219
11220namespace Catch {
11221
11222 std::size_t listTests( Config const& config );
11223
11224 std::size_t listTestsNamesOnly( Config const& config );
11225
11226 struct TagInfo {
11227 void add( std::string const& spelling );
11228 std::string all() const;
11229
11230 std::set<std::string> spellings;
11231 std::size_t count = 0;
11232 };
11233
11234 std::size_t listTags( Config const& config );
11235
11236 std::size_t listReporters();
11237
11238 Option<std::size_t> list( std::shared_ptr<Config> const& config );
11239
11240} // end namespace Catch
11241
11242// end catch_list.h
11243// start catch_text.h
11244
11245namespace Catch {
11246 using namespace clara::TextFlow;
11247}
11248
11249// end catch_text.h
11250#include <limits>
11251#include <algorithm>
11252#include <iomanip>
11253
11254namespace Catch {
11255
11256 std::size_t listTests( Config const& config ) {
11257 TestSpec const& testSpec = config.testSpec();
11258 if( config.hasTestFilters() )
11259 Catch::cout() << "Matching test cases:\n";
11260 else {
11261 Catch::cout() << "All available test cases:\n";
11262 }
11263
11264 auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11265 for( auto const& testCaseInfo : matchedTestCases ) {
11266 Colour::Code colour = testCaseInfo.isHidden()
11267 ? Colour::SecondaryText
11268 : Colour::None;
11269 Colour colourGuard( colour );
11270
11271 Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
11272 if( config.verbosity() >= Verbosity::High ) {
11273 Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
11274 std::string description = testCaseInfo.description;
11275 if( description.empty() )
11276 description = "(NO DESCRIPTION)";
11277 Catch::cout() << Column( description ).indent(4) << std::endl;
11278 }
11279 if( !testCaseInfo.tags.empty() )
11280 Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
11281 }
11282
11283 if( !config.hasTestFilters() )
11284 Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
11285 else
11286 Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
11287 return matchedTestCases.size();
11288 }
11289
11290 std::size_t listTestsNamesOnly( Config const& config ) {
11291 TestSpec const& testSpec = config.testSpec();
11292 std::size_t matchedTests = 0;
11293 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11294 for( auto const& testCaseInfo : matchedTestCases ) {
11295 matchedTests++;
11296 if( startsWith( testCaseInfo.name, '#' ) )
11297 Catch::cout() << '"' << testCaseInfo.name << '"';
11298 else
11299 Catch::cout() << testCaseInfo.name;
11300 if ( config.verbosity() >= Verbosity::High )
11301 Catch::cout() << "\t@" << testCaseInfo.lineInfo;
11302 Catch::cout() << std::endl;
11303 }
11304 return matchedTests;
11305 }
11306
11307 void TagInfo::add( std::string const& spelling ) {
11308 ++count;
11309 spellings.insert( spelling );
11310 }
11311
11312 std::string TagInfo::all() const {
11313 size_t size = 0;
11314 for (auto const& spelling : spellings) {
11315 // Add 2 for the brackes
11316 size += spelling.size() + 2;
11317 }
11318
11319 std::string out; out.reserve(size);
11320 for (auto const& spelling : spellings) {
11321 out += '[';
11322 out += spelling;
11323 out += ']';
11324 }
11325 return out;
11326 }
11327
11328 std::size_t listTags( Config const& config ) {
11329 TestSpec const& testSpec = config.testSpec();
11330 if( config.hasTestFilters() )
11331 Catch::cout() << "Tags for matching test cases:\n";
11332 else {
11333 Catch::cout() << "All available tags:\n";
11334 }
11335
11336 std::map<std::string, TagInfo> tagCounts;
11337
11338 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
11339 for( auto const& testCase : matchedTestCases ) {
11340 for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
11341 std::string lcaseTagName = toLower( tagName );
11342 auto countIt = tagCounts.find( lcaseTagName );
11343 if( countIt == tagCounts.end() )
11344 countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
11345 countIt->second.add( tagName );
11346 }
11347 }
11348
11349 for( auto const& tagCount : tagCounts ) {
11350 ReusableStringStream rss;
11351 rss << " " << std::setw(2) << tagCount.second.count << " ";
11352 auto str = rss.str();
11353 auto wrapper = Column( tagCount.second.all() )
11354 .initialIndent( 0 )
11355 .indent( str.size() )
11356 .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
11357 Catch::cout() << str << wrapper << '\n';
11358 }
11359 Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
11360 return tagCounts.size();
11361 }
11362
11363 std::size_t listReporters() {
11364 Catch::cout() << "Available reporters:\n";
11365 IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
11366 std::size_t maxNameLen = 0;
11367 for( auto const& factoryKvp : factories )
11368 maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
11369
11370 for( auto const& factoryKvp : factories ) {
11371 Catch::cout()
11372 << Column( factoryKvp.first + ":" )
11373 .indent(2)
11374 .width( 5+maxNameLen )
11375 + Column( factoryKvp.second->getDescription() )
11376 .initialIndent(0)
11377 .indent(2)
11378 .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
11379 << "\n";
11380 }
11381 Catch::cout() << std::endl;
11382 return factories.size();
11383 }
11384
11385 Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
11386 Option<std::size_t> listedCount;
11387 getCurrentMutableContext().setConfig( config );
11388 if( config->listTests() )
11389 listedCount = listedCount.valueOr(0) + listTests( *config );
11390 if( config->listTestNamesOnly() )
11391 listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
11392 if( config->listTags() )
11393 listedCount = listedCount.valueOr(0) + listTags( *config );
11394 if( config->listReporters() )
11395 listedCount = listedCount.valueOr(0) + listReporters();
11396 return listedCount;
11397 }
11398
11399} // end namespace Catch
11400// end catch_list.cpp
11401// start catch_matchers.cpp
11402
11403namespace Catch {
11404namespace Matchers {
11405 namespace Impl {
11406
11407 std::string MatcherUntypedBase::toString() const {
11408 if( m_cachedToString.empty() )
11409 m_cachedToString = describe();
11410 return m_cachedToString;
11411 }
11412
11413 MatcherUntypedBase::~MatcherUntypedBase() = default;
11414
11415 } // namespace Impl
11416} // namespace Matchers
11417
11418using namespace Matchers;
11419using Matchers::Impl::MatcherBase;
11420
11421} // namespace Catch
11422// end catch_matchers.cpp
11423// start catch_matchers_exception.cpp
11424
11425namespace Catch {
11426namespace Matchers {
11427namespace Exception {
11428
11429bool ExceptionMessageMatcher::match(std::exception const& ex) const {
11430 return ex.what() == m_message;
11431}
11432
11433std::string ExceptionMessageMatcher::describe() const {
11434 return "exception message matches \"" + m_message + "\"";
11435}
11436
11437}
11438Exception::ExceptionMessageMatcher Message(std::string const& message) {
11439 return Exception::ExceptionMessageMatcher(message);
11440}
11441
11442// namespace Exception
11443} // namespace Matchers
11444} // namespace Catch
11445// end catch_matchers_exception.cpp
11446// start catch_matchers_floating.cpp
11447
11448// start catch_polyfills.hpp
11449
11450namespace Catch {
11451 bool isnan(float f);
11452 bool isnan(double d);
11453}
11454
11455// end catch_polyfills.hpp
11456// start catch_to_string.hpp
11457
11458#include <string>
11459
11460namespace Catch {
11461 template <typename T>
11462 std::string to_string(T const& t) {
11463#if defined(CATCH_CONFIG_CPP11_TO_STRING)
11464 return std::to_string(t);
11465#else
11466 ReusableStringStream rss;
11467 rss << t;
11468 return rss.str();
11469#endif
11470 }
11471} // end namespace Catch
11472
11473// end catch_to_string.hpp
11474#include <algorithm>
11475#include <cmath>
11476#include <cstdlib>
11477#include <cstdint>
11478#include <cstring>
11479#include <sstream>
11480#include <type_traits>
11481#include <iomanip>
11482#include <limits>
11483
11484namespace Catch {
11485namespace {
11486
11487 int32_t convert(float f) {
11488 static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
11489 int32_t i;
11490 std::memcpy(&i, &f, sizeof(f));
11491 return i;
11492 }
11493
11494 int64_t convert(double d) {
11495 static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
11496 int64_t i;
11497 std::memcpy(&i, &d, sizeof(d));
11498 return i;
11499 }
11500
11501 template <typename FP>
11502 bool almostEqualUlps(FP lhs, FP rhs, uint64_t maxUlpDiff) {
11503 // Comparison with NaN should always be false.
11504 // This way we can rule it out before getting into the ugly details
11505 if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
11506 return false;
11507 }
11508
11509 auto lc = convert(lhs);
11510 auto rc = convert(rhs);
11511
11512 if ((lc < 0) != (rc < 0)) {
11513 // Potentially we can have +0 and -0
11514 return lhs == rhs;
11515 }
11516
11517 // static cast as a workaround for IBM XLC
11518 auto ulpDiff = std::abs(static_cast<FP>(lc - rc));
11519 return static_cast<uint64_t>(ulpDiff) <= maxUlpDiff;
11520 }
11521
11522#if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11523
11524 float nextafter(float x, float y) {
11525 return ::nextafterf(x, y);
11526 }
11527
11528 double nextafter(double x, double y) {
11529 return ::nextafter(x, y);
11530 }
11531
11532#endif // ^^^ CATCH_CONFIG_GLOBAL_NEXTAFTER ^^^
11533
11534template <typename FP>
11535FP step(FP start, FP direction, uint64_t steps) {
11536 for (uint64_t i = 0; i < steps; ++i) {
11537#if defined(CATCH_CONFIG_GLOBAL_NEXTAFTER)
11538 start = Catch::nextafter(start, direction);
11539#else
11540 start = std::nextafter(start, direction);
11541#endif
11542 }
11543 return start;
11544}
11545
11546// Performs equivalent check of std::fabs(lhs - rhs) <= margin
11547// But without the subtraction to allow for INFINITY in comparison
11548bool marginComparison(double lhs, double rhs, double margin) {
11549 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
11550}
11551
11552template <typename FloatingPoint>
11553void write(std::ostream& out, FloatingPoint num) {
11554 out << std::scientific
11555 << std::setprecision(std::numeric_limits<FloatingPoint>::max_digits10 - 1)
11556 << num;
11557}
11558
11559} // end anonymous namespace
11560
11561namespace Matchers {
11562namespace Floating {
11563
11564 enum class FloatingPointKind : uint8_t {
11565 Float,
11566 Double
11567 };
11568
11569 WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
11570 :m_target{ target }, m_margin{ margin } {
11571 CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
11572 << " Margin has to be non-negative.");
11573 }
11574
11575 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
11576 // But without the subtraction to allow for INFINITY in comparison
11577 bool WithinAbsMatcher::match(double const& matchee) const {
11578 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
11579 }
11580
11581 std::string WithinAbsMatcher::describe() const {
11582 return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
11583 }
11584
11585 WithinUlpsMatcher::WithinUlpsMatcher(double target, uint64_t ulps, FloatingPointKind baseType)
11586 :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
11587 CATCH_ENFORCE(m_type == FloatingPointKind::Double
11588 || m_ulps < (std::numeric_limits<uint32_t>::max)(),
11589 "Provided ULP is impossibly large for a float comparison.");
11590 }
11591
11592#if defined(__clang__)
11593#pragma clang diagnostic push
11594// Clang <3.5 reports on the default branch in the switch below
11595#pragma clang diagnostic ignored "-Wunreachable-code"
11596#endif
11597
11598 bool WithinUlpsMatcher::match(double const& matchee) const {
11599 switch (m_type) {
11600 case FloatingPointKind::Float:
11601 return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
11602 case FloatingPointKind::Double:
11603 return almostEqualUlps<double>(matchee, m_target, m_ulps);
11604 default:
11605 CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
11606 }
11607 }
11608
11609#if defined(__clang__)
11610#pragma clang diagnostic pop
11611#endif
11612
11613 std::string WithinUlpsMatcher::describe() const {
11614 std::stringstream ret;
11615
11616 ret << "is within " << m_ulps << " ULPs of ";
11617
11618 if (m_type == FloatingPointKind::Float) {
11619 write(ret, static_cast<float>(m_target));
11620 ret << 'f';
11621 } else {
11622 write(ret, m_target);
11623 }
11624
11625 ret << " ([";
11626 if (m_type == FloatingPointKind::Double) {
11627 write(ret, step(m_target, static_cast<double>(-INFINITY), m_ulps));
11628 ret << ", ";
11629 write(ret, step(m_target, static_cast<double>( INFINITY), m_ulps));
11630 } else {
11631 // We have to cast INFINITY to float because of MinGW, see #1782
11632 write(ret, step(static_cast<float>(m_target), static_cast<float>(-INFINITY), m_ulps));
11633 ret << ", ";
11634 write(ret, step(static_cast<float>(m_target), static_cast<float>( INFINITY), m_ulps));
11635 }
11636 ret << "])";
11637
11638 return ret.str();
11639 }
11640
11641 WithinRelMatcher::WithinRelMatcher(double target, double epsilon):
11642 m_target(target),
11643 m_epsilon(epsilon){
11644 CATCH_ENFORCE(m_epsilon >= 0., "Relative comparison with epsilon < 0 does not make sense.");
11645 CATCH_ENFORCE(m_epsilon < 1., "Relative comparison with epsilon >= 1 does not make sense.");
11646 }
11647
11648 bool WithinRelMatcher::match(double const& matchee) const {
11649 const auto relMargin = m_epsilon * (std::max)(std::fabs(matchee), std::fabs(m_target));
11650 return marginComparison(matchee, m_target,
11651 std::isinf(relMargin)? 0 : relMargin);
11652 }
11653
11654 std::string WithinRelMatcher::describe() const {
11655 Catch::ReusableStringStream sstr;
11656 sstr << "and " << m_target << " are within " << m_epsilon * 100. << "% of each other";
11657 return sstr.str();
11658 }
11659
11660}// namespace Floating
11661
11662Floating::WithinUlpsMatcher WithinULP(double target, uint64_t maxUlpDiff) {
11663 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
11664}
11665
11666Floating::WithinUlpsMatcher WithinULP(float target, uint64_t maxUlpDiff) {
11667 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
11668}
11669
11670Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
11671 return Floating::WithinAbsMatcher(target, margin);
11672}
11673
11674Floating::WithinRelMatcher WithinRel(double target, double eps) {
11675 return Floating::WithinRelMatcher(target, eps);
11676}
11677
11678Floating::WithinRelMatcher WithinRel(double target) {
11679 return Floating::WithinRelMatcher(target, std::numeric_limits<double>::epsilon() * 100);
11680}
11681
11682Floating::WithinRelMatcher WithinRel(float target, float eps) {
11683 return Floating::WithinRelMatcher(target, eps);
11684}
11685
11686Floating::WithinRelMatcher WithinRel(float target) {
11687 return Floating::WithinRelMatcher(target, std::numeric_limits<float>::epsilon() * 100);
11688}
11689
11690} // namespace Matchers
11691} // namespace Catch
11692// end catch_matchers_floating.cpp
11693// start catch_matchers_generic.cpp
11694
11695std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
11696 if (desc.empty()) {
11697 return "matches undescribed predicate";
11698 } else {
11699 return "matches predicate: \"" + desc + '"';
11700 }
11701}
11702// end catch_matchers_generic.cpp
11703// start catch_matchers_string.cpp
11704
11705#include <regex>
11706
11707namespace Catch {
11708namespace Matchers {
11709
11710 namespace StdString {
11711
11712 CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
11713 : m_caseSensitivity( caseSensitivity ),
11714 m_str( adjustString( str ) )
11715 {}
11716 std::string CasedString::adjustString( std::string const& str ) const {
11717 return m_caseSensitivity == CaseSensitive::No
11718 ? toLower( str )
11719 : str;
11720 }
11721 std::string CasedString::caseSensitivitySuffix() const {
11722 return m_caseSensitivity == CaseSensitive::No
11723 ? " (case insensitive)"
11724 : std::string();
11725 }
11726
11727 StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
11728 : m_comparator( comparator ),
11729 m_operation( operation ) {
11730 }
11731
11732 std::string StringMatcherBase::describe() const {
11733 std::string description;
11734 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
11735 m_comparator.caseSensitivitySuffix().size());
11736 description += m_operation;
11737 description += ": \"";
11738 description += m_comparator.m_str;
11739 description += "\"";
11740 description += m_comparator.caseSensitivitySuffix();
11741 return description;
11742 }
11743
11744 EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
11745
11746 bool EqualsMatcher::match( std::string const& source ) const {
11747 return m_comparator.adjustString( source ) == m_comparator.m_str;
11748 }
11749
11750 ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
11751
11752 bool ContainsMatcher::match( std::string const& source ) const {
11753 return contains( m_comparator.adjustString( source ), m_comparator.m_str );
11754 }
11755
11756 StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
11757
11758 bool StartsWithMatcher::match( std::string const& source ) const {
11759 return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11760 }
11761
11762 EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
11763
11764 bool EndsWithMatcher::match( std::string const& source ) const {
11765 return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
11766 }
11767
11768 RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
11769
11770 bool RegexMatcher::match(std::string const& matchee) const {
11771 auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
11772 if (m_caseSensitivity == CaseSensitive::Choice::No) {
11773 flags |= std::regex::icase;
11774 }
11775 auto reg = std::regex(m_regex, flags);
11776 return std::regex_match(matchee, reg);
11777 }
11778
11779 std::string RegexMatcher::describe() const {
11780 return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
11781 }
11782
11783 } // namespace StdString
11784
11785 StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11786 return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
11787 }
11788 StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11789 return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
11790 }
11791 StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11792 return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11793 }
11794 StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
11795 return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
11796 }
11797
11798 StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
11799 return StdString::RegexMatcher(regex, caseSensitivity);
11800 }
11801
11802} // namespace Matchers
11803} // namespace Catch
11804// end catch_matchers_string.cpp
11805// start catch_message.cpp
11806
11807// start catch_uncaught_exceptions.h
11808
11809namespace Catch {
11810 bool uncaught_exceptions();
11811} // end namespace Catch
11812
11813// end catch_uncaught_exceptions.h
11814#include <cassert>
11815#include <stack>
11816
11817namespace Catch {
11818
11819 MessageInfo::MessageInfo( StringRef const& _macroName,
11820 SourceLineInfo const& _lineInfo,
11821 ResultWas::OfType _type )
11822 : macroName( _macroName ),
11823 lineInfo( _lineInfo ),
11824 type( _type ),
11825 sequence( ++globalCount )
11826 {}
11827
11828 bool MessageInfo::operator==( MessageInfo const& other ) const {
11829 return sequence == other.sequence;
11830 }
11831
11832 bool MessageInfo::operator<( MessageInfo const& other ) const {
11833 return sequence < other.sequence;
11834 }
11835
11836 // This may need protecting if threading support is added
11837 unsigned int MessageInfo::globalCount = 0;
11838
11840
11841 Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
11842 SourceLineInfo const& lineInfo,
11843 ResultWas::OfType type )
11844 :m_info(macroName, lineInfo, type) {}
11845
11847
11848 ScopedMessage::ScopedMessage( MessageBuilder const& builder )
11849 : m_info( builder.m_info ), m_moved()
11850 {
11851 m_info.message = builder.m_stream.str();
11852 getResultCapture().pushScopedMessage( m_info );
11853 }
11854
11855 ScopedMessage::ScopedMessage( ScopedMessage&& old )
11856 : m_info( old.m_info ), m_moved()
11857 {
11858 old.m_moved = true;
11859 }
11860
11861 ScopedMessage::~ScopedMessage() {
11862 if ( !uncaught_exceptions() && !m_moved ){
11863 getResultCapture().popScopedMessage(m_info);
11864 }
11865 }
11866
11867 Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
11868 auto trimmed = [&] (size_t start, size_t end) {
11869 while (names[start] == ',' || isspace(static_cast<unsigned char>(names[start]))) {
11870 ++start;
11871 }
11872 while (names[end] == ',' || isspace(static_cast<unsigned char>(names[end]))) {
11873 --end;
11874 }
11875 return names.substr(start, end - start + 1);
11876 };
11877 auto skipq = [&] (size_t start, char quote) {
11878 for (auto i = start + 1; i < names.size() ; ++i) {
11879 if (names[i] == quote)
11880 return i;
11881 if (names[i] == '\\')
11882 ++i;
11883 }
11884 CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
11885 };
11886
11887 size_t start = 0;
11888 std::stack<char> openings;
11889 for (size_t pos = 0; pos < names.size(); ++pos) {
11890 char c = names[pos];
11891 switch (c) {
11892 case '[':
11893 case '{':
11894 case '(':
11895 // It is basically impossible to disambiguate between
11896 // comparison and start of template args in this context
11897// case '<':
11898 openings.push(c);
11899 break;
11900 case ']':
11901 case '}':
11902 case ')':
11903// case '>':
11904 openings.pop();
11905 break;
11906 case '"':
11907 case '\'':
11908 pos = skipq(pos, c);
11909 break;
11910 case ',':
11911 if (start != pos && openings.empty()) {
11912 m_messages.emplace_back(macroName, lineInfo, resultType);
11913 m_messages.back().message = static_cast<std::string>(trimmed(start, pos));
11914 m_messages.back().message += " := ";
11915 start = pos;
11916 }
11917 }
11918 }
11919 assert(openings.empty() && "Mismatched openings");
11920 m_messages.emplace_back(macroName, lineInfo, resultType);
11921 m_messages.back().message = static_cast<std::string>(trimmed(start, names.size() - 1));
11922 m_messages.back().message += " := ";
11923 }
11924 Capturer::~Capturer() {
11925 if ( !uncaught_exceptions() ){
11926 assert( m_captured == m_messages.size() );
11927 for( size_t i = 0; i < m_captured; ++i )
11928 m_resultCapture.popScopedMessage( m_messages[i] );
11929 }
11930 }
11931
11932 void Capturer::captureValue( size_t index, std::string const& value ) {
11933 assert( index < m_messages.size() );
11934 m_messages[index].message += value;
11935 m_resultCapture.pushScopedMessage( m_messages[index] );
11936 m_captured++;
11937 }
11938
11939} // end namespace Catch
11940// end catch_message.cpp
11941// start catch_output_redirect.cpp
11942
11943// start catch_output_redirect.h
11944#ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11945#define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
11946
11947#include <cstdio>
11948#include <iosfwd>
11949#include <string>
11950
11951namespace Catch {
11952
11953 class RedirectedStream {
11954 std::ostream& m_originalStream;
11955 std::ostream& m_redirectionStream;
11956 std::streambuf* m_prevBuf;
11957
11958 public:
11959 RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
11960 ~RedirectedStream();
11961 };
11962
11963 class RedirectedStdOut {
11964 ReusableStringStream m_rss;
11965 RedirectedStream m_cout;
11966 public:
11967 RedirectedStdOut();
11968 auto str() const -> std::string;
11969 };
11970
11971 // StdErr has two constituent streams in C++, std::cerr and std::clog
11972 // This means that we need to redirect 2 streams into 1 to keep proper
11973 // order of writes
11974 class RedirectedStdErr {
11975 ReusableStringStream m_rss;
11976 RedirectedStream m_cerr;
11977 RedirectedStream m_clog;
11978 public:
11979 RedirectedStdErr();
11980 auto str() const -> std::string;
11981 };
11982
11983 class RedirectedStreams {
11984 public:
11985 RedirectedStreams(RedirectedStreams const&) = delete;
11986 RedirectedStreams& operator=(RedirectedStreams const&) = delete;
11987 RedirectedStreams(RedirectedStreams&&) = delete;
11988 RedirectedStreams& operator=(RedirectedStreams&&) = delete;
11989
11990 RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
11991 ~RedirectedStreams();
11992 private:
11993 std::string& m_redirectedCout;
11994 std::string& m_redirectedCerr;
11995 RedirectedStdOut m_redirectedStdOut;
11996 RedirectedStdErr m_redirectedStdErr;
11997 };
11998
11999#if defined(CATCH_CONFIG_NEW_CAPTURE)
12000
12001 // Windows's implementation of std::tmpfile is terrible (it tries
12002 // to create a file inside system folder, thus requiring elevated
12003 // privileges for the binary), so we have to use tmpnam(_s) and
12004 // create the file ourselves there.
12005 class TempFile {
12006 public:
12007 TempFile(TempFile const&) = delete;
12008 TempFile& operator=(TempFile const&) = delete;
12009 TempFile(TempFile&&) = delete;
12010 TempFile& operator=(TempFile&&) = delete;
12011
12012 TempFile();
12013 ~TempFile();
12014
12015 std::FILE* getFile();
12016 std::string getContents();
12017
12018 private:
12019 std::FILE* m_file = nullptr;
12020 #if defined(_MSC_VER)
12021 char m_buffer[L_tmpnam] = { 0 };
12022 #endif
12023 };
12024
12025 class OutputRedirect {
12026 public:
12027 OutputRedirect(OutputRedirect const&) = delete;
12028 OutputRedirect& operator=(OutputRedirect const&) = delete;
12029 OutputRedirect(OutputRedirect&&) = delete;
12030 OutputRedirect& operator=(OutputRedirect&&) = delete;
12031
12032 OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
12033 ~OutputRedirect();
12034
12035 private:
12036 int m_originalStdout = -1;
12037 int m_originalStderr = -1;
12038 TempFile m_stdoutFile;
12039 TempFile m_stderrFile;
12040 std::string& m_stdoutDest;
12041 std::string& m_stderrDest;
12042 };
12043
12044#endif
12045
12046} // end namespace Catch
12047
12048#endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
12049// end catch_output_redirect.h
12050#include <cstdio>
12051#include <cstring>
12052#include <fstream>
12053#include <sstream>
12054#include <stdexcept>
12055
12056#if defined(CATCH_CONFIG_NEW_CAPTURE)
12057 #if defined(_MSC_VER)
12058 #include <io.h> //_dup and _dup2
12059 #define dup _dup
12060 #define dup2 _dup2
12061 #define fileno _fileno
12062 #else
12063 #include <unistd.h> // dup and dup2
12064 #endif
12065#endif
12066
12067namespace Catch {
12068
12069 RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
12070 : m_originalStream( originalStream ),
12071 m_redirectionStream( redirectionStream ),
12072 m_prevBuf( m_originalStream.rdbuf() )
12073 {
12074 m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
12075 }
12076
12077 RedirectedStream::~RedirectedStream() {
12078 m_originalStream.rdbuf( m_prevBuf );
12079 }
12080
12081 RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
12082 auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
12083
12084 RedirectedStdErr::RedirectedStdErr()
12085 : m_cerr( Catch::cerr(), m_rss.get() ),
12086 m_clog( Catch::clog(), m_rss.get() )
12087 {}
12088 auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
12089
12090 RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
12091 : m_redirectedCout(redirectedCout),
12092 m_redirectedCerr(redirectedCerr)
12093 {}
12094
12095 RedirectedStreams::~RedirectedStreams() {
12096 m_redirectedCout += m_redirectedStdOut.str();
12097 m_redirectedCerr += m_redirectedStdErr.str();
12098 }
12099
12100#if defined(CATCH_CONFIG_NEW_CAPTURE)
12101
12102#if defined(_MSC_VER)
12103 TempFile::TempFile() {
12104 if (tmpnam_s(m_buffer)) {
12105 CATCH_RUNTIME_ERROR("Could not get a temp filename");
12106 }
12107 if (fopen_s(&m_file, m_buffer, "w+")) {
12108 char buffer[100];
12109 if (strerror_s(buffer, errno)) {
12110 CATCH_RUNTIME_ERROR("Could not translate errno to a string");
12111 }
12112 CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
12113 }
12114 }
12115#else
12116 TempFile::TempFile() {
12117 m_file = std::tmpfile();
12118 if (!m_file) {
12119 CATCH_RUNTIME_ERROR("Could not create a temp file.");
12120 }
12121 }
12122
12123#endif
12124
12125 TempFile::~TempFile() {
12126 // TBD: What to do about errors here?
12127 std::fclose(m_file);
12128 // We manually create the file on Windows only, on Linux
12129 // it will be autodeleted
12130#if defined(_MSC_VER)
12131 std::remove(m_buffer);
12132#endif
12133 }
12134
12135 FILE* TempFile::getFile() {
12136 return m_file;
12137 }
12138
12139 std::string TempFile::getContents() {
12140 std::stringstream sstr;
12141 char buffer[100] = {};
12142 std::rewind(m_file);
12143 while (std::fgets(buffer, sizeof(buffer), m_file)) {
12144 sstr << buffer;
12145 }
12146 return sstr.str();
12147 }
12148
12149 OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
12150 m_originalStdout(dup(1)),
12151 m_originalStderr(dup(2)),
12152 m_stdoutDest(stdout_dest),
12153 m_stderrDest(stderr_dest) {
12154 dup2(fileno(m_stdoutFile.getFile()), 1);
12155 dup2(fileno(m_stderrFile.getFile()), 2);
12156 }
12157
12158 OutputRedirect::~OutputRedirect() {
12159 Catch::cout() << std::flush;
12160 fflush(stdout);
12161 // Since we support overriding these streams, we flush cerr
12162 // even though std::cerr is unbuffered
12163 Catch::cerr() << std::flush;
12164 Catch::clog() << std::flush;
12165 fflush(stderr);
12166
12167 dup2(m_originalStdout, 1);
12168 dup2(m_originalStderr, 2);
12169
12170 m_stdoutDest += m_stdoutFile.getContents();
12171 m_stderrDest += m_stderrFile.getContents();
12172 }
12173
12174#endif // CATCH_CONFIG_NEW_CAPTURE
12175
12176} // namespace Catch
12177
12178#if defined(CATCH_CONFIG_NEW_CAPTURE)
12179 #if defined(_MSC_VER)
12180 #undef dup
12181 #undef dup2
12182 #undef fileno
12183 #endif
12184#endif
12185// end catch_output_redirect.cpp
12186// start catch_polyfills.cpp
12187
12188#include <cmath>
12189
12190namespace Catch {
12191
12192#if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
12193 bool isnan(float f) {
12194 return std::isnan(f);
12195 }
12196 bool isnan(double d) {
12197 return std::isnan(d);
12198 }
12199#else
12200 // For now we only use this for embarcadero
12201 bool isnan(float f) {
12202 return std::_isnan(f);
12203 }
12204 bool isnan(double d) {
12205 return std::_isnan(d);
12206 }
12207#endif
12208
12209} // end namespace Catch
12210// end catch_polyfills.cpp
12211// start catch_random_number_generator.cpp
12212
12213namespace Catch {
12214
12215namespace {
12216
12217#if defined(_MSC_VER)
12218#pragma warning(push)
12219#pragma warning(disable:4146) // we negate uint32 during the rotate
12220#endif
12221 // Safe rotr implementation thanks to John Regehr
12222 uint32_t rotate_right(uint32_t val, uint32_t count) {
12223 const uint32_t mask = 31;
12224 count &= mask;
12225 return (val >> count) | (val << (-count & mask));
12226 }
12227
12228#if defined(_MSC_VER)
12229#pragma warning(pop)
12230#endif
12231
12232}
12233
12234 SimplePcg32::SimplePcg32(result_type seed_) {
12235 seed(seed_);
12236 }
12237
12238 void SimplePcg32::seed(result_type seed_) {
12239 m_state = 0;
12240 (*this)();
12241 m_state += seed_;
12242 (*this)();
12243 }
12244
12245 void SimplePcg32::discard(uint64_t skip) {
12246 // We could implement this to run in O(log n) steps, but this
12247 // should suffice for our use case.
12248 for (uint64_t s = 0; s < skip; ++s) {
12249 static_cast<void>((*this)());
12250 }
12251 }
12252
12253 SimplePcg32::result_type SimplePcg32::operator()() {
12254 // prepare the output value
12255 const uint32_t xorshifted = static_cast<uint32_t>(((m_state >> 18u) ^ m_state) >> 27u);
12256 const auto output = rotate_right(xorshifted, m_state >> 59u);
12257
12258 // advance state
12259 m_state = m_state * 6364136223846793005ULL + s_inc;
12260
12261 return output;
12262 }
12263
12264 bool operator==(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
12265 return lhs.m_state == rhs.m_state;
12266 }
12267
12268 bool operator!=(SimplePcg32 const& lhs, SimplePcg32 const& rhs) {
12269 return lhs.m_state != rhs.m_state;
12270 }
12271}
12272// end catch_random_number_generator.cpp
12273// start catch_registry_hub.cpp
12274
12275// start catch_test_case_registry_impl.h
12276
12277#include <vector>
12278#include <set>
12279#include <algorithm>
12280#include <ios>
12281
12282namespace Catch {
12283
12284 class TestCase;
12285 struct IConfig;
12286
12287 std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
12288
12289 bool isThrowSafe( TestCase const& testCase, IConfig const& config );
12290 bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
12291
12292 void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
12293
12294 std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
12295 std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
12296
12297 class TestRegistry : public ITestCaseRegistry {
12298 public:
12299 virtual ~TestRegistry() = default;
12300
12301 virtual void registerTest( TestCase const& testCase );
12302
12303 std::vector<TestCase> const& getAllTests() const override;
12304 std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
12305
12306 private:
12307 std::vector<TestCase> m_functions;
12308 mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
12309 mutable std::vector<TestCase> m_sortedFunctions;
12310 std::size_t m_unnamedCount = 0;
12311 std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
12312 };
12313
12315
12316 class TestInvokerAsFunction : public ITestInvoker {
12317 void(*m_testAsFunction)();
12318 public:
12319 TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
12320
12321 void invoke() const override;
12322 };
12323
12324 std::string extractClassName( StringRef const& classOrQualifiedMethodName );
12325
12327
12328} // end namespace Catch
12329
12330// end catch_test_case_registry_impl.h
12331// start catch_reporter_registry.h
12332
12333#include <map>
12334
12335namespace Catch {
12336
12337 class ReporterRegistry : public IReporterRegistry {
12338
12339 public:
12340
12341 ~ReporterRegistry() override;
12342
12343 IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
12344
12345 void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
12346 void registerListener( IReporterFactoryPtr const& factory );
12347
12348 FactoryMap const& getFactories() const override;
12349 Listeners const& getListeners() const override;
12350
12351 private:
12352 FactoryMap m_factories;
12353 Listeners m_listeners;
12354 };
12355}
12356
12357// end catch_reporter_registry.h
12358// start catch_tag_alias_registry.h
12359
12360// start catch_tag_alias.h
12361
12362#include <string>
12363
12364namespace Catch {
12365
12366 struct TagAlias {
12367 TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
12368
12369 std::string tag;
12370 SourceLineInfo lineInfo;
12371 };
12372
12373} // end namespace Catch
12374
12375// end catch_tag_alias.h
12376#include <map>
12377
12378namespace Catch {
12379
12380 class TagAliasRegistry : public ITagAliasRegistry {
12381 public:
12382 ~TagAliasRegistry() override;
12383 TagAlias const* find( std::string const& alias ) const override;
12384 std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
12385 void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
12386
12387 private:
12388 std::map<std::string, TagAlias> m_registry;
12389 };
12390
12391} // end namespace Catch
12392
12393// end catch_tag_alias_registry.h
12394// start catch_startup_exception_registry.h
12395
12396#include <vector>
12397#include <exception>
12398
12399namespace Catch {
12400
12401 class StartupExceptionRegistry {
12402#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12403 public:
12404 void add(std::exception_ptr const& exception) noexcept;
12405 std::vector<std::exception_ptr> const& getExceptions() const noexcept;
12406 private:
12407 std::vector<std::exception_ptr> m_exceptions;
12408#endif
12409 };
12410
12411} // end namespace Catch
12412
12413// end catch_startup_exception_registry.h
12414// start catch_singletons.hpp
12415
12416namespace Catch {
12417
12418 struct ISingleton {
12419 virtual ~ISingleton();
12420 };
12421
12422 void addSingleton( ISingleton* singleton );
12423 void cleanupSingletons();
12424
12425 template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
12426 class Singleton : SingletonImplT, public ISingleton {
12427
12428 static auto getInternal() -> Singleton* {
12429 static Singleton* s_instance = nullptr;
12430 if( !s_instance ) {
12431 s_instance = new Singleton;
12432 addSingleton( s_instance );
12433 }
12434 return s_instance;
12435 }
12436
12437 public:
12438 static auto get() -> InterfaceT const& {
12439 return *getInternal();
12440 }
12441 static auto getMutable() -> MutableInterfaceT& {
12442 return *getInternal();
12443 }
12444 };
12445
12446} // namespace Catch
12447
12448// end catch_singletons.hpp
12449namespace Catch {
12450
12451 namespace {
12452
12453 class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
12454 private NonCopyable {
12455
12456 public: // IRegistryHub
12457 RegistryHub() = default;
12458 IReporterRegistry const& getReporterRegistry() const override {
12459 return m_reporterRegistry;
12460 }
12461 ITestCaseRegistry const& getTestCaseRegistry() const override {
12462 return m_testCaseRegistry;
12463 }
12464 IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
12465 return m_exceptionTranslatorRegistry;
12466 }
12467 ITagAliasRegistry const& getTagAliasRegistry() const override {
12468 return m_tagAliasRegistry;
12469 }
12470 StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
12471 return m_exceptionRegistry;
12472 }
12473
12474 public: // IMutableRegistryHub
12475 void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
12476 m_reporterRegistry.registerReporter( name, factory );
12477 }
12478 void registerListener( IReporterFactoryPtr const& factory ) override {
12479 m_reporterRegistry.registerListener( factory );
12480 }
12481 void registerTest( TestCase const& testInfo ) override {
12482 m_testCaseRegistry.registerTest( testInfo );
12483 }
12484 void registerTranslator( const IExceptionTranslator* translator ) override {
12485 m_exceptionTranslatorRegistry.registerTranslator( translator );
12486 }
12487 void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
12488 m_tagAliasRegistry.add( alias, tag, lineInfo );
12489 }
12490 void registerStartupException() noexcept override {
12491#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
12492 m_exceptionRegistry.add(std::current_exception());
12493#else
12494 CATCH_INTERNAL_ERROR("Attempted to register active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
12495#endif
12496 }
12497 IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
12498 return m_enumValuesRegistry;
12499 }
12500
12501 private:
12502 TestRegistry m_testCaseRegistry;
12503 ReporterRegistry m_reporterRegistry;
12504 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
12505 TagAliasRegistry m_tagAliasRegistry;
12506 StartupExceptionRegistry m_exceptionRegistry;
12507 Detail::EnumValuesRegistry m_enumValuesRegistry;
12508 };
12509 }
12510
12511 using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
12512
12513 IRegistryHub const& getRegistryHub() {
12514 return RegistryHubSingleton::get();
12515 }
12516 IMutableRegistryHub& getMutableRegistryHub() {
12517 return RegistryHubSingleton::getMutable();
12518 }
12519 void cleanUp() {
12520 cleanupSingletons();
12521 cleanUpContext();
12522 }
12523 std::string translateActiveException() {
12524 return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
12525 }
12526
12527} // end namespace Catch
12528// end catch_registry_hub.cpp
12529// start catch_reporter_registry.cpp
12530
12531namespace Catch {
12532
12533 ReporterRegistry::~ReporterRegistry() = default;
12534
12535 IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
12536 auto it = m_factories.find( name );
12537 if( it == m_factories.end() )
12538 return nullptr;
12539 return it->second->create( ReporterConfig( config ) );
12540 }
12541
12542 void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
12543 m_factories.emplace(name, factory);
12544 }
12545 void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
12546 m_listeners.push_back( factory );
12547 }
12548
12549 IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
12550 return m_factories;
12551 }
12552 IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
12553 return m_listeners;
12554 }
12555
12556}
12557// end catch_reporter_registry.cpp
12558// start catch_result_type.cpp
12559
12560namespace Catch {
12561
12562 bool isOk( ResultWas::OfType resultType ) {
12563 return ( resultType & ResultWas::FailureBit ) == 0;
12564 }
12565 bool isJustInfo( int flags ) {
12566 return flags == ResultWas::Info;
12567 }
12568
12569 ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
12570 return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
12571 }
12572
12573 bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
12574 bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
12575
12576} // end namespace Catch
12577// end catch_result_type.cpp
12578// start catch_run_context.cpp
12579
12580#include <cassert>
12581#include <algorithm>
12582#include <sstream>
12583
12584namespace Catch {
12585
12586 namespace Generators {
12587 struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
12588 GeneratorBasePtr m_generator;
12589
12590 GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
12591 : TrackerBase( nameAndLocation, ctx, parent )
12592 {}
12593 ~GeneratorTracker();
12594
12595 static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
12596 std::shared_ptr<GeneratorTracker> tracker;
12597
12598 ITracker& currentTracker = ctx.currentTracker();
12599 // Under specific circumstances, the generator we want
12600 // to acquire is also the current tracker. If this is
12601 // the case, we have to avoid looking through current
12602 // tracker's children, and instead return the current
12603 // tracker.
12604 // A case where this check is important is e.g.
12605 // for (int i = 0; i < 5; ++i) {
12606 // int n = GENERATE(1, 2);
12607 // }
12608 //
12609 // without it, the code above creates 5 nested generators.
12610 if (currentTracker.nameAndLocation() == nameAndLocation) {
12611 auto thisTracker = currentTracker.parent().findChild(nameAndLocation);
12612 assert(thisTracker);
12613 assert(thisTracker->isGeneratorTracker());
12614 tracker = std::static_pointer_cast<GeneratorTracker>(thisTracker);
12615 } else if ( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
12616 assert( childTracker );
12617 assert( childTracker->isGeneratorTracker() );
12618 tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
12619 } else {
12620 tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
12621 currentTracker.addChild( tracker );
12622 }
12623
12624 if( !tracker->isComplete() ) {
12625 tracker->open();
12626 }
12627
12628 return *tracker;
12629 }
12630
12631 // TrackerBase interface
12632 bool isGeneratorTracker() const override { return true; }
12633 auto hasGenerator() const -> bool override {
12634 return !!m_generator;
12635 }
12636 void close() override {
12637 TrackerBase::close();
12638 // If a generator has a child (it is followed by a section)
12639 // and none of its children have started, then we must wait
12640 // until later to start consuming its values.
12641 // This catches cases where `GENERATE` is placed between two
12642 // `SECTION`s.
12643 // **The check for m_children.empty cannot be removed**.
12644 // doing so would break `GENERATE` _not_ followed by `SECTION`s.
12645 const bool should_wait_for_child = [&]() {
12646 // No children -> nobody to wait for
12647 if ( m_children.empty() ) {
12648 return false;
12649 }
12650 // If at least one child started executing, don't wait
12651 if ( std::find_if(
12652 m_children.begin(),
12653 m_children.end(),
12654 []( TestCaseTracking::ITrackerPtr tracker ) {
12655 return tracker->hasStarted();
12656 } ) != m_children.end() ) {
12657 return false;
12658 }
12659
12660 // No children have started. We need to check if they _can_
12661 // start, and thus we should wait for them, or they cannot
12662 // start (due to filters), and we shouldn't wait for them
12663 auto* parent = m_parent;
12664 // This is safe: there is always at least one section
12665 // tracker in a test case tracking tree
12666 while ( !parent->isSectionTracker() ) {
12667 parent = &( parent->parent() );
12668 }
12669 assert( parent &&
12670 "Missing root (test case) level section" );
12671
12672 auto const& parentSection =
12673 static_cast<SectionTracker&>( *parent );
12674 auto const& filters = parentSection.getFilters();
12675 // No filters -> no restrictions on running sections
12676 if ( filters.empty() ) {
12677 return true;
12678 }
12679
12680 for ( auto const& child : m_children ) {
12681 if ( child->isSectionTracker() &&
12682 std::find( filters.begin(),
12683 filters.end(),
12684 static_cast<SectionTracker&>( *child )
12685 .trimmedName() ) !=
12686 filters.end() ) {
12687 return true;
12688 }
12689 }
12690 return false;
12691 }();
12692
12693 // This check is a bit tricky, because m_generator->next()
12694 // has a side-effect, where it consumes generator's current
12695 // value, but we do not want to invoke the side-effect if
12696 // this generator is still waiting for any child to start.
12697 if ( should_wait_for_child ||
12698 ( m_runState == CompletedSuccessfully &&
12699 m_generator->next() ) ) {
12700 m_children.clear();
12701 m_runState = Executing;
12702 }
12703 }
12704
12705 // IGeneratorTracker interface
12706 auto getGenerator() const -> GeneratorBasePtr const& override {
12707 return m_generator;
12708 }
12709 void setGenerator( GeneratorBasePtr&& generator ) override {
12710 m_generator = std::move( generator );
12711 }
12712 };
12713 GeneratorTracker::~GeneratorTracker() {}
12714 }
12715
12716 RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
12717 : m_runInfo(_config->name()),
12718 m_context(getCurrentMutableContext()),
12719 m_config(_config),
12720 m_reporter(std::move(reporter)),
12721 m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
12722 m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
12723 {
12724 m_context.setRunner(this);
12725 m_context.setConfig(m_config);
12726 m_context.setResultCapture(this);
12727 m_reporter->testRunStarting(m_runInfo);
12728 }
12729
12730 RunContext::~RunContext() {
12731 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
12732 }
12733
12734 void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
12735 m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
12736 }
12737
12738 void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
12739 m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
12740 }
12741
12742 Totals RunContext::runTest(TestCase const& testCase) {
12743 Totals prevTotals = m_totals;
12744
12745 std::string redirectedCout;
12746 std::string redirectedCerr;
12747
12748 auto const& testInfo = testCase.getTestCaseInfo();
12749
12750 m_reporter->testCaseStarting(testInfo);
12751
12752 m_activeTestCase = &testCase;
12753
12754 ITracker& rootTracker = m_trackerContext.startRun();
12755 assert(rootTracker.isSectionTracker());
12756 static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
12757 do {
12758 m_trackerContext.startCycle();
12759 m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
12760 runCurrentTest(redirectedCout, redirectedCerr);
12761 } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
12762
12763 Totals deltaTotals = m_totals.delta(prevTotals);
12764 if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
12765 deltaTotals.assertions.failed++;
12766 deltaTotals.testCases.passed--;
12767 deltaTotals.testCases.failed++;
12768 }
12769 m_totals.testCases += deltaTotals.testCases;
12770 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12771 deltaTotals,
12772 redirectedCout,
12773 redirectedCerr,
12774 aborting()));
12775
12776 m_activeTestCase = nullptr;
12777 m_testCaseTracker = nullptr;
12778
12779 return deltaTotals;
12780 }
12781
12782 IConfigPtr RunContext::config() const {
12783 return m_config;
12784 }
12785
12786 IStreamingReporter& RunContext::reporter() const {
12787 return *m_reporter;
12788 }
12789
12790 void RunContext::assertionEnded(AssertionResult const & result) {
12791 if (result.getResultType() == ResultWas::Ok) {
12792 m_totals.assertions.passed++;
12793 m_lastAssertionPassed = true;
12794 } else if (!result.isOk()) {
12795 m_lastAssertionPassed = false;
12796 if( m_activeTestCase->getTestCaseInfo().okToFail() )
12797 m_totals.assertions.failedButOk++;
12798 else
12799 m_totals.assertions.failed++;
12800 }
12801 else {
12802 m_lastAssertionPassed = true;
12803 }
12804
12805 // We have no use for the return value (whether messages should be cleared), because messages were made scoped
12806 // and should be let to clear themselves out.
12807 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
12808
12809 if (result.getResultType() != ResultWas::Warning)
12810 m_messageScopes.clear();
12811
12812 // Reset working state
12813 resetAssertionInfo();
12814 m_lastResult = result;
12815 }
12816 void RunContext::resetAssertionInfo() {
12817 m_lastAssertionInfo.macroName = StringRef();
12818 m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
12819 }
12820
12821 bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
12822 ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
12823 if (!sectionTracker.isOpen())
12824 return false;
12825 m_activeSections.push_back(&sectionTracker);
12826
12827 m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
12828
12829 m_reporter->sectionStarting(sectionInfo);
12830
12831 assertions = m_totals.assertions;
12832
12833 return true;
12834 }
12835 auto RunContext::acquireGeneratorTracker( StringRef generatorName, SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
12836 using namespace Generators;
12837 GeneratorTracker& tracker = GeneratorTracker::acquire(m_trackerContext,
12838 TestCaseTracking::NameAndLocation( static_cast<std::string>(generatorName), lineInfo ) );
12839 m_lastAssertionInfo.lineInfo = lineInfo;
12840 return tracker;
12841 }
12842
12843 bool RunContext::testForMissingAssertions(Counts& assertions) {
12844 if (assertions.total() != 0)
12845 return false;
12846 if (!m_config->warnAboutMissingAssertions())
12847 return false;
12848 if (m_trackerContext.currentTracker().hasChildren())
12849 return false;
12850 m_totals.assertions.failed++;
12851 assertions.failed++;
12852 return true;
12853 }
12854
12855 void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
12856 Counts assertions = m_totals.assertions - endInfo.prevAssertions;
12857 bool missingAssertions = testForMissingAssertions(assertions);
12858
12859 if (!m_activeSections.empty()) {
12860 m_activeSections.back()->close();
12861 m_activeSections.pop_back();
12862 }
12863
12864 m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
12865 m_messages.clear();
12866 m_messageScopes.clear();
12867 }
12868
12869 void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
12870 if (m_unfinishedSections.empty())
12871 m_activeSections.back()->fail();
12872 else
12873 m_activeSections.back()->close();
12874 m_activeSections.pop_back();
12875
12876 m_unfinishedSections.push_back(endInfo);
12877 }
12878
12879#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
12880 void RunContext::benchmarkPreparing(std::string const& name) {
12881 m_reporter->benchmarkPreparing(name);
12882 }
12883 void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
12884 m_reporter->benchmarkStarting( info );
12885 }
12886 void RunContext::benchmarkEnded( BenchmarkStats<> const& stats ) {
12887 m_reporter->benchmarkEnded( stats );
12888 }
12889 void RunContext::benchmarkFailed(std::string const & error) {
12890 m_reporter->benchmarkFailed(error);
12891 }
12892#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
12893
12894 void RunContext::pushScopedMessage(MessageInfo const & message) {
12895 m_messages.push_back(message);
12896 }
12897
12898 void RunContext::popScopedMessage(MessageInfo const & message) {
12899 m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
12900 }
12901
12902 void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
12903 m_messageScopes.emplace_back( builder );
12904 }
12905
12906 std::string RunContext::getCurrentTestName() const {
12907 return m_activeTestCase
12908 ? m_activeTestCase->getTestCaseInfo().name
12909 : std::string();
12910 }
12911
12912 const AssertionResult * RunContext::getLastResult() const {
12913 return &(*m_lastResult);
12914 }
12915
12916 void RunContext::exceptionEarlyReported() {
12917 m_shouldReportUnexpected = false;
12918 }
12919
12920 void RunContext::handleFatalErrorCondition( StringRef message ) {
12921 // First notify reporter that bad things happened
12922 m_reporter->fatalErrorEncountered(message);
12923
12924 // Don't rebuild the result -- the stringification itself can cause more fatal errors
12925 // Instead, fake a result data.
12926 AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
12927 tempResult.message = static_cast<std::string>(message);
12928 AssertionResult result(m_lastAssertionInfo, tempResult);
12929
12930 assertionEnded(result);
12931
12932 handleUnfinishedSections();
12933
12934 // Recreate section for test case (as we will lose the one that was in scope)
12935 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12936 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12937
12938 Counts assertions;
12939 assertions.failed = 1;
12940 SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
12941 m_reporter->sectionEnded(testCaseSectionStats);
12942
12943 auto const& testInfo = m_activeTestCase->getTestCaseInfo();
12944
12945 Totals deltaTotals;
12946 deltaTotals.testCases.failed = 1;
12947 deltaTotals.assertions.failed = 1;
12948 m_reporter->testCaseEnded(TestCaseStats(testInfo,
12949 deltaTotals,
12950 std::string(),
12951 std::string(),
12952 false));
12953 m_totals.testCases.failed++;
12954 testGroupEnded(std::string(), m_totals, 1, 1);
12955 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
12956 }
12957
12958 bool RunContext::lastAssertionPassed() {
12959 return m_lastAssertionPassed;
12960 }
12961
12962 void RunContext::assertionPassed() {
12963 m_lastAssertionPassed = true;
12964 ++m_totals.assertions.passed;
12965 resetAssertionInfo();
12966 m_messageScopes.clear();
12967 }
12968
12969 bool RunContext::aborting() const {
12970 return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
12971 }
12972
12973 void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
12974 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
12975 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
12976 m_reporter->sectionStarting(testCaseSection);
12977 Counts prevAssertions = m_totals.assertions;
12978 double duration = 0;
12979 m_shouldReportUnexpected = true;
12980 m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
12981
12982 seedRng(*m_config);
12983
12984 Timer timer;
12985 CATCH_TRY {
12986 if (m_reporter->getPreferences().shouldRedirectStdOut) {
12987#if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
12988 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
12989
12990 timer.start();
12991 invokeActiveTestCase();
12992#else
12993 OutputRedirect r(redirectedCout, redirectedCerr);
12994 timer.start();
12995 invokeActiveTestCase();
12996#endif
12997 } else {
12998 timer.start();
12999 invokeActiveTestCase();
13000 }
13001 duration = timer.getElapsedSeconds();
13002 } CATCH_CATCH_ANON (TestFailureException&) {
13003 // This just means the test was aborted due to failure
13004 } CATCH_CATCH_ALL {
13005 // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
13006 // are reported without translation at the point of origin.
13007 if( m_shouldReportUnexpected ) {
13008 AssertionReaction dummyReaction;
13009 handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
13010 }
13011 }
13012 Counts assertions = m_totals.assertions - prevAssertions;
13013 bool missingAssertions = testForMissingAssertions(assertions);
13014
13015 m_testCaseTracker->close();
13016 handleUnfinishedSections();
13017 m_messages.clear();
13018 m_messageScopes.clear();
13019
13020 SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
13021 m_reporter->sectionEnded(testCaseSectionStats);
13022 }
13023
13024 void RunContext::invokeActiveTestCase() {
13025 FatalConditionHandlerGuard _(&m_fatalConditionhandler);
13026 m_activeTestCase->invoke();
13027 }
13028
13029 void RunContext::handleUnfinishedSections() {
13030 // If sections ended prematurely due to an exception we stored their
13031 // infos here so we can tear them down outside the unwind process.
13032 for (auto it = m_unfinishedSections.rbegin(),
13033 itEnd = m_unfinishedSections.rend();
13034 it != itEnd;
13035 ++it)
13036 sectionEnded(*it);
13037 m_unfinishedSections.clear();
13038 }
13039
13040 void RunContext::handleExpr(
13041 AssertionInfo const& info,
13042 ITransientExpression const& expr,
13043 AssertionReaction& reaction
13044 ) {
13045 m_reporter->assertionStarting( info );
13046
13047 bool negated = isFalseTest( info.resultDisposition );
13048 bool result = expr.getResult() != negated;
13049
13050 if( result ) {
13051 if (!m_includeSuccessfulResults) {
13052 assertionPassed();
13053 }
13054 else {
13055 reportExpr(info, ResultWas::Ok, &expr, negated);
13056 }
13057 }
13058 else {
13059 reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
13060 populateReaction( reaction );
13061 }
13062 }
13063 void RunContext::reportExpr(
13064 AssertionInfo const &info,
13065 ResultWas::OfType resultType,
13066 ITransientExpression const *expr,
13067 bool negated ) {
13068
13069 m_lastAssertionInfo = info;
13070 AssertionResultData data( resultType, LazyExpression( negated ) );
13071
13072 AssertionResult assertionResult{ info, data };
13073 assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
13074
13075 assertionEnded( assertionResult );
13076 }
13077
13078 void RunContext::handleMessage(
13079 AssertionInfo const& info,
13080 ResultWas::OfType resultType,
13081 StringRef const& message,
13082 AssertionReaction& reaction
13083 ) {
13084 m_reporter->assertionStarting( info );
13085
13086 m_lastAssertionInfo = info;
13087
13088 AssertionResultData data( resultType, LazyExpression( false ) );
13089 data.message = static_cast<std::string>(message);
13090 AssertionResult assertionResult{ m_lastAssertionInfo, data };
13091 assertionEnded( assertionResult );
13092 if( !assertionResult.isOk() )
13093 populateReaction( reaction );
13094 }
13095 void RunContext::handleUnexpectedExceptionNotThrown(
13096 AssertionInfo const& info,
13097 AssertionReaction& reaction
13098 ) {
13099 handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
13100 }
13101
13102 void RunContext::handleUnexpectedInflightException(
13103 AssertionInfo const& info,
13104 std::string const& message,
13105 AssertionReaction& reaction
13106 ) {
13107 m_lastAssertionInfo = info;
13108
13109 AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
13110 data.message = message;
13111 AssertionResult assertionResult{ info, data };
13112 assertionEnded( assertionResult );
13113 populateReaction( reaction );
13114 }
13115
13116 void RunContext::populateReaction( AssertionReaction& reaction ) {
13117 reaction.shouldDebugBreak = m_config->shouldDebugBreak();
13118 reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
13119 }
13120
13121 void RunContext::handleIncomplete(
13122 AssertionInfo const& info
13123 ) {
13124 m_lastAssertionInfo = info;
13125
13126 AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
13127 data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
13128 AssertionResult assertionResult{ info, data };
13129 assertionEnded( assertionResult );
13130 }
13131 void RunContext::handleNonExpr(
13132 AssertionInfo const &info,
13133 ResultWas::OfType resultType,
13134 AssertionReaction &reaction
13135 ) {
13136 m_lastAssertionInfo = info;
13137
13138 AssertionResultData data( resultType, LazyExpression( false ) );
13139 AssertionResult assertionResult{ info, data };
13140 assertionEnded( assertionResult );
13141
13142 if( !assertionResult.isOk() )
13143 populateReaction( reaction );
13144 }
13145
13146 IResultCapture& getResultCapture() {
13147 if (auto* capture = getCurrentContext().getResultCapture())
13148 return *capture;
13149 else
13150 CATCH_INTERNAL_ERROR("No result capture instance");
13151 }
13152
13153 void seedRng(IConfig const& config) {
13154 if (config.rngSeed() != 0) {
13155 std::srand(config.rngSeed());
13156 rng().seed(config.rngSeed());
13157 }
13158 }
13159
13160 unsigned int rngSeed() {
13161 return getCurrentContext().getConfig()->rngSeed();
13162 }
13163
13164}
13165// end catch_run_context.cpp
13166// start catch_section.cpp
13167
13168namespace Catch {
13169
13170 Section::Section( SectionInfo const& info )
13171 : m_info( info ),
13172 m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
13173 {
13174 m_timer.start();
13175 }
13176
13177 Section::~Section() {
13178 if( m_sectionIncluded ) {
13179 SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
13180 if( uncaught_exceptions() )
13181 getResultCapture().sectionEndedEarly( endInfo );
13182 else
13183 getResultCapture().sectionEnded( endInfo );
13184 }
13185 }
13186
13187 // This indicates whether the section should be executed or not
13188 Section::operator bool() const {
13189 return m_sectionIncluded;
13190 }
13191
13192} // end namespace Catch
13193// end catch_section.cpp
13194// start catch_section_info.cpp
13195
13196namespace Catch {
13197
13198 SectionInfo::SectionInfo
13199 ( SourceLineInfo const& _lineInfo,
13200 std::string const& _name )
13201 : name( _name ),
13202 lineInfo( _lineInfo )
13203 {}
13204
13205} // end namespace Catch
13206// end catch_section_info.cpp
13207// start catch_session.cpp
13208
13209// start catch_session.h
13210
13211#include <memory>
13212
13213namespace Catch {
13214
13215 class Session : NonCopyable {
13216 public:
13217
13218 Session();
13219 ~Session() override;
13220
13221 void showHelp() const;
13222 void libIdentify();
13223
13224 int applyCommandLine( int argc, char const * const * argv );
13225 #if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13226 int applyCommandLine( int argc, wchar_t const * const * argv );
13227 #endif
13228
13229 void useConfigData( ConfigData const& configData );
13230
13231 template<typename CharT>
13232 int run(int argc, CharT const * const argv[]) {
13233 if (m_startupExceptions)
13234 return 1;
13235 int returnCode = applyCommandLine(argc, argv);
13236 if (returnCode == 0)
13237 returnCode = run();
13238 return returnCode;
13239 }
13240
13241 int run();
13242
13243 clara::Parser const& cli() const;
13244 void cli( clara::Parser const& newParser );
13245 ConfigData& configData();
13246 Config& config();
13247 private:
13248 int runInternal();
13249
13250 clara::Parser m_cli;
13251 ConfigData m_configData;
13252 std::shared_ptr<Config> m_config;
13253 bool m_startupExceptions = false;
13254 };
13255
13256} // end namespace Catch
13257
13258// end catch_session.h
13259// start catch_version.h
13260
13261#include <iosfwd>
13262
13263namespace Catch {
13264
13265 // Versioning information
13266 struct Version {
13267 Version( Version const& ) = delete;
13268 Version& operator=( Version const& ) = delete;
13269 Version( unsigned int _majorVersion,
13270 unsigned int _minorVersion,
13271 unsigned int _patchNumber,
13272 char const * const _branchName,
13273 unsigned int _buildNumber );
13274
13275 unsigned int const majorVersion;
13276 unsigned int const minorVersion;
13277 unsigned int const patchNumber;
13278
13279 // buildNumber is only used if branchName is not null
13280 char const * const branchName;
13281 unsigned int const buildNumber;
13282
13283 friend std::ostream& operator << ( std::ostream& os, Version const& version );
13284 };
13285
13286 Version const& libraryVersion();
13287}
13288
13289// end catch_version.h
13290#include <cstdlib>
13291#include <iomanip>
13292#include <set>
13293#include <iterator>
13294
13295namespace Catch {
13296
13297 namespace {
13298 const int MaxExitCode = 255;
13299
13300 IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
13301 auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
13302 CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
13303
13304 return reporter;
13305 }
13306
13307 IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
13308 if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
13309 return createReporter(config->getReporterName(), config);
13310 }
13311
13312 // On older platforms, returning std::unique_ptr<ListeningReporter>
13313 // when the return type is std::unique_ptr<IStreamingReporter>
13314 // doesn't compile without a std::move call. However, this causes
13315 // a warning on newer platforms. Thus, we have to work around
13316 // it a bit and downcast the pointer manually.
13317 auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
13318 auto& multi = static_cast<ListeningReporter&>(*ret);
13319 auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
13320 for (auto const& listener : listeners) {
13321 multi.addListener(listener->create(Catch::ReporterConfig(config)));
13322 }
13323 multi.addReporter(createReporter(config->getReporterName(), config));
13324 return ret;
13325 }
13326
13327 class TestGroup {
13328 public:
13329 explicit TestGroup(std::shared_ptr<Config> const& config)
13330 : m_config{config}
13331 , m_context{config, makeReporter(config)}
13332 {
13333 auto const& allTestCases = getAllTestCasesSorted(*m_config);
13334 m_matches = m_config->testSpec().matchesByFilter(allTestCases, *m_config);
13335 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13336
13337 if (m_matches.empty() && invalidArgs.empty()) {
13338 for (auto const& test : allTestCases)
13339 if (!test.isHidden())
13340 m_tests.emplace(&test);
13341 } else {
13342 for (auto const& match : m_matches)
13343 m_tests.insert(match.tests.begin(), match.tests.end());
13344 }
13345 }
13346
13347 Totals execute() {
13348 auto const& invalidArgs = m_config->testSpec().getInvalidArgs();
13349 Totals totals;
13350 m_context.testGroupStarting(m_config->name(), 1, 1);
13351 for (auto const& testCase : m_tests) {
13352 if (!m_context.aborting())
13353 totals += m_context.runTest(*testCase);
13354 else
13355 m_context.reporter().skipTest(*testCase);
13356 }
13357
13358 for (auto const& match : m_matches) {
13359 if (match.tests.empty()) {
13360 m_context.reporter().noMatchingTestCases(match.name);
13361 totals.error = -1;
13362 }
13363 }
13364
13365 if (!invalidArgs.empty()) {
13366 for (auto const& invalidArg: invalidArgs)
13367 m_context.reporter().reportInvalidArguments(invalidArg);
13368 }
13369
13370 m_context.testGroupEnded(m_config->name(), totals, 1, 1);
13371 return totals;
13372 }
13373
13374 private:
13375 using Tests = std::set<TestCase const*>;
13376
13377 std::shared_ptr<Config> m_config;
13378 RunContext m_context;
13379 Tests m_tests;
13380 TestSpec::Matches m_matches;
13381 };
13382
13383 void applyFilenamesAsTags(Catch::IConfig const& config) {
13384 auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
13385 for (auto& testCase : tests) {
13386 auto tags = testCase.tags;
13387
13388 std::string filename = testCase.lineInfo.file;
13389 auto lastSlash = filename.find_last_of("\\/");
13390 if (lastSlash != std::string::npos) {
13391 filename.erase(0, lastSlash);
13392 filename[0] = '#';
13393 }
13394 else
13395 {
13396 filename.insert(0, "#");
13397 }
13398
13399 auto lastDot = filename.find_last_of('.');
13400 if (lastDot != std::string::npos) {
13401 filename.erase(lastDot);
13402 }
13403
13404 tags.push_back(std::move(filename));
13405 setTags(testCase, tags);
13406 }
13407 }
13408
13409 } // anon namespace
13410
13411 Session::Session() {
13412 static bool alreadyInstantiated = false;
13413 if( alreadyInstantiated ) {
13414 CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
13415 CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
13416 }
13417
13418 // There cannot be exceptions at startup in no-exception mode.
13419#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13420 const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
13421 if ( !exceptions.empty() ) {
13422 config();
13423 getCurrentMutableContext().setConfig(m_config);
13424
13425 m_startupExceptions = true;
13426 Colour colourGuard( Colour::Red );
13427 Catch::cerr() << "Errors occurred during startup!" << '\n';
13428 // iterate over all exceptions and notify user
13429 for ( const auto& ex_ptr : exceptions ) {
13430 try {
13431 std::rethrow_exception(ex_ptr);
13432 } catch ( std::exception const& ex ) {
13433 Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
13434 }
13435 }
13436 }
13437#endif
13438
13439 alreadyInstantiated = true;
13440 m_cli = makeCommandLineParser( m_configData );
13441 }
13442 Session::~Session() {
13443 Catch::cleanUp();
13444 }
13445
13446 void Session::showHelp() const {
13447 Catch::cout()
13448 << "\nCatch v" << libraryVersion() << "\n"
13449 << m_cli << std::endl
13450 << "For more detailed usage please see the project docs\n" << std::endl;
13451 }
13452 void Session::libIdentify() {
13453 Catch::cout()
13454 << std::left << std::setw(16) << "description: " << "A Catch2 test executable\n"
13455 << std::left << std::setw(16) << "category: " << "testframework\n"
13456 << std::left << std::setw(16) << "framework: " << "Catch Test\n"
13457 << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
13458 }
13459
13460 int Session::applyCommandLine( int argc, char const * const * argv ) {
13461 if( m_startupExceptions )
13462 return 1;
13463
13464 auto result = m_cli.parse( clara::Args( argc, argv ) );
13465 if( !result ) {
13466 config();
13467 getCurrentMutableContext().setConfig(m_config);
13468 Catch::cerr()
13469 << Colour( Colour::Red )
13470 << "\nError(s) in input:\n"
13471 << Column( result.errorMessage() ).indent( 2 )
13472 << "\n\n";
13473 Catch::cerr() << "Run with -? for usage\n" << std::endl;
13474 return MaxExitCode;
13475 }
13476
13477 if( m_configData.showHelp )
13478 showHelp();
13479 if( m_configData.libIdentify )
13480 libIdentify();
13481 m_config.reset();
13482 return 0;
13483 }
13484
13485#if defined(CATCH_CONFIG_WCHAR) && defined(_WIN32) && defined(UNICODE)
13486 int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
13487
13488 char **utf8Argv = new char *[ argc ];
13489
13490 for ( int i = 0; i < argc; ++i ) {
13491 int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, nullptr, 0, nullptr, nullptr );
13492
13493 utf8Argv[ i ] = new char[ bufSize ];
13494
13495 WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, nullptr, nullptr );
13496 }
13497
13498 int returnCode = applyCommandLine( argc, utf8Argv );
13499
13500 for ( int i = 0; i < argc; ++i )
13501 delete [] utf8Argv[ i ];
13502
13503 delete [] utf8Argv;
13504
13505 return returnCode;
13506 }
13507#endif
13508
13509 void Session::useConfigData( ConfigData const& configData ) {
13510 m_configData = configData;
13511 m_config.reset();
13512 }
13513
13514 int Session::run() {
13515 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
13516 Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
13517 static_cast<void>(std::getchar());
13518 }
13519 int exitCode = runInternal();
13520 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
13521 Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
13522 static_cast<void>(std::getchar());
13523 }
13524 return exitCode;
13525 }
13526
13527 clara::Parser const& Session::cli() const {
13528 return m_cli;
13529 }
13530 void Session::cli( clara::Parser const& newParser ) {
13531 m_cli = newParser;
13532 }
13533 ConfigData& Session::configData() {
13534 return m_configData;
13535 }
13536 Config& Session::config() {
13537 if( !m_config )
13538 m_config = std::make_shared<Config>( m_configData );
13539 return *m_config;
13540 }
13541
13542 int Session::runInternal() {
13543 if( m_startupExceptions )
13544 return 1;
13545
13546 if (m_configData.showHelp || m_configData.libIdentify) {
13547 return 0;
13548 }
13549
13550 CATCH_TRY {
13551 config(); // Force config to be constructed
13552
13553 seedRng( *m_config );
13554
13555 if( m_configData.filenamesAsTags )
13556 applyFilenamesAsTags( *m_config );
13557
13558 // Handle list request
13559 if( Option<std::size_t> listed = list( m_config ) )
13560 return (std::min) (MaxExitCode, static_cast<int>(*listed));
13561
13562 TestGroup tests { m_config };
13563 auto const totals = tests.execute();
13564
13565 if( m_config->warnAboutNoTests() && totals.error == -1 )
13566 return 2;
13567
13568 // Note that on unices only the lower 8 bits are usually used, clamping
13569 // the return value to 255 prevents false negative when some multiple
13570 // of 256 tests has failed
13571 return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
13572 }
13573#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13574 catch( std::exception& ex ) {
13575 Catch::cerr() << ex.what() << std::endl;
13576 return MaxExitCode;
13577 }
13578#endif
13579 }
13580
13581} // end namespace Catch
13582// end catch_session.cpp
13583// start catch_singletons.cpp
13584
13585#include <vector>
13586
13587namespace Catch {
13588
13589 namespace {
13590 static auto getSingletons() -> std::vector<ISingleton*>*& {
13591 static std::vector<ISingleton*>* g_singletons = nullptr;
13592 if( !g_singletons )
13593 g_singletons = new std::vector<ISingleton*>();
13594 return g_singletons;
13595 }
13596 }
13597
13598 ISingleton::~ISingleton() {}
13599
13600 void addSingleton(ISingleton* singleton ) {
13601 getSingletons()->push_back( singleton );
13602 }
13603 void cleanupSingletons() {
13604 auto& singletons = getSingletons();
13605 for( auto singleton : *singletons )
13606 delete singleton;
13607 delete singletons;
13608 singletons = nullptr;
13609 }
13610
13611} // namespace Catch
13612// end catch_singletons.cpp
13613// start catch_startup_exception_registry.cpp
13614
13615#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
13616namespace Catch {
13617void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
13618 CATCH_TRY {
13619 m_exceptions.push_back(exception);
13620 } CATCH_CATCH_ALL {
13621 // If we run out of memory during start-up there's really not a lot more we can do about it
13622 std::terminate();
13623 }
13624 }
13625
13626 std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
13627 return m_exceptions;
13628 }
13629
13630} // end namespace Catch
13631#endif
13632// end catch_startup_exception_registry.cpp
13633// start catch_stream.cpp
13634
13635#include <cstdio>
13636#include <iostream>
13637#include <fstream>
13638#include <sstream>
13639#include <vector>
13640#include <memory>
13641
13642namespace Catch {
13643
13644 Catch::IStream::~IStream() = default;
13645
13646 namespace Detail { namespace {
13647 template<typename WriterF, std::size_t bufferSize=256>
13648 class StreamBufImpl : public std::streambuf {
13649 char data[bufferSize];
13650 WriterF m_writer;
13651
13652 public:
13653 StreamBufImpl() {
13654 setp( data, data + sizeof(data) );
13655 }
13656
13657 ~StreamBufImpl() noexcept {
13658 StreamBufImpl::sync();
13659 }
13660
13661 private:
13662 int overflow( int c ) override {
13663 sync();
13664
13665 if( c != EOF ) {
13666 if( pbase() == epptr() )
13667 m_writer( std::string( 1, static_cast<char>( c ) ) );
13668 else
13669 sputc( static_cast<char>( c ) );
13670 }
13671 return 0;
13672 }
13673
13674 int sync() override {
13675 if( pbase() != pptr() ) {
13676 m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
13677 setp( pbase(), epptr() );
13678 }
13679 return 0;
13680 }
13681 };
13682
13684
13685 struct OutputDebugWriter {
13686
13687 void operator()( std::string const&str ) {
13688 writeToDebugConsole( str );
13689 }
13690 };
13691
13693
13694 class FileStream : public IStream {
13695 mutable std::ofstream m_ofs;
13696 public:
13697 FileStream( StringRef filename ) {
13698 m_ofs.open( filename.c_str() );
13699 CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
13700 }
13701 ~FileStream() override = default;
13702 public: // IStream
13703 std::ostream& stream() const override {
13704 return m_ofs;
13705 }
13706 };
13707
13709
13710 class CoutStream : public IStream {
13711 mutable std::ostream m_os;
13712 public:
13713 // Store the streambuf from cout up-front because
13714 // cout may get redirected when running tests
13715 CoutStream() : m_os( Catch::cout().rdbuf() ) {}
13716 ~CoutStream() override = default;
13717
13718 public: // IStream
13719 std::ostream& stream() const override { return m_os; }
13720 };
13721
13723
13724 class DebugOutStream : public IStream {
13725 std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
13726 mutable std::ostream m_os;
13727 public:
13728 DebugOutStream()
13729 : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
13730 m_os( m_streamBuf.get() )
13731 {}
13732
13733 ~DebugOutStream() override = default;
13734
13735 public: // IStream
13736 std::ostream& stream() const override { return m_os; }
13737 };
13738
13739 }} // namespace anon::detail
13740
13742
13743 auto makeStream( StringRef const &filename ) -> IStream const* {
13744 if( filename.empty() )
13745 return new Detail::CoutStream();
13746 else if( filename[0] == '%' ) {
13747 if( filename == "%debug" )
13748 return new Detail::DebugOutStream();
13749 else
13750 CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
13751 }
13752 else
13753 return new Detail::FileStream( filename );
13754 }
13755
13756 // This class encapsulates the idea of a pool of ostringstreams that can be reused.
13757 struct StringStreams {
13758 std::vector<std::unique_ptr<std::ostringstream>> m_streams;
13759 std::vector<std::size_t> m_unused;
13760 std::ostringstream m_referenceStream; // Used for copy state/ flags from
13761
13762 auto add() -> std::size_t {
13763 if( m_unused.empty() ) {
13764 m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
13765 return m_streams.size()-1;
13766 }
13767 else {
13768 auto index = m_unused.back();
13769 m_unused.pop_back();
13770 return index;
13771 }
13772 }
13773
13774 void release( std::size_t index ) {
13775 m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
13776 m_unused.push_back(index);
13777 }
13778 };
13779
13780 ReusableStringStream::ReusableStringStream()
13781 : m_index( Singleton<StringStreams>::getMutable().add() ),
13782 m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
13783 {}
13784
13785 ReusableStringStream::~ReusableStringStream() {
13786 static_cast<std::ostringstream*>( m_oss )->str("");
13787 m_oss->clear();
13788 Singleton<StringStreams>::getMutable().release( m_index );
13789 }
13790
13791 auto ReusableStringStream::str() const -> std::string {
13792 return static_cast<std::ostringstream*>( m_oss )->str();
13793 }
13794
13796
13797#ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
13798 std::ostream& cout() { return std::cout; }
13799 std::ostream& cerr() { return std::cerr; }
13800 std::ostream& clog() { return std::clog; }
13801#endif
13802}
13803// end catch_stream.cpp
13804// start catch_string_manip.cpp
13805
13806#include <algorithm>
13807#include <ostream>
13808#include <cstring>
13809#include <cctype>
13810#include <vector>
13811
13812namespace Catch {
13813
13814 namespace {
13815 char toLowerCh(char c) {
13816 return static_cast<char>( std::tolower( static_cast<unsigned char>(c) ) );
13817 }
13818 }
13819
13820 bool startsWith( std::string const& s, std::string const& prefix ) {
13821 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
13822 }
13823 bool startsWith( std::string const& s, char prefix ) {
13824 return !s.empty() && s[0] == prefix;
13825 }
13826 bool endsWith( std::string const& s, std::string const& suffix ) {
13827 return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
13828 }
13829 bool endsWith( std::string const& s, char suffix ) {
13830 return !s.empty() && s[s.size()-1] == suffix;
13831 }
13832 bool contains( std::string const& s, std::string const& infix ) {
13833 return s.find( infix ) != std::string::npos;
13834 }
13835 void toLowerInPlace( std::string& s ) {
13836 std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
13837 }
13838 std::string toLower( std::string const& s ) {
13839 std::string lc = s;
13840 toLowerInPlace( lc );
13841 return lc;
13842 }
13843 std::string trim( std::string const& str ) {
13844 static char const* whitespaceChars = "\n\r\t ";
13845 std::string::size_type start = str.find_first_not_of( whitespaceChars );
13846 std::string::size_type end = str.find_last_not_of( whitespaceChars );
13847
13848 return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
13849 }
13850
13851 StringRef trim(StringRef ref) {
13852 const auto is_ws = [](char c) {
13853 return c == ' ' || c == '\t' || c == '\n' || c == '\r';
13854 };
13855 size_t real_begin = 0;
13856 while (real_begin < ref.size() && is_ws(ref[real_begin])) { ++real_begin; }
13857 size_t real_end = ref.size();
13858 while (real_end > real_begin && is_ws(ref[real_end - 1])) { --real_end; }
13859
13860 return ref.substr(real_begin, real_end - real_begin);
13861 }
13862
13863 bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
13864 bool replaced = false;
13865 std::size_t i = str.find( replaceThis );
13866 while( i != std::string::npos ) {
13867 replaced = true;
13868 str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
13869 if( i < str.size()-withThis.size() )
13870 i = str.find( replaceThis, i+withThis.size() );
13871 else
13872 i = std::string::npos;
13873 }
13874 return replaced;
13875 }
13876
13877 std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
13878 std::vector<StringRef> subStrings;
13879 std::size_t start = 0;
13880 for(std::size_t pos = 0; pos < str.size(); ++pos ) {
13881 if( str[pos] == delimiter ) {
13882 if( pos - start > 1 )
13883 subStrings.push_back( str.substr( start, pos-start ) );
13884 start = pos+1;
13885 }
13886 }
13887 if( start < str.size() )
13888 subStrings.push_back( str.substr( start, str.size()-start ) );
13889 return subStrings;
13890 }
13891
13892 pluralise::pluralise( std::size_t count, std::string const& label )
13893 : m_count( count ),
13894 m_label( label )
13895 {}
13896
13897 std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
13898 os << pluraliser.m_count << ' ' << pluraliser.m_label;
13899 if( pluraliser.m_count != 1 )
13900 os << 's';
13901 return os;
13902 }
13903
13904}
13905// end catch_string_manip.cpp
13906// start catch_stringref.cpp
13907
13908#include <algorithm>
13909#include <ostream>
13910#include <cstring>
13911#include <cstdint>
13912
13913namespace Catch {
13914 StringRef::StringRef( char const* rawChars ) noexcept
13915 : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
13916 {}
13917
13918 auto StringRef::c_str() const -> char const* {
13919 CATCH_ENFORCE(isNullTerminated(), "Called StringRef::c_str() on a non-null-terminated instance");
13920 return m_start;
13921 }
13922 auto StringRef::data() const noexcept -> char const* {
13923 return m_start;
13924 }
13925
13926 auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
13927 if (start < m_size) {
13928 return StringRef(m_start + start, (std::min)(m_size - start, size));
13929 } else {
13930 return StringRef();
13931 }
13932 }
13933 auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
13934 return m_size == other.m_size
13935 && (std::memcmp( m_start, other.m_start, m_size ) == 0);
13936 }
13937
13938 auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
13939 return os.write(str.data(), str.size());
13940 }
13941
13942 auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
13943 lhs.append(rhs.data(), rhs.size());
13944 return lhs;
13945 }
13946
13947} // namespace Catch
13948// end catch_stringref.cpp
13949// start catch_tag_alias.cpp
13950
13951namespace Catch {
13952 TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
13953}
13954// end catch_tag_alias.cpp
13955// start catch_tag_alias_autoregistrar.cpp
13956
13957namespace Catch {
13958
13959 RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
13960 CATCH_TRY {
13961 getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
13962 } CATCH_CATCH_ALL {
13963 // Do not throw when constructing global objects, instead register the exception to be processed later
13964 getMutableRegistryHub().registerStartupException();
13965 }
13966 }
13967
13968}
13969// end catch_tag_alias_autoregistrar.cpp
13970// start catch_tag_alias_registry.cpp
13971
13972#include <sstream>
13973
13974namespace Catch {
13975
13976 TagAliasRegistry::~TagAliasRegistry() {}
13977
13978 TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
13979 auto it = m_registry.find( alias );
13980 if( it != m_registry.end() )
13981 return &(it->second);
13982 else
13983 return nullptr;
13984 }
13985
13986 std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
13987 std::string expandedTestSpec = unexpandedTestSpec;
13988 for( auto const& registryKvp : m_registry ) {
13989 std::size_t pos = expandedTestSpec.find( registryKvp.first );
13990 if( pos != std::string::npos ) {
13991 expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
13992 registryKvp.second.tag +
13993 expandedTestSpec.substr( pos + registryKvp.first.size() );
13994 }
13995 }
13996 return expandedTestSpec;
13997 }
13998
13999 void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
14000 CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
14001 "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
14002
14003 CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
14004 "error: tag alias, '" << alias << "' already registered.\n"
14005 << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
14006 << "\tRedefined at: " << lineInfo );
14007 }
14008
14009 ITagAliasRegistry::~ITagAliasRegistry() {}
14010
14011 ITagAliasRegistry const& ITagAliasRegistry::get() {
14012 return getRegistryHub().getTagAliasRegistry();
14013 }
14014
14015} // end namespace Catch
14016// end catch_tag_alias_registry.cpp
14017// start catch_test_case_info.cpp
14018
14019#include <cctype>
14020#include <exception>
14021#include <algorithm>
14022#include <sstream>
14023
14024namespace Catch {
14025
14026 namespace {
14027 TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
14028 if( startsWith( tag, '.' ) ||
14029 tag == "!hide" )
14030 return TestCaseInfo::IsHidden;
14031 else if( tag == "!throws" )
14032 return TestCaseInfo::Throws;
14033 else if( tag == "!shouldfail" )
14034 return TestCaseInfo::ShouldFail;
14035 else if( tag == "!mayfail" )
14036 return TestCaseInfo::MayFail;
14037 else if( tag == "!nonportable" )
14038 return TestCaseInfo::NonPortable;
14039 else if( tag == "!benchmark" )
14040 return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
14041 else
14042 return TestCaseInfo::None;
14043 }
14044 bool isReservedTag( std::string const& tag ) {
14045 return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
14046 }
14047 void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
14048 CATCH_ENFORCE( !isReservedTag(tag),
14049 "Tag name: [" << tag << "] is not allowed.\n"
14050 << "Tag names starting with non alphanumeric characters are reserved\n"
14051 << _lineInfo );
14052 }
14053 }
14054
14055 TestCase makeTestCase( ITestInvoker* _testCase,
14056 std::string const& _className,
14057 NameAndTags const& nameAndTags,
14058 SourceLineInfo const& _lineInfo )
14059 {
14060 bool isHidden = false;
14061
14062 // Parse out tags
14063 std::vector<std::string> tags;
14064 std::string desc, tag;
14065 bool inTag = false;
14066 for (char c : nameAndTags.tags) {
14067 if( !inTag ) {
14068 if( c == '[' )
14069 inTag = true;
14070 else
14071 desc += c;
14072 }
14073 else {
14074 if( c == ']' ) {
14075 TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
14076 if( ( prop & TestCaseInfo::IsHidden ) != 0 )
14077 isHidden = true;
14078 else if( prop == TestCaseInfo::None )
14079 enforceNotReservedTag( tag, _lineInfo );
14080
14081 // Merged hide tags like `[.approvals]` should be added as
14082 // `[.][approvals]`. The `[.]` is added at later point, so
14083 // we only strip the prefix
14084 if (startsWith(tag, '.') && tag.size() > 1) {
14085 tag.erase(0, 1);
14086 }
14087 tags.push_back( tag );
14088 tag.clear();
14089 inTag = false;
14090 }
14091 else
14092 tag += c;
14093 }
14094 }
14095 if( isHidden ) {
14096 // Add all "hidden" tags to make them behave identically
14097 tags.insert( tags.end(), { ".", "!hide" } );
14098 }
14099
14100 TestCaseInfo info( static_cast<std::string>(nameAndTags.name), _className, desc, tags, _lineInfo );
14101 return TestCase( _testCase, std::move(info) );
14102 }
14103
14104 void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
14105 std::sort(begin(tags), end(tags));
14106 tags.erase(std::unique(begin(tags), end(tags)), end(tags));
14107 testCaseInfo.lcaseTags.clear();
14108
14109 for( auto const& tag : tags ) {
14110 std::string lcaseTag = toLower( tag );
14111 testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
14112 testCaseInfo.lcaseTags.push_back( lcaseTag );
14113 }
14114 testCaseInfo.tags = std::move(tags);
14115 }
14116
14117 TestCaseInfo::TestCaseInfo( std::string const& _name,
14118 std::string const& _className,
14119 std::string const& _description,
14120 std::vector<std::string> const& _tags,
14121 SourceLineInfo const& _lineInfo )
14122 : name( _name ),
14123 className( _className ),
14124 description( _description ),
14125 lineInfo( _lineInfo ),
14126 properties( None )
14127 {
14128 setTags( *this, _tags );
14129 }
14130
14131 bool TestCaseInfo::isHidden() const {
14132 return ( properties & IsHidden ) != 0;
14133 }
14134 bool TestCaseInfo::throws() const {
14135 return ( properties & Throws ) != 0;
14136 }
14137 bool TestCaseInfo::okToFail() const {
14138 return ( properties & (ShouldFail | MayFail ) ) != 0;
14139 }
14140 bool TestCaseInfo::expectedToFail() const {
14141 return ( properties & (ShouldFail ) ) != 0;
14142 }
14143
14144 std::string TestCaseInfo::tagsAsString() const {
14145 std::string ret;
14146 // '[' and ']' per tag
14147 std::size_t full_size = 2 * tags.size();
14148 for (const auto& tag : tags) {
14149 full_size += tag.size();
14150 }
14151 ret.reserve(full_size);
14152 for (const auto& tag : tags) {
14153 ret.push_back('[');
14154 ret.append(tag);
14155 ret.push_back(']');
14156 }
14157
14158 return ret;
14159 }
14160
14161 TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
14162
14163 TestCase TestCase::withName( std::string const& _newName ) const {
14164 TestCase other( *this );
14165 other.name = _newName;
14166 return other;
14167 }
14168
14169 void TestCase::invoke() const {
14170 test->invoke();
14171 }
14172
14173 bool TestCase::operator == ( TestCase const& other ) const {
14174 return test.get() == other.test.get() &&
14175 name == other.name &&
14176 className == other.className;
14177 }
14178
14179 bool TestCase::operator < ( TestCase const& other ) const {
14180 return name < other.name;
14181 }
14182
14183 TestCaseInfo const& TestCase::getTestCaseInfo() const
14184 {
14185 return *this;
14186 }
14187
14188} // end namespace Catch
14189// end catch_test_case_info.cpp
14190// start catch_test_case_registry_impl.cpp
14191
14192#include <algorithm>
14193#include <sstream>
14194
14195namespace Catch {
14196
14197 namespace {
14198 struct TestHasher {
14199 using hash_t = uint64_t;
14200
14201 explicit TestHasher( hash_t hashSuffix ):
14202 m_hashSuffix{ hashSuffix } {}
14203
14204 uint32_t operator()( TestCase const& t ) const {
14205 // FNV-1a hash with multiplication fold.
14206 const hash_t prime = 1099511628211u;
14207 hash_t hash = 14695981039346656037u;
14208 for ( const char c : t.name ) {
14209 hash ^= c;
14210 hash *= prime;
14211 }
14212 hash ^= m_hashSuffix;
14213 hash *= prime;
14214 const uint32_t low{ static_cast<uint32_t>( hash ) };
14215 const uint32_t high{ static_cast<uint32_t>( hash >> 32 ) };
14216 return low * high;
14217 }
14218
14219 private:
14220 hash_t m_hashSuffix;
14221 };
14222 } // end unnamed namespace
14223
14224 std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
14225 switch( config.runOrder() ) {
14226 case RunTests::InDeclarationOrder:
14227 // already in declaration order
14228 break;
14229
14230 case RunTests::InLexicographicalOrder: {
14231 std::vector<TestCase> sorted = unsortedTestCases;
14232 std::sort( sorted.begin(), sorted.end() );
14233 return sorted;
14234 }
14235
14236 case RunTests::InRandomOrder: {
14237 seedRng( config );
14238 TestHasher h{ config.rngSeed() };
14239
14240 using hashedTest = std::pair<TestHasher::hash_t, TestCase const*>;
14241 std::vector<hashedTest> indexed_tests;
14242 indexed_tests.reserve( unsortedTestCases.size() );
14243
14244 for (auto const& testCase : unsortedTestCases) {
14245 indexed_tests.emplace_back(h(testCase), &testCase);
14246 }
14247
14248 std::sort(indexed_tests.begin(), indexed_tests.end(),
14249 [](hashedTest const& lhs, hashedTest const& rhs) {
14250 if (lhs.first == rhs.first) {
14251 return lhs.second->name < rhs.second->name;
14252 }
14253 return lhs.first < rhs.first;
14254 });
14255
14256 std::vector<TestCase> sorted;
14257 sorted.reserve( indexed_tests.size() );
14258
14259 for (auto const& hashed : indexed_tests) {
14260 sorted.emplace_back(*hashed.second);
14261 }
14262
14263 return sorted;
14264 }
14265 }
14266 return unsortedTestCases;
14267 }
14268
14269 bool isThrowSafe( TestCase const& testCase, IConfig const& config ) {
14270 return !testCase.throws() || config.allowThrows();
14271 }
14272
14273 bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
14274 return testSpec.matches( testCase ) && isThrowSafe( testCase, config );
14275 }
14276
14277 void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
14278 std::set<TestCase> seenFunctions;
14279 for( auto const& function : functions ) {
14280 auto prev = seenFunctions.insert( function );
14281 CATCH_ENFORCE( prev.second,
14282 "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
14283 << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
14284 << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
14285 }
14286 }
14287
14288 std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
14289 std::vector<TestCase> filtered;
14290 filtered.reserve( testCases.size() );
14291 for (auto const& testCase : testCases) {
14292 if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
14293 (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
14294 filtered.push_back(testCase);
14295 }
14296 }
14297 return filtered;
14298 }
14299 std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
14300 return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
14301 }
14302
14303 void TestRegistry::registerTest( TestCase const& testCase ) {
14304 std::string name = testCase.getTestCaseInfo().name;
14305 if( name.empty() ) {
14306 ReusableStringStream rss;
14307 rss << "Anonymous test case " << ++m_unnamedCount;
14308 return registerTest( testCase.withName( rss.str() ) );
14309 }
14310 m_functions.push_back( testCase );
14311 }
14312
14313 std::vector<TestCase> const& TestRegistry::getAllTests() const {
14314 return m_functions;
14315 }
14316 std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
14317 if( m_sortedFunctions.empty() )
14318 enforceNoDuplicateTestCases( m_functions );
14319
14320 if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
14321 m_sortedFunctions = sortTests( config, m_functions );
14322 m_currentSortOrder = config.runOrder();
14323 }
14324 return m_sortedFunctions;
14325 }
14326
14328 TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
14329
14330 void TestInvokerAsFunction::invoke() const {
14331 m_testAsFunction();
14332 }
14333
14334 std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
14335 std::string className(classOrQualifiedMethodName);
14336 if( startsWith( className, '&' ) )
14337 {
14338 std::size_t lastColons = className.rfind( "::" );
14339 std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
14340 if( penultimateColons == std::string::npos )
14341 penultimateColons = 1;
14342 className = className.substr( penultimateColons, lastColons-penultimateColons );
14343 }
14344 return className;
14345 }
14346
14347} // end namespace Catch
14348// end catch_test_case_registry_impl.cpp
14349// start catch_test_case_tracker.cpp
14350
14351#include <algorithm>
14352#include <cassert>
14353#include <stdexcept>
14354#include <memory>
14355#include <sstream>
14356
14357#if defined(__clang__)
14358# pragma clang diagnostic push
14359# pragma clang diagnostic ignored "-Wexit-time-destructors"
14360#endif
14361
14362namespace Catch {
14363namespace TestCaseTracking {
14364
14365 NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
14366 : name( _name ),
14367 location( _location )
14368 {}
14369
14370 ITracker::~ITracker() = default;
14371
14372 ITracker& TrackerContext::startRun() {
14373 m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
14374 m_currentTracker = nullptr;
14375 m_runState = Executing;
14376 return *m_rootTracker;
14377 }
14378
14379 void TrackerContext::endRun() {
14380 m_rootTracker.reset();
14381 m_currentTracker = nullptr;
14382 m_runState = NotStarted;
14383 }
14384
14385 void TrackerContext::startCycle() {
14386 m_currentTracker = m_rootTracker.get();
14387 m_runState = Executing;
14388 }
14389 void TrackerContext::completeCycle() {
14390 m_runState = CompletedCycle;
14391 }
14392
14393 bool TrackerContext::completedCycle() const {
14394 return m_runState == CompletedCycle;
14395 }
14396 ITracker& TrackerContext::currentTracker() {
14397 return *m_currentTracker;
14398 }
14399 void TrackerContext::setCurrentTracker( ITracker* tracker ) {
14400 m_currentTracker = tracker;
14401 }
14402
14403 TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent ):
14404 ITracker(nameAndLocation),
14405 m_ctx( ctx ),
14406 m_parent( parent )
14407 {}
14408
14409 bool TrackerBase::isComplete() const {
14410 return m_runState == CompletedSuccessfully || m_runState == Failed;
14411 }
14412 bool TrackerBase::isSuccessfullyCompleted() const {
14413 return m_runState == CompletedSuccessfully;
14414 }
14415 bool TrackerBase::isOpen() const {
14416 return m_runState != NotStarted && !isComplete();
14417 }
14418 bool TrackerBase::hasChildren() const {
14419 return !m_children.empty();
14420 }
14421
14422 void TrackerBase::addChild( ITrackerPtr const& child ) {
14423 m_children.push_back( child );
14424 }
14425
14426 ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
14427 auto it = std::find_if( m_children.begin(), m_children.end(),
14428 [&nameAndLocation]( ITrackerPtr const& tracker ){
14429 return
14430 tracker->nameAndLocation().location == nameAndLocation.location &&
14431 tracker->nameAndLocation().name == nameAndLocation.name;
14432 } );
14433 return( it != m_children.end() )
14434 ? *it
14435 : nullptr;
14436 }
14437 ITracker& TrackerBase::parent() {
14438 assert( m_parent ); // Should always be non-null except for root
14439 return *m_parent;
14440 }
14441
14442 void TrackerBase::openChild() {
14443 if( m_runState != ExecutingChildren ) {
14444 m_runState = ExecutingChildren;
14445 if( m_parent )
14446 m_parent->openChild();
14447 }
14448 }
14449
14450 bool TrackerBase::isSectionTracker() const { return false; }
14451 bool TrackerBase::isGeneratorTracker() const { return false; }
14452
14453 void TrackerBase::open() {
14454 m_runState = Executing;
14455 moveToThis();
14456 if( m_parent )
14457 m_parent->openChild();
14458 }
14459
14460 void TrackerBase::close() {
14461
14462 // Close any still open children (e.g. generators)
14463 while( &m_ctx.currentTracker() != this )
14464 m_ctx.currentTracker().close();
14465
14466 switch( m_runState ) {
14467 case NeedsAnotherRun:
14468 break;
14469
14470 case Executing:
14471 m_runState = CompletedSuccessfully;
14472 break;
14473 case ExecutingChildren:
14474 if( std::all_of(m_children.begin(), m_children.end(), [](ITrackerPtr const& t){ return t->isComplete(); }) )
14475 m_runState = CompletedSuccessfully;
14476 break;
14477
14478 case NotStarted:
14479 case CompletedSuccessfully:
14480 case Failed:
14481 CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
14482
14483 default:
14484 CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
14485 }
14486 moveToParent();
14487 m_ctx.completeCycle();
14488 }
14489 void TrackerBase::fail() {
14490 m_runState = Failed;
14491 if( m_parent )
14492 m_parent->markAsNeedingAnotherRun();
14493 moveToParent();
14494 m_ctx.completeCycle();
14495 }
14496 void TrackerBase::markAsNeedingAnotherRun() {
14497 m_runState = NeedsAnotherRun;
14498 }
14499
14500 void TrackerBase::moveToParent() {
14501 assert( m_parent );
14502 m_ctx.setCurrentTracker( m_parent );
14503 }
14504 void TrackerBase::moveToThis() {
14505 m_ctx.setCurrentTracker( this );
14506 }
14507
14508 SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
14509 : TrackerBase( nameAndLocation, ctx, parent ),
14510 m_trimmed_name(trim(nameAndLocation.name))
14511 {
14512 if( parent ) {
14513 while( !parent->isSectionTracker() )
14514 parent = &parent->parent();
14515
14516 SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
14517 addNextFilters( parentSection.m_filters );
14518 }
14519 }
14520
14521 bool SectionTracker::isComplete() const {
14522 bool complete = true;
14523
14524 if (m_filters.empty()
14525 || m_filters[0] == ""
14526 || std::find(m_filters.begin(), m_filters.end(), m_trimmed_name) != m_filters.end()) {
14527 complete = TrackerBase::isComplete();
14528 }
14529 return complete;
14530 }
14531
14532 bool SectionTracker::isSectionTracker() const { return true; }
14533
14534 SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
14535 std::shared_ptr<SectionTracker> section;
14536
14537 ITracker& currentTracker = ctx.currentTracker();
14538 if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
14539 assert( childTracker );
14540 assert( childTracker->isSectionTracker() );
14541 section = std::static_pointer_cast<SectionTracker>( childTracker );
14542 }
14543 else {
14544 section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
14545 currentTracker.addChild( section );
14546 }
14547 if( !ctx.completedCycle() )
14548 section->tryOpen();
14549 return *section;
14550 }
14551
14552 void SectionTracker::tryOpen() {
14553 if( !isComplete() )
14554 open();
14555 }
14556
14557 void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
14558 if( !filters.empty() ) {
14559 m_filters.reserve( m_filters.size() + filters.size() + 2 );
14560 m_filters.emplace_back(""); // Root - should never be consulted
14561 m_filters.emplace_back(""); // Test Case - not a section filter
14562 m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
14563 }
14564 }
14565 void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
14566 if( filters.size() > 1 )
14567 m_filters.insert( m_filters.end(), filters.begin()+1, filters.end() );
14568 }
14569
14570 std::vector<std::string> const& SectionTracker::getFilters() const {
14571 return m_filters;
14572 }
14573
14574 std::string const& SectionTracker::trimmedName() const {
14575 return m_trimmed_name;
14576 }
14577
14578} // namespace TestCaseTracking
14579
14580using TestCaseTracking::ITracker;
14581using TestCaseTracking::TrackerContext;
14582using TestCaseTracking::SectionTracker;
14583
14584} // namespace Catch
14585
14586#if defined(__clang__)
14587# pragma clang diagnostic pop
14588#endif
14589// end catch_test_case_tracker.cpp
14590// start catch_test_registry.cpp
14591
14592namespace Catch {
14593
14594 auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
14595 return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
14596 }
14597
14598 NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
14599
14600 AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
14601 CATCH_TRY {
14602 getMutableRegistryHub()
14603 .registerTest(
14604 makeTestCase(
14605 invoker,
14606 extractClassName( classOrMethod ),
14607 nameAndTags,
14608 lineInfo));
14609 } CATCH_CATCH_ALL {
14610 // Do not throw when constructing global objects, instead register the exception to be processed later
14611 getMutableRegistryHub().registerStartupException();
14612 }
14613 }
14614
14615 AutoReg::~AutoReg() = default;
14616}
14617// end catch_test_registry.cpp
14618// start catch_test_spec.cpp
14619
14620#include <algorithm>
14621#include <string>
14622#include <vector>
14623#include <memory>
14624
14625namespace Catch {
14626
14627 TestSpec::Pattern::Pattern( std::string const& name )
14628 : m_name( name )
14629 {}
14630
14631 TestSpec::Pattern::~Pattern() = default;
14632
14633 std::string const& TestSpec::Pattern::name() const {
14634 return m_name;
14635 }
14636
14637 TestSpec::NamePattern::NamePattern( std::string const& name, std::string const& filterString )
14638 : Pattern( filterString )
14639 , m_wildcardPattern( toLower( name ), CaseSensitive::No )
14640 {}
14641
14642 bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
14643 return m_wildcardPattern.matches( testCase.name );
14644 }
14645
14646 TestSpec::TagPattern::TagPattern( std::string const& tag, std::string const& filterString )
14647 : Pattern( filterString )
14648 , m_tag( toLower( tag ) )
14649 {}
14650
14651 bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
14652 return std::find(begin(testCase.lcaseTags),
14653 end(testCase.lcaseTags),
14654 m_tag) != end(testCase.lcaseTags);
14655 }
14656
14657 TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern )
14658 : Pattern( underlyingPattern->name() )
14659 , m_underlyingPattern( underlyingPattern )
14660 {}
14661
14662 bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const {
14663 return !m_underlyingPattern->matches( testCase );
14664 }
14665
14666 bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
14667 return std::all_of( m_patterns.begin(), m_patterns.end(), [&]( PatternPtr const& p ){ return p->matches( testCase ); } );
14668 }
14669
14670 std::string TestSpec::Filter::name() const {
14671 std::string name;
14672 for( auto const& p : m_patterns )
14673 name += p->name();
14674 return name;
14675 }
14676
14677 bool TestSpec::hasFilters() const {
14678 return !m_filters.empty();
14679 }
14680
14681 bool TestSpec::matches( TestCaseInfo const& testCase ) const {
14682 return std::any_of( m_filters.begin(), m_filters.end(), [&]( Filter const& f ){ return f.matches( testCase ); } );
14683 }
14684
14685 TestSpec::Matches TestSpec::matchesByFilter( std::vector<TestCase> const& testCases, IConfig const& config ) const
14686 {
14687 Matches matches( m_filters.size() );
14688 std::transform( m_filters.begin(), m_filters.end(), matches.begin(), [&]( Filter const& filter ){
14689 std::vector<TestCase const*> currentMatches;
14690 for( auto const& test : testCases )
14691 if( isThrowSafe( test, config ) && filter.matches( test ) )
14692 currentMatches.emplace_back( &test );
14693 return FilterMatch{ filter.name(), currentMatches };
14694 } );
14695 return matches;
14696 }
14697
14698 const TestSpec::vectorStrings& TestSpec::getInvalidArgs() const{
14699 return (m_invalidArgs);
14700 }
14701
14702}
14703// end catch_test_spec.cpp
14704// start catch_test_spec_parser.cpp
14705
14706namespace Catch {
14707
14708 TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
14709
14710 TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
14711 m_mode = None;
14712 m_exclusion = false;
14713 m_arg = m_tagAliases->expandAliases( arg );
14714 m_escapeChars.clear();
14715 m_substring.reserve(m_arg.size());
14716 m_patternName.reserve(m_arg.size());
14717 m_realPatternPos = 0;
14718
14719 for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
14720 //if visitChar fails
14721 if( !visitChar( m_arg[m_pos] ) ){
14722 m_testSpec.m_invalidArgs.push_back(arg);
14723 break;
14724 }
14725 endMode();
14726 return *this;
14727 }
14728 TestSpec TestSpecParser::testSpec() {
14729 addFilter();
14730 return m_testSpec;
14731 }
14732 bool TestSpecParser::visitChar( char c ) {
14733 if( (m_mode != EscapedName) && (c == '\\') ) {
14734 escape();
14735 addCharToPattern(c);
14736 return true;
14737 }else if((m_mode != EscapedName) && (c == ',') ) {
14738 return separate();
14739 }
14740
14741 switch( m_mode ) {
14742 case None:
14743 if( processNoneChar( c ) )
14744 return true;
14745 break;
14746 case Name:
14747 processNameChar( c );
14748 break;
14749 case EscapedName:
14750 endMode();
14751 addCharToPattern(c);
14752 return true;
14753 default:
14754 case Tag:
14755 case QuotedName:
14756 if( processOtherChar( c ) )
14757 return true;
14758 break;
14759 }
14760
14761 m_substring += c;
14762 if( !isControlChar( c ) ) {
14763 m_patternName += c;
14764 m_realPatternPos++;
14765 }
14766 return true;
14767 }
14768 // Two of the processing methods return true to signal the caller to return
14769 // without adding the given character to the current pattern strings
14770 bool TestSpecParser::processNoneChar( char c ) {
14771 switch( c ) {
14772 case ' ':
14773 return true;
14774 case '~':
14775 m_exclusion = true;
14776 return false;
14777 case '[':
14778 startNewMode( Tag );
14779 return false;
14780 case '"':
14781 startNewMode( QuotedName );
14782 return false;
14783 default:
14784 startNewMode( Name );
14785 return false;
14786 }
14787 }
14788 void TestSpecParser::processNameChar( char c ) {
14789 if( c == '[' ) {
14790 if( m_substring == "exclude:" )
14791 m_exclusion = true;
14792 else
14793 endMode();
14794 startNewMode( Tag );
14795 }
14796 }
14797 bool TestSpecParser::processOtherChar( char c ) {
14798 if( !isControlChar( c ) )
14799 return false;
14800 m_substring += c;
14801 endMode();
14802 return true;
14803 }
14804 void TestSpecParser::startNewMode( Mode mode ) {
14805 m_mode = mode;
14806 }
14807 void TestSpecParser::endMode() {
14808 switch( m_mode ) {
14809 case Name:
14810 case QuotedName:
14811 return addNamePattern();
14812 case Tag:
14813 return addTagPattern();
14814 case EscapedName:
14815 revertBackToLastMode();
14816 return;
14817 case None:
14818 default:
14819 return startNewMode( None );
14820 }
14821 }
14822 void TestSpecParser::escape() {
14823 saveLastMode();
14824 m_mode = EscapedName;
14825 m_escapeChars.push_back(m_realPatternPos);
14826 }
14827 bool TestSpecParser::isControlChar( char c ) const {
14828 switch( m_mode ) {
14829 default:
14830 return false;
14831 case None:
14832 return c == '~';
14833 case Name:
14834 return c == '[';
14835 case EscapedName:
14836 return true;
14837 case QuotedName:
14838 return c == '"';
14839 case Tag:
14840 return c == '[' || c == ']';
14841 }
14842 }
14843
14844 void TestSpecParser::addFilter() {
14845 if( !m_currentFilter.m_patterns.empty() ) {
14846 m_testSpec.m_filters.push_back( m_currentFilter );
14847 m_currentFilter = TestSpec::Filter();
14848 }
14849 }
14850
14851 void TestSpecParser::saveLastMode() {
14852 lastMode = m_mode;
14853 }
14854
14855 void TestSpecParser::revertBackToLastMode() {
14856 m_mode = lastMode;
14857 }
14858
14859 bool TestSpecParser::separate() {
14860 if( (m_mode==QuotedName) || (m_mode==Tag) ){
14861 //invalid argument, signal failure to previous scope.
14862 m_mode = None;
14863 m_pos = m_arg.size();
14864 m_substring.clear();
14865 m_patternName.clear();
14866 m_realPatternPos = 0;
14867 return false;
14868 }
14869 endMode();
14870 addFilter();
14871 return true; //success
14872 }
14873
14874 std::string TestSpecParser::preprocessPattern() {
14875 std::string token = m_patternName;
14876 for (std::size_t i = 0; i < m_escapeChars.size(); ++i)
14877 token = token.substr(0, m_escapeChars[i] - i) + token.substr(m_escapeChars[i] - i + 1);
14878 m_escapeChars.clear();
14879 if (startsWith(token, "exclude:")) {
14880 m_exclusion = true;
14881 token = token.substr(8);
14882 }
14883
14884 m_patternName.clear();
14885 m_realPatternPos = 0;
14886
14887 return token;
14888 }
14889
14890 void TestSpecParser::addNamePattern() {
14891 auto token = preprocessPattern();
14892
14893 if (!token.empty()) {
14894 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::NamePattern>(token, m_substring);
14895 if (m_exclusion)
14896 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14897 m_currentFilter.m_patterns.push_back(pattern);
14898 }
14899 m_substring.clear();
14900 m_exclusion = false;
14901 m_mode = None;
14902 }
14903
14904 void TestSpecParser::addTagPattern() {
14905 auto token = preprocessPattern();
14906
14907 if (!token.empty()) {
14908 // If the tag pattern is the "hide and tag" shorthand (e.g. [.foo])
14909 // we have to create a separate hide tag and shorten the real one
14910 if (token.size() > 1 && token[0] == '.') {
14911 token.erase(token.begin());
14912 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(".", m_substring);
14913 if (m_exclusion) {
14914 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14915 }
14916 m_currentFilter.m_patterns.push_back(pattern);
14917 }
14918
14919 TestSpec::PatternPtr pattern = std::make_shared<TestSpec::TagPattern>(token, m_substring);
14920
14921 if (m_exclusion) {
14922 pattern = std::make_shared<TestSpec::ExcludedPattern>(pattern);
14923 }
14924 m_currentFilter.m_patterns.push_back(pattern);
14925 }
14926 m_substring.clear();
14927 m_exclusion = false;
14928 m_mode = None;
14929 }
14930
14931 TestSpec parseTestSpec( std::string const& arg ) {
14932 return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
14933 }
14934
14935} // namespace Catch
14936// end catch_test_spec_parser.cpp
14937// start catch_timer.cpp
14938
14939#include <chrono>
14940
14941static const uint64_t nanosecondsInSecond = 1000000000;
14942
14943namespace Catch {
14944
14945 auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
14946 return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
14947 }
14948
14949 namespace {
14950 auto estimateClockResolution() -> uint64_t {
14951 uint64_t sum = 0;
14952 static const uint64_t iterations = 1000000;
14953
14954 auto startTime = getCurrentNanosecondsSinceEpoch();
14955
14956 for( std::size_t i = 0; i < iterations; ++i ) {
14957
14958 uint64_t ticks;
14959 uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
14960 do {
14961 ticks = getCurrentNanosecondsSinceEpoch();
14962 } while( ticks == baseTicks );
14963
14964 auto delta = ticks - baseTicks;
14965 sum += delta;
14966
14967 // If we have been calibrating for over 3 seconds -- the clock
14968 // is terrible and we should move on.
14969 // TBD: How to signal that the measured resolution is probably wrong?
14970 if (ticks > startTime + 3 * nanosecondsInSecond) {
14971 return sum / ( i + 1u );
14972 }
14973 }
14974
14975 // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
14976 // - and potentially do more iterations if there's a high variance.
14977 return sum/iterations;
14978 }
14979 }
14980 auto getEstimatedClockResolution() -> uint64_t {
14981 static auto s_resolution = estimateClockResolution();
14982 return s_resolution;
14983 }
14984
14985 void Timer::start() {
14986 m_nanoseconds = getCurrentNanosecondsSinceEpoch();
14987 }
14988 auto Timer::getElapsedNanoseconds() const -> uint64_t {
14989 return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
14990 }
14991 auto Timer::getElapsedMicroseconds() const -> uint64_t {
14992 return getElapsedNanoseconds()/1000;
14993 }
14994 auto Timer::getElapsedMilliseconds() const -> unsigned int {
14995 return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
14996 }
14997 auto Timer::getElapsedSeconds() const -> double {
14998 return getElapsedMicroseconds()/1000000.0;
14999 }
15000
15001} // namespace Catch
15002// end catch_timer.cpp
15003// start catch_tostring.cpp
15004
15005#if defined(__clang__)
15006# pragma clang diagnostic push
15007# pragma clang diagnostic ignored "-Wexit-time-destructors"
15008# pragma clang diagnostic ignored "-Wglobal-constructors"
15009#endif
15010
15011// Enable specific decls locally
15012#if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
15013#define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
15014#endif
15015
15016#include <cmath>
15017#include <iomanip>
15018
15019namespace Catch {
15020
15021namespace Detail {
15022
15023 const std::string unprintableString = "{?}";
15024
15025 namespace {
15026 const int hexThreshold = 255;
15027
15028 struct Endianness {
15029 enum Arch { Big, Little };
15030
15031 static Arch which() {
15032 int one = 1;
15033 // If the lowest byte we read is non-zero, we can assume
15034 // that little endian format is used.
15035 auto value = *reinterpret_cast<char*>(&one);
15036 return value ? Little : Big;
15037 }
15038 };
15039 }
15040
15041 std::string rawMemoryToString( const void *object, std::size_t size ) {
15042 // Reverse order for little endian architectures
15043 int i = 0, end = static_cast<int>( size ), inc = 1;
15044 if( Endianness::which() == Endianness::Little ) {
15045 i = end-1;
15046 end = inc = -1;
15047 }
15048
15049 unsigned char const *bytes = static_cast<unsigned char const *>(object);
15050 ReusableStringStream rss;
15051 rss << "0x" << std::setfill('0') << std::hex;
15052 for( ; i != end; i += inc )
15053 rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
15054 return rss.str();
15055 }
15056}
15057
15058template<typename T>
15059std::string fpToString( T value, int precision ) {
15060 if (Catch::isnan(value)) {
15061 return "nan";
15062 }
15063
15064 ReusableStringStream rss;
15065 rss << std::setprecision( precision )
15066 << std::fixed
15067 << value;
15068 std::string d = rss.str();
15069 std::size_t i = d.find_last_not_of( '0' );
15070 if( i != std::string::npos && i != d.size()-1 ) {
15071 if( d[i] == '.' )
15072 i++;
15073 d = d.substr( 0, i+1 );
15074 }
15075 return d;
15076}
15077
15079//
15080// Out-of-line defs for full specialization of StringMaker
15081//
15083
15084std::string StringMaker<std::string>::convert(const std::string& str) {
15085 if (!getCurrentContext().getConfig()->showInvisibles()) {
15086 return '"' + str + '"';
15087 }
15088
15089 std::string s("\"");
15090 for (char c : str) {
15091 switch (c) {
15092 case '\n':
15093 s.append("\\n");
15094 break;
15095 case '\t':
15096 s.append("\\t");
15097 break;
15098 default:
15099 s.push_back(c);
15100 break;
15101 }
15102 }
15103 s.append("\"");
15104 return s;
15105}
15106
15107#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15108std::string StringMaker<std::string_view>::convert(std::string_view str) {
15109 return ::Catch::Detail::stringify(std::string{ str });
15110}
15111#endif
15112
15113std::string StringMaker<char const*>::convert(char const* str) {
15114 if (str) {
15115 return ::Catch::Detail::stringify(std::string{ str });
15116 } else {
15117 return{ "{null string}" };
15118 }
15119}
15120std::string StringMaker<char*>::convert(char* str) {
15121 if (str) {
15122 return ::Catch::Detail::stringify(std::string{ str });
15123 } else {
15124 return{ "{null string}" };
15125 }
15126}
15127
15128#ifdef CATCH_CONFIG_WCHAR
15129std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
15130 std::string s;
15131 s.reserve(wstr.size());
15132 for (auto c : wstr) {
15133 s += (c <= 0xff) ? static_cast<char>(c) : '?';
15134 }
15135 return ::Catch::Detail::stringify(s);
15136}
15137
15138# ifdef CATCH_CONFIG_CPP17_STRING_VIEW
15139std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
15140 return StringMaker<std::wstring>::convert(std::wstring(str));
15141}
15142# endif
15143
15144std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
15145 if (str) {
15146 return ::Catch::Detail::stringify(std::wstring{ str });
15147 } else {
15148 return{ "{null string}" };
15149 }
15150}
15151std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
15152 if (str) {
15153 return ::Catch::Detail::stringify(std::wstring{ str });
15154 } else {
15155 return{ "{null string}" };
15156 }
15157}
15158#endif
15159
15160#if defined(CATCH_CONFIG_CPP17_BYTE)
15161#include <cstddef>
15162std::string StringMaker<std::byte>::convert(std::byte value) {
15163 return ::Catch::Detail::stringify(std::to_integer<unsigned long long>(value));
15164}
15165#endif // defined(CATCH_CONFIG_CPP17_BYTE)
15166
15167std::string StringMaker<int>::convert(int value) {
15168 return ::Catch::Detail::stringify(static_cast<long long>(value));
15169}
15170std::string StringMaker<long>::convert(long value) {
15171 return ::Catch::Detail::stringify(static_cast<long long>(value));
15172}
15173std::string StringMaker<long long>::convert(long long value) {
15174 ReusableStringStream rss;
15175 rss << value;
15176 if (value > Detail::hexThreshold) {
15177 rss << " (0x" << std::hex << value << ')';
15178 }
15179 return rss.str();
15180}
15181
15182std::string StringMaker<unsigned int>::convert(unsigned int value) {
15183 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15184}
15185std::string StringMaker<unsigned long>::convert(unsigned long value) {
15186 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
15187}
15188std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
15189 ReusableStringStream rss;
15190 rss << value;
15191 if (value > Detail::hexThreshold) {
15192 rss << " (0x" << std::hex << value << ')';
15193 }
15194 return rss.str();
15195}
15196
15197std::string StringMaker<bool>::convert(bool b) {
15198 return b ? "true" : "false";
15199}
15200
15201std::string StringMaker<signed char>::convert(signed char value) {
15202 if (value == '\r') {
15203 return "'\\r'";
15204 } else if (value == '\f') {
15205 return "'\\f'";
15206 } else if (value == '\n') {
15207 return "'\\n'";
15208 } else if (value == '\t') {
15209 return "'\\t'";
15210 } else if ('\0' <= value && value < ' ') {
15211 return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
15212 } else {
15213 char chstr[] = "' '";
15214 chstr[1] = value;
15215 return chstr;
15216 }
15217}
15218std::string StringMaker<char>::convert(char c) {
15219 return ::Catch::Detail::stringify(static_cast<signed char>(c));
15220}
15221std::string StringMaker<unsigned char>::convert(unsigned char c) {
15222 return ::Catch::Detail::stringify(static_cast<char>(c));
15223}
15224
15225std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
15226 return "nullptr";
15227}
15228
15229int StringMaker<float>::precision = 5;
15230
15231std::string StringMaker<float>::convert(float value) {
15232 return fpToString(value, precision) + 'f';
15233}
15234
15235int StringMaker<double>::precision = 10;
15236
15237std::string StringMaker<double>::convert(double value) {
15238 return fpToString(value, precision);
15239}
15240
15241std::string ratio_string<std::atto>::symbol() { return "a"; }
15242std::string ratio_string<std::femto>::symbol() { return "f"; }
15243std::string ratio_string<std::pico>::symbol() { return "p"; }
15244std::string ratio_string<std::nano>::symbol() { return "n"; }
15245std::string ratio_string<std::micro>::symbol() { return "u"; }
15246std::string ratio_string<std::milli>::symbol() { return "m"; }
15247
15248} // end namespace Catch
15249
15250#if defined(__clang__)
15251# pragma clang diagnostic pop
15252#endif
15253
15254// end catch_tostring.cpp
15255// start catch_totals.cpp
15256
15257namespace Catch {
15258
15259 Counts Counts::operator - ( Counts const& other ) const {
15260 Counts diff;
15261 diff.passed = passed - other.passed;
15262 diff.failed = failed - other.failed;
15263 diff.failedButOk = failedButOk - other.failedButOk;
15264 return diff;
15265 }
15266
15267 Counts& Counts::operator += ( Counts const& other ) {
15268 passed += other.passed;
15269 failed += other.failed;
15270 failedButOk += other.failedButOk;
15271 return *this;
15272 }
15273
15274 std::size_t Counts::total() const {
15275 return passed + failed + failedButOk;
15276 }
15277 bool Counts::allPassed() const {
15278 return failed == 0 && failedButOk == 0;
15279 }
15280 bool Counts::allOk() const {
15281 return failed == 0;
15282 }
15283
15284 Totals Totals::operator - ( Totals const& other ) const {
15285 Totals diff;
15286 diff.assertions = assertions - other.assertions;
15287 diff.testCases = testCases - other.testCases;
15288 return diff;
15289 }
15290
15291 Totals& Totals::operator += ( Totals const& other ) {
15292 assertions += other.assertions;
15293 testCases += other.testCases;
15294 return *this;
15295 }
15296
15297 Totals Totals::delta( Totals const& prevTotals ) const {
15298 Totals diff = *this - prevTotals;
15299 if( diff.assertions.failed > 0 )
15300 ++diff.testCases.failed;
15301 else if( diff.assertions.failedButOk > 0 )
15302 ++diff.testCases.failedButOk;
15303 else
15304 ++diff.testCases.passed;
15305 return diff;
15306 }
15307
15308}
15309// end catch_totals.cpp
15310// start catch_uncaught_exceptions.cpp
15311
15312// start catch_config_uncaught_exceptions.hpp
15313
15314// Copyright Catch2 Authors
15315// Distributed under the Boost Software License, Version 1.0.
15316// (See accompanying file LICENSE_1_0.txt or copy at
15317// https://www.boost.org/LICENSE_1_0.txt)
15318
15319// SPDX-License-Identifier: BSL-1.0
15320
15321#ifndef CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15322#define CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15323
15324#if defined(_MSC_VER)
15325# if _MSC_VER >= 1900 // Visual Studio 2015 or newer
15326# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15327# endif
15328#endif
15329
15330#include <exception>
15331
15332#if defined(__cpp_lib_uncaught_exceptions) \
15333 && !defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15334
15335# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15336#endif // __cpp_lib_uncaught_exceptions
15337
15338#if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) \
15339 && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) \
15340 && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15341
15342# define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
15343#endif
15344
15345#endif // CATCH_CONFIG_UNCAUGHT_EXCEPTIONS_HPP
15346// end catch_config_uncaught_exceptions.hpp
15347#include <exception>
15348
15349namespace Catch {
15350 bool uncaught_exceptions() {
15351#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
15352 return false;
15353#elif defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
15354 return std::uncaught_exceptions() > 0;
15355#else
15356 return std::uncaught_exception();
15357#endif
15358 }
15359} // end namespace Catch
15360// end catch_uncaught_exceptions.cpp
15361// start catch_version.cpp
15362
15363#include <ostream>
15364
15365namespace Catch {
15366
15367 Version::Version
15368 ( unsigned int _majorVersion,
15369 unsigned int _minorVersion,
15370 unsigned int _patchNumber,
15371 char const * const _branchName,
15372 unsigned int _buildNumber )
15373 : majorVersion( _majorVersion ),
15374 minorVersion( _minorVersion ),
15375 patchNumber( _patchNumber ),
15376 branchName( _branchName ),
15377 buildNumber( _buildNumber )
15378 {}
15379
15380 std::ostream& operator << ( std::ostream& os, Version const& version ) {
15381 os << version.majorVersion << '.'
15382 << version.minorVersion << '.'
15383 << version.patchNumber;
15384 // branchName is never null -> 0th char is \0 if it is empty
15385 if (version.branchName[0]) {
15386 os << '-' << version.branchName
15387 << '.' << version.buildNumber;
15388 }
15389 return os;
15390 }
15391
15392 Version const& libraryVersion() {
15393 static Version version( 2, 13, 10, "", 0 );
15394 return version;
15395 }
15396
15397}
15398// end catch_version.cpp
15399// start catch_wildcard_pattern.cpp
15400
15401namespace Catch {
15402
15403 WildcardPattern::WildcardPattern( std::string const& pattern,
15404 CaseSensitive::Choice caseSensitivity )
15405 : m_caseSensitivity( caseSensitivity ),
15406 m_pattern( normaliseString( pattern ) )
15407 {
15408 if( startsWith( m_pattern, '*' ) ) {
15409 m_pattern = m_pattern.substr( 1 );
15410 m_wildcard = WildcardAtStart;
15411 }
15412 if( endsWith( m_pattern, '*' ) ) {
15413 m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
15414 m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
15415 }
15416 }
15417
15418 bool WildcardPattern::matches( std::string const& str ) const {
15419 switch( m_wildcard ) {
15420 case NoWildcard:
15421 return m_pattern == normaliseString( str );
15422 case WildcardAtStart:
15423 return endsWith( normaliseString( str ), m_pattern );
15424 case WildcardAtEnd:
15425 return startsWith( normaliseString( str ), m_pattern );
15426 case WildcardAtBothEnds:
15427 return contains( normaliseString( str ), m_pattern );
15428 default:
15429 CATCH_INTERNAL_ERROR( "Unknown enum" );
15430 }
15431 }
15432
15433 std::string WildcardPattern::normaliseString( std::string const& str ) const {
15434 return trim( m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str );
15435 }
15436}
15437// end catch_wildcard_pattern.cpp
15438// start catch_xmlwriter.cpp
15439
15440#include <iomanip>
15441#include <type_traits>
15442
15443namespace Catch {
15444
15445namespace {
15446
15447 size_t trailingBytes(unsigned char c) {
15448 if ((c & 0xE0) == 0xC0) {
15449 return 2;
15450 }
15451 if ((c & 0xF0) == 0xE0) {
15452 return 3;
15453 }
15454 if ((c & 0xF8) == 0xF0) {
15455 return 4;
15456 }
15457 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
15458 }
15459
15460 uint32_t headerValue(unsigned char c) {
15461 if ((c & 0xE0) == 0xC0) {
15462 return c & 0x1F;
15463 }
15464 if ((c & 0xF0) == 0xE0) {
15465 return c & 0x0F;
15466 }
15467 if ((c & 0xF8) == 0xF0) {
15468 return c & 0x07;
15469 }
15470 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
15471 }
15472
15473 void hexEscapeChar(std::ostream& os, unsigned char c) {
15474 std::ios_base::fmtflags f(os.flags());
15475 os << "\\x"
15476 << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
15477 << static_cast<int>(c);
15478 os.flags(f);
15479 }
15480
15481 bool shouldNewline(XmlFormatting fmt) {
15482 return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Newline));
15483 }
15484
15485 bool shouldIndent(XmlFormatting fmt) {
15486 return !!(static_cast<std::underlying_type<XmlFormatting>::type>(fmt & XmlFormatting::Indent));
15487 }
15488
15489} // anonymous namespace
15490
15491 XmlFormatting operator | (XmlFormatting lhs, XmlFormatting rhs) {
15492 return static_cast<XmlFormatting>(
15493 static_cast<std::underlying_type<XmlFormatting>::type>(lhs) |
15494 static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
15495 );
15496 }
15497
15498 XmlFormatting operator & (XmlFormatting lhs, XmlFormatting rhs) {
15499 return static_cast<XmlFormatting>(
15500 static_cast<std::underlying_type<XmlFormatting>::type>(lhs) &
15501 static_cast<std::underlying_type<XmlFormatting>::type>(rhs)
15502 );
15503 }
15504
15505 XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
15506 : m_str( str ),
15507 m_forWhat( forWhat )
15508 {}
15509
15510 void XmlEncode::encodeTo( std::ostream& os ) const {
15511 // Apostrophe escaping not necessary if we always use " to write attributes
15512 // (see: http://www.w3.org/TR/xml/#syntax)
15513
15514 for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
15515 unsigned char c = m_str[idx];
15516 switch (c) {
15517 case '<': os << "&lt;"; break;
15518 case '&': os << "&amp;"; break;
15519
15520 case '>':
15521 // See: http://www.w3.org/TR/xml/#syntax
15522 if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
15523 os << "&gt;";
15524 else
15525 os << c;
15526 break;
15527
15528 case '\"':
15529 if (m_forWhat == ForAttributes)
15530 os << "&quot;";
15531 else
15532 os << c;
15533 break;
15534
15535 default:
15536 // Check for control characters and invalid utf-8
15537
15538 // Escape control characters in standard ascii
15539 // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
15540 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
15541 hexEscapeChar(os, c);
15542 break;
15543 }
15544
15545 // Plain ASCII: Write it to stream
15546 if (c < 0x7F) {
15547 os << c;
15548 break;
15549 }
15550
15551 // UTF-8 territory
15552 // Check if the encoding is valid and if it is not, hex escape bytes.
15553 // Important: We do not check the exact decoded values for validity, only the encoding format
15554 // First check that this bytes is a valid lead byte:
15555 // This means that it is not encoded as 1111 1XXX
15556 // Or as 10XX XXXX
15557 if (c < 0xC0 ||
15558 c >= 0xF8) {
15559 hexEscapeChar(os, c);
15560 break;
15561 }
15562
15563 auto encBytes = trailingBytes(c);
15564 // Are there enough bytes left to avoid accessing out-of-bounds memory?
15565 if (idx + encBytes - 1 >= m_str.size()) {
15566 hexEscapeChar(os, c);
15567 break;
15568 }
15569 // The header is valid, check data
15570 // The next encBytes bytes must together be a valid utf-8
15571 // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
15572 bool valid = true;
15573 uint32_t value = headerValue(c);
15574 for (std::size_t n = 1; n < encBytes; ++n) {
15575 unsigned char nc = m_str[idx + n];
15576 valid &= ((nc & 0xC0) == 0x80);
15577 value = (value << 6) | (nc & 0x3F);
15578 }
15579
15580 if (
15581 // Wrong bit pattern of following bytes
15582 (!valid) ||
15583 // Overlong encodings
15584 (value < 0x80) ||
15585 (0x80 <= value && value < 0x800 && encBytes > 2) ||
15586 (0x800 < value && value < 0x10000 && encBytes > 3) ||
15587 // Encoded value out of range
15588 (value >= 0x110000)
15589 ) {
15590 hexEscapeChar(os, c);
15591 break;
15592 }
15593
15594 // If we got here, this is in fact a valid(ish) utf-8 sequence
15595 for (std::size_t n = 0; n < encBytes; ++n) {
15596 os << m_str[idx + n];
15597 }
15598 idx += encBytes - 1;
15599 break;
15600 }
15601 }
15602 }
15603
15604 std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
15605 xmlEncode.encodeTo( os );
15606 return os;
15607 }
15608
15609 XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer, XmlFormatting fmt )
15610 : m_writer( writer ),
15611 m_fmt(fmt)
15612 {}
15613
15614 XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
15615 : m_writer( other.m_writer ),
15616 m_fmt(other.m_fmt)
15617 {
15618 other.m_writer = nullptr;
15619 other.m_fmt = XmlFormatting::None;
15620 }
15621 XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
15622 if ( m_writer ) {
15623 m_writer->endElement();
15624 }
15625 m_writer = other.m_writer;
15626 other.m_writer = nullptr;
15627 m_fmt = other.m_fmt;
15628 other.m_fmt = XmlFormatting::None;
15629 return *this;
15630 }
15631
15632 XmlWriter::ScopedElement::~ScopedElement() {
15633 if (m_writer) {
15634 m_writer->endElement(m_fmt);
15635 }
15636 }
15637
15638 XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, XmlFormatting fmt ) {
15639 m_writer->writeText( text, fmt );
15640 return *this;
15641 }
15642
15643 XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
15644 {
15645 writeDeclaration();
15646 }
15647
15648 XmlWriter::~XmlWriter() {
15649 while (!m_tags.empty()) {
15650 endElement();
15651 }
15652 newlineIfNecessary();
15653 }
15654
15655 XmlWriter& XmlWriter::startElement( std::string const& name, XmlFormatting fmt ) {
15656 ensureTagClosed();
15657 newlineIfNecessary();
15658 if (shouldIndent(fmt)) {
15659 m_os << m_indent;
15660 m_indent += " ";
15661 }
15662 m_os << '<' << name;
15663 m_tags.push_back( name );
15664 m_tagIsOpen = true;
15665 applyFormatting(fmt);
15666 return *this;
15667 }
15668
15669 XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name, XmlFormatting fmt ) {
15670 ScopedElement scoped( this, fmt );
15671 startElement( name, fmt );
15672 return scoped;
15673 }
15674
15675 XmlWriter& XmlWriter::endElement(XmlFormatting fmt) {
15676 m_indent = m_indent.substr(0, m_indent.size() - 2);
15677
15678 if( m_tagIsOpen ) {
15679 m_os << "/>";
15680 m_tagIsOpen = false;
15681 } else {
15682 newlineIfNecessary();
15683 if (shouldIndent(fmt)) {
15684 m_os << m_indent;
15685 }
15686 m_os << "</" << m_tags.back() << ">";
15687 }
15688 m_os << std::flush;
15689 applyFormatting(fmt);
15690 m_tags.pop_back();
15691 return *this;
15692 }
15693
15694 XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
15695 if( !name.empty() && !attribute.empty() )
15696 m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
15697 return *this;
15698 }
15699
15700 XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
15701 m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
15702 return *this;
15703 }
15704
15705 XmlWriter& XmlWriter::writeText( std::string const& text, XmlFormatting fmt) {
15706 if( !text.empty() ){
15707 bool tagWasOpen = m_tagIsOpen;
15708 ensureTagClosed();
15709 if (tagWasOpen && shouldIndent(fmt)) {
15710 m_os << m_indent;
15711 }
15712 m_os << XmlEncode( text );
15713 applyFormatting(fmt);
15714 }
15715 return *this;
15716 }
15717
15718 XmlWriter& XmlWriter::writeComment( std::string const& text, XmlFormatting fmt) {
15719 ensureTagClosed();
15720 if (shouldIndent(fmt)) {
15721 m_os << m_indent;
15722 }
15723 m_os << "<!--" << text << "-->";
15724 applyFormatting(fmt);
15725 return *this;
15726 }
15727
15728 void XmlWriter::writeStylesheetRef( std::string const& url ) {
15729 m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
15730 }
15731
15732 XmlWriter& XmlWriter::writeBlankLine() {
15733 ensureTagClosed();
15734 m_os << '\n';
15735 return *this;
15736 }
15737
15738 void XmlWriter::ensureTagClosed() {
15739 if( m_tagIsOpen ) {
15740 m_os << '>' << std::flush;
15741 newlineIfNecessary();
15742 m_tagIsOpen = false;
15743 }
15744 }
15745
15746 void XmlWriter::applyFormatting(XmlFormatting fmt) {
15747 m_needsNewline = shouldNewline(fmt);
15748 }
15749
15750 void XmlWriter::writeDeclaration() {
15751 m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
15752 }
15753
15754 void XmlWriter::newlineIfNecessary() {
15755 if( m_needsNewline ) {
15756 m_os << std::endl;
15757 m_needsNewline = false;
15758 }
15759 }
15760}
15761// end catch_xmlwriter.cpp
15762// start catch_reporter_bases.cpp
15763
15764#include <cstring>
15765#include <cfloat>
15766#include <cstdio>
15767#include <cassert>
15768#include <memory>
15769
15770namespace Catch {
15771 void prepareExpandedExpression(AssertionResult& result) {
15772 result.getExpandedExpression();
15773 }
15774
15775 // Because formatting using c++ streams is stateful, drop down to C is required
15776 // Alternatively we could use stringstream, but its performance is... not good.
15777 std::string getFormattedDuration( double duration ) {
15778 // Max exponent + 1 is required to represent the whole part
15779 // + 1 for decimal point
15780 // + 3 for the 3 decimal places
15781 // + 1 for null terminator
15782 const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
15783 char buffer[maxDoubleSize];
15784
15785 // Save previous errno, to prevent sprintf from overwriting it
15786 ErrnoGuard guard;
15787#ifdef _MSC_VER
15788 sprintf_s(buffer, "%.3f", duration);
15789#else
15790 std::sprintf(buffer, "%.3f", duration);
15791#endif
15792 return std::string(buffer);
15793 }
15794
15795 bool shouldShowDuration( IConfig const& config, double duration ) {
15796 if ( config.showDurations() == ShowDurations::Always ) {
15797 return true;
15798 }
15799 if ( config.showDurations() == ShowDurations::Never ) {
15800 return false;
15801 }
15802 const double min = config.minDuration();
15803 return min >= 0 && duration >= min;
15804 }
15805
15806 std::string serializeFilters( std::vector<std::string> const& container ) {
15807 ReusableStringStream oss;
15808 bool first = true;
15809 for (auto&& filter : container)
15810 {
15811 if (!first)
15812 oss << ' ';
15813 else
15814 first = false;
15815
15816 oss << filter;
15817 }
15818 return oss.str();
15819 }
15820
15821 TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
15822 :StreamingReporterBase(_config) {}
15823
15824 std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
15825 return { Verbosity::Quiet, Verbosity::Normal, Verbosity::High };
15826 }
15827
15828 void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
15829
15830 bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
15831 return false;
15832 }
15833
15834} // end namespace Catch
15835// end catch_reporter_bases.cpp
15836// start catch_reporter_compact.cpp
15837
15838namespace {
15839
15840#ifdef CATCH_PLATFORM_MAC
15841 const char* failedString() { return "FAILED"; }
15842 const char* passedString() { return "PASSED"; }
15843#else
15844 const char* failedString() { return "failed"; }
15845 const char* passedString() { return "passed"; }
15846#endif
15847
15848 // Colour::LightGrey
15849 Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
15850
15851 std::string bothOrAll( std::size_t count ) {
15852 return count == 1 ? std::string() :
15853 count == 2 ? "both " : "all " ;
15854 }
15855
15856} // anon namespace
15857
15858namespace Catch {
15859namespace {
15860// Colour, message variants:
15861// - white: No tests ran.
15862// - red: Failed [both/all] N test cases, failed [both/all] M assertions.
15863// - white: Passed [both/all] N test cases (no assertions).
15864// - red: Failed N tests cases, failed M assertions.
15865// - green: Passed [both/all] N tests cases with M assertions.
15866void printTotals(std::ostream& out, const Totals& totals) {
15867 if (totals.testCases.total() == 0) {
15868 out << "No tests ran.";
15869 } else if (totals.testCases.failed == totals.testCases.total()) {
15870 Colour colour(Colour::ResultError);
15871 const std::string qualify_assertions_failed =
15872 totals.assertions.failed == totals.assertions.total() ?
15873 bothOrAll(totals.assertions.failed) : std::string();
15874 out <<
15875 "Failed " << bothOrAll(totals.testCases.failed)
15876 << pluralise(totals.testCases.failed, "test case") << ", "
15877 "failed " << qualify_assertions_failed <<
15878 pluralise(totals.assertions.failed, "assertion") << '.';
15879 } else if (totals.assertions.total() == 0) {
15880 out <<
15881 "Passed " << bothOrAll(totals.testCases.total())
15882 << pluralise(totals.testCases.total(), "test case")
15883 << " (no assertions).";
15884 } else if (totals.assertions.failed) {
15885 Colour colour(Colour::ResultError);
15886 out <<
15887 "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
15888 "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
15889 } else {
15890 Colour colour(Colour::ResultSuccess);
15891 out <<
15892 "Passed " << bothOrAll(totals.testCases.passed)
15893 << pluralise(totals.testCases.passed, "test case") <<
15894 " with " << pluralise(totals.assertions.passed, "assertion") << '.';
15895 }
15896}
15897
15898// Implementation of CompactReporter formatting
15899class AssertionPrinter {
15900public:
15901 AssertionPrinter& operator= (AssertionPrinter const&) = delete;
15902 AssertionPrinter(AssertionPrinter const&) = delete;
15903 AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
15904 : stream(_stream)
15905 , result(_stats.assertionResult)
15906 , messages(_stats.infoMessages)
15907 , itMessage(_stats.infoMessages.begin())
15908 , printInfoMessages(_printInfoMessages) {}
15909
15910 void print() {
15911 printSourceInfo();
15912
15913 itMessage = messages.begin();
15914
15915 switch (result.getResultType()) {
15916 case ResultWas::Ok:
15917 printResultType(Colour::ResultSuccess, passedString());
15918 printOriginalExpression();
15919 printReconstructedExpression();
15920 if (!result.hasExpression())
15921 printRemainingMessages(Colour::None);
15922 else
15923 printRemainingMessages();
15924 break;
15925 case ResultWas::ExpressionFailed:
15926 if (result.isOk())
15927 printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
15928 else
15929 printResultType(Colour::Error, failedString());
15930 printOriginalExpression();
15931 printReconstructedExpression();
15932 printRemainingMessages();
15933 break;
15934 case ResultWas::ThrewException:
15935 printResultType(Colour::Error, failedString());
15936 printIssue("unexpected exception with message:");
15937 printMessage();
15938 printExpressionWas();
15939 printRemainingMessages();
15940 break;
15941 case ResultWas::FatalErrorCondition:
15942 printResultType(Colour::Error, failedString());
15943 printIssue("fatal error condition with message:");
15944 printMessage();
15945 printExpressionWas();
15946 printRemainingMessages();
15947 break;
15948 case ResultWas::DidntThrowException:
15949 printResultType(Colour::Error, failedString());
15950 printIssue("expected exception, got none");
15951 printExpressionWas();
15952 printRemainingMessages();
15953 break;
15954 case ResultWas::Info:
15955 printResultType(Colour::None, "info");
15956 printMessage();
15957 printRemainingMessages();
15958 break;
15959 case ResultWas::Warning:
15960 printResultType(Colour::None, "warning");
15961 printMessage();
15962 printRemainingMessages();
15963 break;
15964 case ResultWas::ExplicitFailure:
15965 printResultType(Colour::Error, failedString());
15966 printIssue("explicitly");
15967 printRemainingMessages(Colour::None);
15968 break;
15969 // These cases are here to prevent compiler warnings
15970 case ResultWas::Unknown:
15971 case ResultWas::FailureBit:
15972 case ResultWas::Exception:
15973 printResultType(Colour::Error, "** internal error **");
15974 break;
15975 }
15976 }
15977
15978private:
15979 void printSourceInfo() const {
15980 Colour colourGuard(Colour::FileName);
15981 stream << result.getSourceInfo() << ':';
15982 }
15983
15984 void printResultType(Colour::Code colour, std::string const& passOrFail) const {
15985 if (!passOrFail.empty()) {
15986 {
15987 Colour colourGuard(colour);
15988 stream << ' ' << passOrFail;
15989 }
15990 stream << ':';
15991 }
15992 }
15993
15994 void printIssue(std::string const& issue) const {
15995 stream << ' ' << issue;
15996 }
15997
15998 void printExpressionWas() {
15999 if (result.hasExpression()) {
16000 stream << ';';
16001 {
16002 Colour colour(dimColour());
16003 stream << " expression was:";
16004 }
16005 printOriginalExpression();
16006 }
16007 }
16008
16009 void printOriginalExpression() const {
16010 if (result.hasExpression()) {
16011 stream << ' ' << result.getExpression();
16012 }
16013 }
16014
16015 void printReconstructedExpression() const {
16016 if (result.hasExpandedExpression()) {
16017 {
16018 Colour colour(dimColour());
16019 stream << " for: ";
16020 }
16021 stream << result.getExpandedExpression();
16022 }
16023 }
16024
16025 void printMessage() {
16026 if (itMessage != messages.end()) {
16027 stream << " '" << itMessage->message << '\'';
16028 ++itMessage;
16029 }
16030 }
16031
16032 void printRemainingMessages(Colour::Code colour = dimColour()) {
16033 if (itMessage == messages.end())
16034 return;
16035
16036 const auto itEnd = messages.cend();
16037 const auto N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
16038
16039 {
16040 Colour colourGuard(colour);
16041 stream << " with " << pluralise(N, "message") << ':';
16042 }
16043
16044 while (itMessage != itEnd) {
16045 // If this assertion is a warning ignore any INFO messages
16046 if (printInfoMessages || itMessage->type != ResultWas::Info) {
16047 printMessage();
16048 if (itMessage != itEnd) {
16049 Colour colourGuard(dimColour());
16050 stream << " and";
16051 }
16052 continue;
16053 }
16054 ++itMessage;
16055 }
16056 }
16057
16058private:
16059 std::ostream& stream;
16060 AssertionResult const& result;
16061 std::vector<MessageInfo> messages;
16062 std::vector<MessageInfo>::const_iterator itMessage;
16063 bool printInfoMessages;
16064};
16065
16066} // anon namespace
16067
16068 std::string CompactReporter::getDescription() {
16069 return "Reports test results on a single line, suitable for IDEs";
16070 }
16071
16072 void CompactReporter::noMatchingTestCases( std::string const& spec ) {
16073 stream << "No test cases matched '" << spec << '\'' << std::endl;
16074 }
16075
16076 void CompactReporter::assertionStarting( AssertionInfo const& ) {}
16077
16078 bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
16079 AssertionResult const& result = _assertionStats.assertionResult;
16080
16081 bool printInfoMessages = true;
16082
16083 // Drop out if result was successful and we're not printing those
16084 if( !m_config->includeSuccessfulResults() && result.isOk() ) {
16085 if( result.getResultType() != ResultWas::Warning )
16086 return false;
16087 printInfoMessages = false;
16088 }
16089
16090 AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
16091 printer.print();
16092
16093 stream << std::endl;
16094 return true;
16095 }
16096
16097 void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
16098 double dur = _sectionStats.durationInSeconds;
16099 if ( shouldShowDuration( *m_config, dur ) ) {
16100 stream << getFormattedDuration( dur ) << " s: " << _sectionStats.sectionInfo.name << std::endl;
16101 }
16102 }
16103
16104 void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
16105 printTotals( stream, _testRunStats.totals );
16106 stream << '\n' << std::endl;
16107 StreamingReporterBase::testRunEnded( _testRunStats );
16108 }
16109
16110 CompactReporter::~CompactReporter() {}
16111
16112 CATCH_REGISTER_REPORTER( "compact", CompactReporter )
16113
16114} // end namespace Catch
16115// end catch_reporter_compact.cpp
16116// start catch_reporter_console.cpp
16117
16118#include <cfloat>
16119#include <cstdio>
16120
16121#if defined(_MSC_VER)
16122#pragma warning(push)
16123#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
16124 // Note that 4062 (not all labels are handled and default is missing) is enabled
16125#endif
16126
16127#if defined(__clang__)
16128# pragma clang diagnostic push
16129// For simplicity, benchmarking-only helpers are always enabled
16130# pragma clang diagnostic ignored "-Wunused-function"
16131#endif
16132
16133namespace Catch {
16134
16135namespace {
16136
16137// Formatter impl for ConsoleReporter
16138class ConsoleAssertionPrinter {
16139public:
16140 ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
16141 ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
16142 ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
16143 : stream(_stream),
16144 stats(_stats),
16145 result(_stats.assertionResult),
16146 colour(Colour::None),
16147 message(result.getMessage()),
16148 messages(_stats.infoMessages),
16149 printInfoMessages(_printInfoMessages) {
16150 switch (result.getResultType()) {
16151 case ResultWas::Ok:
16152 colour = Colour::Success;
16153 passOrFail = "PASSED";
16154 //if( result.hasMessage() )
16155 if (_stats.infoMessages.size() == 1)
16156 messageLabel = "with message";
16157 if (_stats.infoMessages.size() > 1)
16158 messageLabel = "with messages";
16159 break;
16160 case ResultWas::ExpressionFailed:
16161 if (result.isOk()) {
16162 colour = Colour::Success;
16163 passOrFail = "FAILED - but was ok";
16164 } else {
16165 colour = Colour::Error;
16166 passOrFail = "FAILED";
16167 }
16168 if (_stats.infoMessages.size() == 1)
16169 messageLabel = "with message";
16170 if (_stats.infoMessages.size() > 1)
16171 messageLabel = "with messages";
16172 break;
16173 case ResultWas::ThrewException:
16174 colour = Colour::Error;
16175 passOrFail = "FAILED";
16176 messageLabel = "due to unexpected exception with ";
16177 if (_stats.infoMessages.size() == 1)
16178 messageLabel += "message";
16179 if (_stats.infoMessages.size() > 1)
16180 messageLabel += "messages";
16181 break;
16182 case ResultWas::FatalErrorCondition:
16183 colour = Colour::Error;
16184 passOrFail = "FAILED";
16185 messageLabel = "due to a fatal error condition";
16186 break;
16187 case ResultWas::DidntThrowException:
16188 colour = Colour::Error;
16189 passOrFail = "FAILED";
16190 messageLabel = "because no exception was thrown where one was expected";
16191 break;
16192 case ResultWas::Info:
16193 messageLabel = "info";
16194 break;
16195 case ResultWas::Warning:
16196 messageLabel = "warning";
16197 break;
16198 case ResultWas::ExplicitFailure:
16199 passOrFail = "FAILED";
16200 colour = Colour::Error;
16201 if (_stats.infoMessages.size() == 1)
16202 messageLabel = "explicitly with message";
16203 if (_stats.infoMessages.size() > 1)
16204 messageLabel = "explicitly with messages";
16205 break;
16206 // These cases are here to prevent compiler warnings
16207 case ResultWas::Unknown:
16208 case ResultWas::FailureBit:
16209 case ResultWas::Exception:
16210 passOrFail = "** internal error **";
16211 colour = Colour::Error;
16212 break;
16213 }
16214 }
16215
16216 void print() const {
16217 printSourceInfo();
16218 if (stats.totals.assertions.total() > 0) {
16219 printResultType();
16220 printOriginalExpression();
16221 printReconstructedExpression();
16222 } else {
16223 stream << '\n';
16224 }
16225 printMessage();
16226 }
16227
16228private:
16229 void printResultType() const {
16230 if (!passOrFail.empty()) {
16231 Colour colourGuard(colour);
16232 stream << passOrFail << ":\n";
16233 }
16234 }
16235 void printOriginalExpression() const {
16236 if (result.hasExpression()) {
16237 Colour colourGuard(Colour::OriginalExpression);
16238 stream << " ";
16239 stream << result.getExpressionInMacro();
16240 stream << '\n';
16241 }
16242 }
16243 void printReconstructedExpression() const {
16244 if (result.hasExpandedExpression()) {
16245 stream << "with expansion:\n";
16246 Colour colourGuard(Colour::ReconstructedExpression);
16247 stream << Column(result.getExpandedExpression()).indent(2) << '\n';
16248 }
16249 }
16250 void printMessage() const {
16251 if (!messageLabel.empty())
16252 stream << messageLabel << ':' << '\n';
16253 for (auto const& msg : messages) {
16254 // If this assertion is a warning ignore any INFO messages
16255 if (printInfoMessages || msg.type != ResultWas::Info)
16256 stream << Column(msg.message).indent(2) << '\n';
16257 }
16258 }
16259 void printSourceInfo() const {
16260 Colour colourGuard(Colour::FileName);
16261 stream << result.getSourceInfo() << ": ";
16262 }
16263
16264 std::ostream& stream;
16265 AssertionStats const& stats;
16266 AssertionResult const& result;
16267 Colour::Code colour;
16268 std::string passOrFail;
16269 std::string messageLabel;
16270 std::string message;
16271 std::vector<MessageInfo> messages;
16272 bool printInfoMessages;
16273};
16274
16275std::size_t makeRatio(std::size_t number, std::size_t total) {
16276 std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
16277 return (ratio == 0 && number > 0) ? 1 : ratio;
16278}
16279
16280std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
16281 if (i > j && i > k)
16282 return i;
16283 else if (j > k)
16284 return j;
16285 else
16286 return k;
16287}
16288
16289struct ColumnInfo {
16290 enum Justification { Left, Right };
16291 std::string name;
16292 int width;
16293 Justification justification;
16294};
16295struct ColumnBreak {};
16296struct RowBreak {};
16297
16298class Duration {
16299 enum class Unit {
16300 Auto,
16301 Nanoseconds,
16302 Microseconds,
16303 Milliseconds,
16304 Seconds,
16305 Minutes
16306 };
16307 static const uint64_t s_nanosecondsInAMicrosecond = 1000;
16308 static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
16309 static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
16310 static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
16311
16312 double m_inNanoseconds;
16313 Unit m_units;
16314
16315public:
16316 explicit Duration(double inNanoseconds, Unit units = Unit::Auto)
16317 : m_inNanoseconds(inNanoseconds),
16318 m_units(units) {
16319 if (m_units == Unit::Auto) {
16320 if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
16321 m_units = Unit::Nanoseconds;
16322 else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
16323 m_units = Unit::Microseconds;
16324 else if (m_inNanoseconds < s_nanosecondsInASecond)
16325 m_units = Unit::Milliseconds;
16326 else if (m_inNanoseconds < s_nanosecondsInAMinute)
16327 m_units = Unit::Seconds;
16328 else
16329 m_units = Unit::Minutes;
16330 }
16331
16332 }
16333
16334 auto value() const -> double {
16335 switch (m_units) {
16336 case Unit::Microseconds:
16337 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
16338 case Unit::Milliseconds:
16339 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
16340 case Unit::Seconds:
16341 return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
16342 case Unit::Minutes:
16343 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
16344 default:
16345 return m_inNanoseconds;
16346 }
16347 }
16348 auto unitsAsString() const -> std::string {
16349 switch (m_units) {
16350 case Unit::Nanoseconds:
16351 return "ns";
16352 case Unit::Microseconds:
16353 return "us";
16354 case Unit::Milliseconds:
16355 return "ms";
16356 case Unit::Seconds:
16357 return "s";
16358 case Unit::Minutes:
16359 return "m";
16360 default:
16361 return "** internal error **";
16362 }
16363
16364 }
16365 friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
16366 return os << duration.value() << ' ' << duration.unitsAsString();
16367 }
16368};
16369} // end anon namespace
16370
16371class TablePrinter {
16372 std::ostream& m_os;
16373 std::vector<ColumnInfo> m_columnInfos;
16374 std::ostringstream m_oss;
16375 int m_currentColumn = -1;
16376 bool m_isOpen = false;
16377
16378public:
16379 TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
16380 : m_os( os ),
16381 m_columnInfos( std::move( columnInfos ) ) {}
16382
16383 auto columnInfos() const -> std::vector<ColumnInfo> const& {
16384 return m_columnInfos;
16385 }
16386
16387 void open() {
16388 if (!m_isOpen) {
16389 m_isOpen = true;
16390 *this << RowBreak();
16391
16392 Columns headerCols;
16393 Spacer spacer(2);
16394 for (auto const& info : m_columnInfos) {
16395 headerCols += Column(info.name).width(static_cast<std::size_t>(info.width - 2));
16396 headerCols += spacer;
16397 }
16398 m_os << headerCols << '\n';
16399
16400 m_os << Catch::getLineOfChars<'-'>() << '\n';
16401 }
16402 }
16403 void close() {
16404 if (m_isOpen) {
16405 *this << RowBreak();
16406 m_os << std::endl;
16407 m_isOpen = false;
16408 }
16409 }
16410
16411 template<typename T>
16412 friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
16413 tp.m_oss << value;
16414 return tp;
16415 }
16416
16417 friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
16418 auto colStr = tp.m_oss.str();
16419 const auto strSize = colStr.size();
16420 tp.m_oss.str("");
16421 tp.open();
16422 if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
16423 tp.m_currentColumn = -1;
16424 tp.m_os << '\n';
16425 }
16426 tp.m_currentColumn++;
16427
16428 auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
16429 auto padding = (strSize + 1 < static_cast<std::size_t>(colInfo.width))
16430 ? std::string(colInfo.width - (strSize + 1), ' ')
16431 : std::string();
16432 if (colInfo.justification == ColumnInfo::Left)
16433 tp.m_os << colStr << padding << ' ';
16434 else
16435 tp.m_os << padding << colStr << ' ';
16436 return tp;
16437 }
16438
16439 friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
16440 if (tp.m_currentColumn > 0) {
16441 tp.m_os << '\n';
16442 tp.m_currentColumn = -1;
16443 }
16444 return tp;
16445 }
16446};
16447
16448ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
16449 : StreamingReporterBase(config),
16450 m_tablePrinter(new TablePrinter(config.stream(),
16451 [&config]() -> std::vector<ColumnInfo> {
16452 if (config.fullConfig()->benchmarkNoAnalysis())
16453 {
16454 return{
16455 { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16456 { " samples", 14, ColumnInfo::Right },
16457 { " iterations", 14, ColumnInfo::Right },
16458 { " mean", 14, ColumnInfo::Right }
16459 };
16460 }
16461 else
16462 {
16463 return{
16464 { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 43, ColumnInfo::Left },
16465 { "samples mean std dev", 14, ColumnInfo::Right },
16466 { "iterations low mean low std dev", 14, ColumnInfo::Right },
16467 { "estimated high mean high std dev", 14, ColumnInfo::Right }
16468 };
16469 }
16470 }())) {}
16471ConsoleReporter::~ConsoleReporter() = default;
16472
16473std::string ConsoleReporter::getDescription() {
16474 return "Reports test results as plain lines of text";
16475}
16476
16477void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
16478 stream << "No test cases matched '" << spec << '\'' << std::endl;
16479}
16480
16481void ConsoleReporter::reportInvalidArguments(std::string const&arg){
16482 stream << "Invalid Filter: " << arg << std::endl;
16483}
16484
16485void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
16486
16487bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
16488 AssertionResult const& result = _assertionStats.assertionResult;
16489
16490 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
16491
16492 // Drop out if result was successful but we're not printing them.
16493 if (!includeResults && result.getResultType() != ResultWas::Warning)
16494 return false;
16495
16496 lazyPrint();
16497
16498 ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
16499 printer.print();
16500 stream << std::endl;
16501 return true;
16502}
16503
16504void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
16505 m_tablePrinter->close();
16506 m_headerPrinted = false;
16507 StreamingReporterBase::sectionStarting(_sectionInfo);
16508}
16509void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
16510 m_tablePrinter->close();
16511 if (_sectionStats.missingAssertions) {
16512 lazyPrint();
16513 Colour colour(Colour::ResultError);
16514 if (m_sectionStack.size() > 1)
16515 stream << "\nNo assertions in section";
16516 else
16517 stream << "\nNo assertions in test case";
16518 stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
16519 }
16520 double dur = _sectionStats.durationInSeconds;
16521 if (shouldShowDuration(*m_config, dur)) {
16522 stream << getFormattedDuration(dur) << " s: " << _sectionStats.sectionInfo.name << std::endl;
16523 }
16524 if (m_headerPrinted) {
16525 m_headerPrinted = false;
16526 }
16527 StreamingReporterBase::sectionEnded(_sectionStats);
16528}
16529
16530#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
16531void ConsoleReporter::benchmarkPreparing(std::string const& name) {
16532 lazyPrintWithoutClosingBenchmarkTable();
16533
16534 auto nameCol = Column(name).width(static_cast<std::size_t>(m_tablePrinter->columnInfos()[0].width - 2));
16535
16536 bool firstLine = true;
16537 for (auto line : nameCol) {
16538 if (!firstLine)
16539 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
16540 else
16541 firstLine = false;
16542
16543 (*m_tablePrinter) << line << ColumnBreak();
16544 }
16545}
16546
16547void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
16548 (*m_tablePrinter) << info.samples << ColumnBreak()
16549 << info.iterations << ColumnBreak();
16550 if (!m_config->benchmarkNoAnalysis())
16551 (*m_tablePrinter) << Duration(info.estimatedDuration) << ColumnBreak();
16552}
16553void ConsoleReporter::benchmarkEnded(BenchmarkStats<> const& stats) {
16554 if (m_config->benchmarkNoAnalysis())
16555 {
16556 (*m_tablePrinter) << Duration(stats.mean.point.count()) << ColumnBreak();
16557 }
16558 else
16559 {
16560 (*m_tablePrinter) << ColumnBreak()
16561 << Duration(stats.mean.point.count()) << ColumnBreak()
16562 << Duration(stats.mean.lower_bound.count()) << ColumnBreak()
16563 << Duration(stats.mean.upper_bound.count()) << ColumnBreak() << ColumnBreak()
16564 << Duration(stats.standardDeviation.point.count()) << ColumnBreak()
16565 << Duration(stats.standardDeviation.lower_bound.count()) << ColumnBreak()
16566 << Duration(stats.standardDeviation.upper_bound.count()) << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak() << ColumnBreak();
16567 }
16568}
16569
16570void ConsoleReporter::benchmarkFailed(std::string const& error) {
16571 Colour colour(Colour::Red);
16572 (*m_tablePrinter)
16573 << "Benchmark failed (" << error << ')'
16574 << ColumnBreak() << RowBreak();
16575}
16576#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
16577
16578void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
16579 m_tablePrinter->close();
16580 StreamingReporterBase::testCaseEnded(_testCaseStats);
16581 m_headerPrinted = false;
16582}
16583void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
16584 if (currentGroupInfo.used) {
16585 printSummaryDivider();
16586 stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
16587 printTotals(_testGroupStats.totals);
16588 stream << '\n' << std::endl;
16589 }
16590 StreamingReporterBase::testGroupEnded(_testGroupStats);
16591}
16592void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
16593 printTotalsDivider(_testRunStats.totals);
16594 printTotals(_testRunStats.totals);
16595 stream << std::endl;
16596 StreamingReporterBase::testRunEnded(_testRunStats);
16597}
16598void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
16599 StreamingReporterBase::testRunStarting(_testInfo);
16600 printTestFilters();
16601}
16602
16603void ConsoleReporter::lazyPrint() {
16604
16605 m_tablePrinter->close();
16606 lazyPrintWithoutClosingBenchmarkTable();
16607}
16608
16609void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
16610
16611 if (!currentTestRunInfo.used)
16612 lazyPrintRunInfo();
16613 if (!currentGroupInfo.used)
16614 lazyPrintGroupInfo();
16615
16616 if (!m_headerPrinted) {
16617 printTestCaseAndSectionHeader();
16618 m_headerPrinted = true;
16619 }
16620}
16621void ConsoleReporter::lazyPrintRunInfo() {
16622 stream << '\n' << getLineOfChars<'~'>() << '\n';
16623 Colour colour(Colour::SecondaryText);
16624 stream << currentTestRunInfo->name
16625 << " is a Catch v" << libraryVersion() << " host application.\n"
16626 << "Run with -? for options\n\n";
16627
16628 if (m_config->rngSeed() != 0)
16629 stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
16630
16631 currentTestRunInfo.used = true;
16632}
16633void ConsoleReporter::lazyPrintGroupInfo() {
16634 if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
16635 printClosedHeader("Group: " + currentGroupInfo->name);
16636 currentGroupInfo.used = true;
16637 }
16638}
16639void ConsoleReporter::printTestCaseAndSectionHeader() {
16640 assert(!m_sectionStack.empty());
16641 printOpenHeader(currentTestCaseInfo->name);
16642
16643 if (m_sectionStack.size() > 1) {
16644 Colour colourGuard(Colour::Headers);
16645
16646 auto
16647 it = m_sectionStack.begin() + 1, // Skip first section (test case)
16648 itEnd = m_sectionStack.end();
16649 for (; it != itEnd; ++it)
16650 printHeaderString(it->name, 2);
16651 }
16652
16653 SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
16654
16655 stream << getLineOfChars<'-'>() << '\n';
16656 Colour colourGuard(Colour::FileName);
16657 stream << lineInfo << '\n';
16658 stream << getLineOfChars<'.'>() << '\n' << std::endl;
16659}
16660
16661void ConsoleReporter::printClosedHeader(std::string const& _name) {
16662 printOpenHeader(_name);
16663 stream << getLineOfChars<'.'>() << '\n';
16664}
16665void ConsoleReporter::printOpenHeader(std::string const& _name) {
16666 stream << getLineOfChars<'-'>() << '\n';
16667 {
16668 Colour colourGuard(Colour::Headers);
16669 printHeaderString(_name);
16670 }
16671}
16672
16673// if string has a : in first line will set indent to follow it on
16674// subsequent lines
16675void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
16676 std::size_t i = _string.find(": ");
16677 if (i != std::string::npos)
16678 i += 2;
16679 else
16680 i = 0;
16681 stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
16682}
16683
16684struct SummaryColumn {
16685
16686 SummaryColumn( std::string _label, Colour::Code _colour )
16687 : label( std::move( _label ) ),
16688 colour( _colour ) {}
16689 SummaryColumn addRow( std::size_t count ) {
16690 ReusableStringStream rss;
16691 rss << count;
16692 std::string row = rss.str();
16693 for (auto& oldRow : rows) {
16694 while (oldRow.size() < row.size())
16695 oldRow = ' ' + oldRow;
16696 while (oldRow.size() > row.size())
16697 row = ' ' + row;
16698 }
16699 rows.push_back(row);
16700 return *this;
16701 }
16702
16703 std::string label;
16704 Colour::Code colour;
16705 std::vector<std::string> rows;
16706
16707};
16708
16709void ConsoleReporter::printTotals( Totals const& totals ) {
16710 if (totals.testCases.total() == 0) {
16711 stream << Colour(Colour::Warning) << "No tests ran\n";
16712 } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
16713 stream << Colour(Colour::ResultSuccess) << "All tests passed";
16714 stream << " ("
16715 << pluralise(totals.assertions.passed, "assertion") << " in "
16716 << pluralise(totals.testCases.passed, "test case") << ')'
16717 << '\n';
16718 } else {
16719
16720 std::vector<SummaryColumn> columns;
16721 columns.push_back(SummaryColumn("", Colour::None)
16722 .addRow(totals.testCases.total())
16723 .addRow(totals.assertions.total()));
16724 columns.push_back(SummaryColumn("passed", Colour::Success)
16725 .addRow(totals.testCases.passed)
16726 .addRow(totals.assertions.passed));
16727 columns.push_back(SummaryColumn("failed", Colour::ResultError)
16728 .addRow(totals.testCases.failed)
16729 .addRow(totals.assertions.failed));
16730 columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
16731 .addRow(totals.testCases.failedButOk)
16732 .addRow(totals.assertions.failedButOk));
16733
16734 printSummaryRow("test cases", columns, 0);
16735 printSummaryRow("assertions", columns, 1);
16736 }
16737}
16738void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
16739 for (auto col : cols) {
16740 std::string value = col.rows[row];
16741 if (col.label.empty()) {
16742 stream << label << ": ";
16743 if (value != "0")
16744 stream << value;
16745 else
16746 stream << Colour(Colour::Warning) << "- none -";
16747 } else if (value != "0") {
16748 stream << Colour(Colour::LightGrey) << " | ";
16749 stream << Colour(col.colour)
16750 << value << ' ' << col.label;
16751 }
16752 }
16753 stream << '\n';
16754}
16755
16756void ConsoleReporter::printTotalsDivider(Totals const& totals) {
16757 if (totals.testCases.total() > 0) {
16758 std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
16759 std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
16760 std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
16761 while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
16762 findMax(failedRatio, failedButOkRatio, passedRatio)++;
16763 while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
16764 findMax(failedRatio, failedButOkRatio, passedRatio)--;
16765
16766 stream << Colour(Colour::Error) << std::string(failedRatio, '=');
16767 stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
16768 if (totals.testCases.allPassed())
16769 stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
16770 else
16771 stream << Colour(Colour::Success) << std::string(passedRatio, '=');
16772 } else {
16773 stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
16774 }
16775 stream << '\n';
16776}
16777void ConsoleReporter::printSummaryDivider() {
16778 stream << getLineOfChars<'-'>() << '\n';
16779}
16780
16781void ConsoleReporter::printTestFilters() {
16782 if (m_config->testSpec().hasFilters()) {
16783 Colour guard(Colour::BrightYellow);
16784 stream << "Filters: " << serializeFilters(m_config->getTestsOrTags()) << '\n';
16785 }
16786}
16787
16788CATCH_REGISTER_REPORTER("console", ConsoleReporter)
16789
16790} // end namespace Catch
16791
16792#if defined(_MSC_VER)
16793#pragma warning(pop)
16794#endif
16795
16796#if defined(__clang__)
16797# pragma clang diagnostic pop
16798#endif
16799// end catch_reporter_console.cpp
16800// start catch_reporter_junit.cpp
16801
16802#include <cassert>
16803#include <sstream>
16804#include <ctime>
16805#include <algorithm>
16806#include <iomanip>
16807
16808namespace Catch {
16809
16810 namespace {
16811 std::string getCurrentTimestamp() {
16812 // Beware, this is not reentrant because of backward compatibility issues
16813 // Also, UTC only, again because of backward compatibility (%z is C++11)
16814 time_t rawtime;
16815 std::time(&rawtime);
16816 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
16817
16818#ifdef _MSC_VER
16819 std::tm timeInfo = {};
16820 gmtime_s(&timeInfo, &rawtime);
16821#else
16822 std::tm* timeInfo;
16823 timeInfo = std::gmtime(&rawtime);
16824#endif
16825
16826 char timeStamp[timeStampSize];
16827 const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
16828
16829#ifdef _MSC_VER
16830 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
16831#else
16832 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
16833#endif
16834 return std::string(timeStamp, timeStampSize-1);
16835 }
16836
16837 std::string fileNameTag(const std::vector<std::string> &tags) {
16838 auto it = std::find_if(begin(tags),
16839 end(tags),
16840 [] (std::string const& tag) {return tag.front() == '#'; });
16841 if (it != tags.end())
16842 return it->substr(1);
16843 return std::string();
16844 }
16845
16846 // Formats the duration in seconds to 3 decimal places.
16847 // This is done because some genius defined Maven Surefire schema
16848 // in a way that only accepts 3 decimal places, and tools like
16849 // Jenkins use that schema for validation JUnit reporter output.
16850 std::string formatDuration( double seconds ) {
16851 ReusableStringStream rss;
16852 rss << std::fixed << std::setprecision( 3 ) << seconds;
16853 return rss.str();
16854 }
16855
16856 } // anonymous namespace
16857
16858 JunitReporter::JunitReporter( ReporterConfig const& _config )
16859 : CumulativeReporterBase( _config ),
16860 xml( _config.stream() )
16861 {
16862 m_reporterPrefs.shouldRedirectStdOut = true;
16863 m_reporterPrefs.shouldReportAllAssertions = true;
16864 }
16865
16866 JunitReporter::~JunitReporter() {}
16867
16868 std::string JunitReporter::getDescription() {
16869 return "Reports test results in an XML format that looks like Ant's junitreport target";
16870 }
16871
16872 void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
16873
16874 void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
16875 CumulativeReporterBase::testRunStarting( runInfo );
16876 xml.startElement( "testsuites" );
16877 }
16878
16879 void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
16880 suiteTimer.start();
16881 stdOutForSuite.clear();
16882 stdErrForSuite.clear();
16883 unexpectedExceptions = 0;
16884 CumulativeReporterBase::testGroupStarting( groupInfo );
16885 }
16886
16887 void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
16888 m_okToFail = testCaseInfo.okToFail();
16889 }
16890
16891 bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
16892 if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
16893 unexpectedExceptions++;
16894 return CumulativeReporterBase::assertionEnded( assertionStats );
16895 }
16896
16897 void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
16898 stdOutForSuite += testCaseStats.stdOut;
16899 stdErrForSuite += testCaseStats.stdErr;
16900 CumulativeReporterBase::testCaseEnded( testCaseStats );
16901 }
16902
16903 void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
16904 double suiteTime = suiteTimer.getElapsedSeconds();
16905 CumulativeReporterBase::testGroupEnded( testGroupStats );
16906 writeGroup( *m_testGroups.back(), suiteTime );
16907 }
16908
16909 void JunitReporter::testRunEndedCumulative() {
16910 xml.endElement();
16911 }
16912
16913 void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
16914 XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
16915
16916 TestGroupStats const& stats = groupNode.value;
16917 xml.writeAttribute( "name", stats.groupInfo.name );
16918 xml.writeAttribute( "errors", unexpectedExceptions );
16919 xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
16920 xml.writeAttribute( "tests", stats.totals.assertions.total() );
16921 xml.writeAttribute( "hostname", "tbd" ); // !TBD
16922 if( m_config->showDurations() == ShowDurations::Never )
16923 xml.writeAttribute( "time", "" );
16924 else
16925 xml.writeAttribute( "time", formatDuration( suiteTime ) );
16926 xml.writeAttribute( "timestamp", getCurrentTimestamp() );
16927
16928 // Write properties if there are any
16929 if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
16930 auto properties = xml.scopedElement("properties");
16931 if (m_config->hasTestFilters()) {
16932 xml.scopedElement("property")
16933 .writeAttribute("name", "filters")
16934 .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
16935 }
16936 if (m_config->rngSeed() != 0) {
16937 xml.scopedElement("property")
16938 .writeAttribute("name", "random-seed")
16939 .writeAttribute("value", m_config->rngSeed());
16940 }
16941 }
16942
16943 // Write test cases
16944 for( auto const& child : groupNode.children )
16945 writeTestCase( *child );
16946
16947 xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), XmlFormatting::Newline );
16948 xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), XmlFormatting::Newline );
16949 }
16950
16951 void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
16952 TestCaseStats const& stats = testCaseNode.value;
16953
16954 // All test cases have exactly one section - which represents the
16955 // test case itself. That section may have 0-n nested sections
16956 assert( testCaseNode.children.size() == 1 );
16957 SectionNode const& rootSection = *testCaseNode.children.front();
16958
16959 std::string className = stats.testInfo.className;
16960
16961 if( className.empty() ) {
16962 className = fileNameTag(stats.testInfo.tags);
16963 if ( className.empty() )
16964 className = "global";
16965 }
16966
16967 if ( !m_config->name().empty() )
16968 className = m_config->name() + "." + className;
16969
16970 writeSection( className, "", rootSection, stats.testInfo.okToFail() );
16971 }
16972
16973 void JunitReporter::writeSection( std::string const& className,
16974 std::string const& rootName,
16975 SectionNode const& sectionNode,
16976 bool testOkToFail) {
16977 std::string name = trim( sectionNode.stats.sectionInfo.name );
16978 if( !rootName.empty() )
16979 name = rootName + '/' + name;
16980
16981 if( !sectionNode.assertions.empty() ||
16982 !sectionNode.stdOut.empty() ||
16983 !sectionNode.stdErr.empty() ) {
16984 XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
16985 if( className.empty() ) {
16986 xml.writeAttribute( "classname", name );
16987 xml.writeAttribute( "name", "root" );
16988 }
16989 else {
16990 xml.writeAttribute( "classname", className );
16991 xml.writeAttribute( "name", name );
16992 }
16993 xml.writeAttribute( "time", formatDuration( sectionNode.stats.durationInSeconds ) );
16994 // This is not ideal, but it should be enough to mimic gtest's
16995 // junit output.
16996 // Ideally the JUnit reporter would also handle `skipTest`
16997 // events and write those out appropriately.
16998 xml.writeAttribute( "status", "run" );
16999
17000 if (sectionNode.stats.assertions.failedButOk) {
17001 xml.scopedElement("skipped")
17002 .writeAttribute("message", "TEST_CASE tagged with !mayfail");
17003 }
17004
17005 writeAssertions( sectionNode );
17006
17007 if( !sectionNode.stdOut.empty() )
17008 xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), XmlFormatting::Newline );
17009 if( !sectionNode.stdErr.empty() )
17010 xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), XmlFormatting::Newline );
17011 }
17012 for( auto const& childNode : sectionNode.childSections )
17013 if( className.empty() )
17014 writeSection( name, "", *childNode, testOkToFail );
17015 else
17016 writeSection( className, name, *childNode, testOkToFail );
17017 }
17018
17019 void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
17020 for( auto const& assertion : sectionNode.assertions )
17021 writeAssertion( assertion );
17022 }
17023
17024 void JunitReporter::writeAssertion( AssertionStats const& stats ) {
17025 AssertionResult const& result = stats.assertionResult;
17026 if( !result.isOk() ) {
17027 std::string elementName;
17028 switch( result.getResultType() ) {
17029 case ResultWas::ThrewException:
17030 case ResultWas::FatalErrorCondition:
17031 elementName = "error";
17032 break;
17033 case ResultWas::ExplicitFailure:
17034 case ResultWas::ExpressionFailed:
17035 case ResultWas::DidntThrowException:
17036 elementName = "failure";
17037 break;
17038
17039 // We should never see these here:
17040 case ResultWas::Info:
17041 case ResultWas::Warning:
17042 case ResultWas::Ok:
17043 case ResultWas::Unknown:
17044 case ResultWas::FailureBit:
17045 case ResultWas::Exception:
17046 elementName = "internalError";
17047 break;
17048 }
17049
17050 XmlWriter::ScopedElement e = xml.scopedElement( elementName );
17051
17052 xml.writeAttribute( "message", result.getExpression() );
17053 xml.writeAttribute( "type", result.getTestMacroName() );
17054
17055 ReusableStringStream rss;
17056 if (stats.totals.assertions.total() > 0) {
17057 rss << "FAILED" << ":\n";
17058 if (result.hasExpression()) {
17059 rss << " ";
17060 rss << result.getExpressionInMacro();
17061 rss << '\n';
17062 }
17063 if (result.hasExpandedExpression()) {
17064 rss << "with expansion:\n";
17065 rss << Column(result.getExpandedExpression()).indent(2) << '\n';
17066 }
17067 } else {
17068 rss << '\n';
17069 }
17070
17071 if( !result.getMessage().empty() )
17072 rss << result.getMessage() << '\n';
17073 for( auto const& msg : stats.infoMessages )
17074 if( msg.type == ResultWas::Info )
17075 rss << msg.message << '\n';
17076
17077 rss << "at " << result.getSourceInfo();
17078 xml.writeText( rss.str(), XmlFormatting::Newline );
17079 }
17080 }
17081
17082 CATCH_REGISTER_REPORTER( "junit", JunitReporter )
17083
17084} // end namespace Catch
17085// end catch_reporter_junit.cpp
17086// start catch_reporter_listening.cpp
17087
17088#include <cassert>
17089
17090namespace Catch {
17091
17092 ListeningReporter::ListeningReporter() {
17093 // We will assume that listeners will always want all assertions
17094 m_preferences.shouldReportAllAssertions = true;
17095 }
17096
17097 void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
17098 m_listeners.push_back( std::move( listener ) );
17099 }
17100
17101 void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
17102 assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
17103 m_reporter = std::move( reporter );
17104 m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
17105 }
17106
17107 ReporterPreferences ListeningReporter::getPreferences() const {
17108 return m_preferences;
17109 }
17110
17111 std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
17112 return std::set<Verbosity>{ };
17113 }
17114
17115 void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
17116 for ( auto const& listener : m_listeners ) {
17117 listener->noMatchingTestCases( spec );
17118 }
17119 m_reporter->noMatchingTestCases( spec );
17120 }
17121
17122 void ListeningReporter::reportInvalidArguments(std::string const&arg){
17123 for ( auto const& listener : m_listeners ) {
17124 listener->reportInvalidArguments( arg );
17125 }
17126 m_reporter->reportInvalidArguments( arg );
17127 }
17128
17129#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17130 void ListeningReporter::benchmarkPreparing( std::string const& name ) {
17131 for (auto const& listener : m_listeners) {
17132 listener->benchmarkPreparing(name);
17133 }
17134 m_reporter->benchmarkPreparing(name);
17135 }
17136 void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
17137 for ( auto const& listener : m_listeners ) {
17138 listener->benchmarkStarting( benchmarkInfo );
17139 }
17140 m_reporter->benchmarkStarting( benchmarkInfo );
17141 }
17142 void ListeningReporter::benchmarkEnded( BenchmarkStats<> const& benchmarkStats ) {
17143 for ( auto const& listener : m_listeners ) {
17144 listener->benchmarkEnded( benchmarkStats );
17145 }
17146 m_reporter->benchmarkEnded( benchmarkStats );
17147 }
17148
17149 void ListeningReporter::benchmarkFailed( std::string const& error ) {
17150 for (auto const& listener : m_listeners) {
17151 listener->benchmarkFailed(error);
17152 }
17153 m_reporter->benchmarkFailed(error);
17154 }
17155#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17156
17157 void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
17158 for ( auto const& listener : m_listeners ) {
17159 listener->testRunStarting( testRunInfo );
17160 }
17161 m_reporter->testRunStarting( testRunInfo );
17162 }
17163
17164 void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
17165 for ( auto const& listener : m_listeners ) {
17166 listener->testGroupStarting( groupInfo );
17167 }
17168 m_reporter->testGroupStarting( groupInfo );
17169 }
17170
17171 void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
17172 for ( auto const& listener : m_listeners ) {
17173 listener->testCaseStarting( testInfo );
17174 }
17175 m_reporter->testCaseStarting( testInfo );
17176 }
17177
17178 void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
17179 for ( auto const& listener : m_listeners ) {
17180 listener->sectionStarting( sectionInfo );
17181 }
17182 m_reporter->sectionStarting( sectionInfo );
17183 }
17184
17185 void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
17186 for ( auto const& listener : m_listeners ) {
17187 listener->assertionStarting( assertionInfo );
17188 }
17189 m_reporter->assertionStarting( assertionInfo );
17190 }
17191
17192 // The return value indicates if the messages buffer should be cleared:
17193 bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
17194 for( auto const& listener : m_listeners ) {
17195 static_cast<void>( listener->assertionEnded( assertionStats ) );
17196 }
17197 return m_reporter->assertionEnded( assertionStats );
17198 }
17199
17200 void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
17201 for ( auto const& listener : m_listeners ) {
17202 listener->sectionEnded( sectionStats );
17203 }
17204 m_reporter->sectionEnded( sectionStats );
17205 }
17206
17207 void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
17208 for ( auto const& listener : m_listeners ) {
17209 listener->testCaseEnded( testCaseStats );
17210 }
17211 m_reporter->testCaseEnded( testCaseStats );
17212 }
17213
17214 void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
17215 for ( auto const& listener : m_listeners ) {
17216 listener->testGroupEnded( testGroupStats );
17217 }
17218 m_reporter->testGroupEnded( testGroupStats );
17219 }
17220
17221 void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
17222 for ( auto const& listener : m_listeners ) {
17223 listener->testRunEnded( testRunStats );
17224 }
17225 m_reporter->testRunEnded( testRunStats );
17226 }
17227
17228 void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
17229 for ( auto const& listener : m_listeners ) {
17230 listener->skipTest( testInfo );
17231 }
17232 m_reporter->skipTest( testInfo );
17233 }
17234
17235 bool ListeningReporter::isMulti() const {
17236 return true;
17237 }
17238
17239} // end namespace Catch
17240// end catch_reporter_listening.cpp
17241// start catch_reporter_xml.cpp
17242
17243#if defined(_MSC_VER)
17244#pragma warning(push)
17245#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
17246 // Note that 4062 (not all labels are handled
17247 // and default is missing) is enabled
17248#endif
17249
17250namespace Catch {
17251 XmlReporter::XmlReporter( ReporterConfig const& _config )
17252 : StreamingReporterBase( _config ),
17253 m_xml(_config.stream())
17254 {
17255 m_reporterPrefs.shouldRedirectStdOut = true;
17256 m_reporterPrefs.shouldReportAllAssertions = true;
17257 }
17258
17259 XmlReporter::~XmlReporter() = default;
17260
17261 std::string XmlReporter::getDescription() {
17262 return "Reports test results as an XML document";
17263 }
17264
17265 std::string XmlReporter::getStylesheetRef() const {
17266 return std::string();
17267 }
17268
17269 void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
17270 m_xml
17271 .writeAttribute( "filename", sourceInfo.file )
17272 .writeAttribute( "line", sourceInfo.line );
17273 }
17274
17275 void XmlReporter::noMatchingTestCases( std::string const& s ) {
17276 StreamingReporterBase::noMatchingTestCases( s );
17277 }
17278
17279 void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
17280 StreamingReporterBase::testRunStarting( testInfo );
17281 std::string stylesheetRef = getStylesheetRef();
17282 if( !stylesheetRef.empty() )
17283 m_xml.writeStylesheetRef( stylesheetRef );
17284 m_xml.startElement( "Catch" );
17285 if( !m_config->name().empty() )
17286 m_xml.writeAttribute( "name", m_config->name() );
17287 if (m_config->testSpec().hasFilters())
17288 m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
17289 if( m_config->rngSeed() != 0 )
17290 m_xml.scopedElement( "Randomness" )
17291 .writeAttribute( "seed", m_config->rngSeed() );
17292 }
17293
17294 void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
17295 StreamingReporterBase::testGroupStarting( groupInfo );
17296 m_xml.startElement( "Group" )
17297 .writeAttribute( "name", groupInfo.name );
17298 }
17299
17300 void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
17301 StreamingReporterBase::testCaseStarting(testInfo);
17302 m_xml.startElement( "TestCase" )
17303 .writeAttribute( "name", trim( testInfo.name ) )
17304 .writeAttribute( "description", testInfo.description )
17305 .writeAttribute( "tags", testInfo.tagsAsString() );
17306
17307 writeSourceInfo( testInfo.lineInfo );
17308
17309 if ( m_config->showDurations() == ShowDurations::Always )
17310 m_testCaseTimer.start();
17311 m_xml.ensureTagClosed();
17312 }
17313
17314 void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
17315 StreamingReporterBase::sectionStarting( sectionInfo );
17316 if( m_sectionDepth++ > 0 ) {
17317 m_xml.startElement( "Section" )
17318 .writeAttribute( "name", trim( sectionInfo.name ) );
17319 writeSourceInfo( sectionInfo.lineInfo );
17320 m_xml.ensureTagClosed();
17321 }
17322 }
17323
17324 void XmlReporter::assertionStarting( AssertionInfo const& ) { }
17325
17326 bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
17327
17328 AssertionResult const& result = assertionStats.assertionResult;
17329
17330 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
17331
17332 if( includeResults || result.getResultType() == ResultWas::Warning ) {
17333 // Print any info messages in <Info> tags.
17334 for( auto const& msg : assertionStats.infoMessages ) {
17335 if( msg.type == ResultWas::Info && includeResults ) {
17336 m_xml.scopedElement( "Info" )
17337 .writeText( msg.message );
17338 } else if ( msg.type == ResultWas::Warning ) {
17339 m_xml.scopedElement( "Warning" )
17340 .writeText( msg.message );
17341 }
17342 }
17343 }
17344
17345 // Drop out if result was successful but we're not printing them.
17346 if( !includeResults && result.getResultType() != ResultWas::Warning )
17347 return true;
17348
17349 // Print the expression if there is one.
17350 if( result.hasExpression() ) {
17351 m_xml.startElement( "Expression" )
17352 .writeAttribute( "success", result.succeeded() )
17353 .writeAttribute( "type", result.getTestMacroName() );
17354
17355 writeSourceInfo( result.getSourceInfo() );
17356
17357 m_xml.scopedElement( "Original" )
17358 .writeText( result.getExpression() );
17359 m_xml.scopedElement( "Expanded" )
17360 .writeText( result.getExpandedExpression() );
17361 }
17362
17363 // And... Print a result applicable to each result type.
17364 switch( result.getResultType() ) {
17365 case ResultWas::ThrewException:
17366 m_xml.startElement( "Exception" );
17367 writeSourceInfo( result.getSourceInfo() );
17368 m_xml.writeText( result.getMessage() );
17369 m_xml.endElement();
17370 break;
17371 case ResultWas::FatalErrorCondition:
17372 m_xml.startElement( "FatalErrorCondition" );
17373 writeSourceInfo( result.getSourceInfo() );
17374 m_xml.writeText( result.getMessage() );
17375 m_xml.endElement();
17376 break;
17377 case ResultWas::Info:
17378 m_xml.scopedElement( "Info" )
17379 .writeText( result.getMessage() );
17380 break;
17381 case ResultWas::Warning:
17382 // Warning will already have been written
17383 break;
17384 case ResultWas::ExplicitFailure:
17385 m_xml.startElement( "Failure" );
17386 writeSourceInfo( result.getSourceInfo() );
17387 m_xml.writeText( result.getMessage() );
17388 m_xml.endElement();
17389 break;
17390 default:
17391 break;
17392 }
17393
17394 if( result.hasExpression() )
17395 m_xml.endElement();
17396
17397 return true;
17398 }
17399
17400 void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
17401 StreamingReporterBase::sectionEnded( sectionStats );
17402 if( --m_sectionDepth > 0 ) {
17403 XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
17404 e.writeAttribute( "successes", sectionStats.assertions.passed );
17405 e.writeAttribute( "failures", sectionStats.assertions.failed );
17406 e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
17407
17408 if ( m_config->showDurations() == ShowDurations::Always )
17409 e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
17410
17411 m_xml.endElement();
17412 }
17413 }
17414
17415 void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
17416 StreamingReporterBase::testCaseEnded( testCaseStats );
17417 XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
17418 e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
17419
17420 if ( m_config->showDurations() == ShowDurations::Always )
17421 e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
17422
17423 if( !testCaseStats.stdOut.empty() )
17424 m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), XmlFormatting::Newline );
17425 if( !testCaseStats.stdErr.empty() )
17426 m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), XmlFormatting::Newline );
17427
17428 m_xml.endElement();
17429 }
17430
17431 void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
17432 StreamingReporterBase::testGroupEnded( testGroupStats );
17433 // TODO: Check testGroupStats.aborting and act accordingly.
17434 m_xml.scopedElement( "OverallResults" )
17435 .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
17436 .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
17437 .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
17438 m_xml.scopedElement( "OverallResultsCases")
17439 .writeAttribute( "successes", testGroupStats.totals.testCases.passed )
17440 .writeAttribute( "failures", testGroupStats.totals.testCases.failed )
17441 .writeAttribute( "expectedFailures", testGroupStats.totals.testCases.failedButOk );
17442 m_xml.endElement();
17443 }
17444
17445 void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
17446 StreamingReporterBase::testRunEnded( testRunStats );
17447 m_xml.scopedElement( "OverallResults" )
17448 .writeAttribute( "successes", testRunStats.totals.assertions.passed )
17449 .writeAttribute( "failures", testRunStats.totals.assertions.failed )
17450 .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
17451 m_xml.scopedElement( "OverallResultsCases")
17452 .writeAttribute( "successes", testRunStats.totals.testCases.passed )
17453 .writeAttribute( "failures", testRunStats.totals.testCases.failed )
17454 .writeAttribute( "expectedFailures", testRunStats.totals.testCases.failedButOk );
17455 m_xml.endElement();
17456 }
17457
17458#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17459 void XmlReporter::benchmarkPreparing(std::string const& name) {
17460 m_xml.startElement("BenchmarkResults")
17461 .writeAttribute("name", name);
17462 }
17463
17464 void XmlReporter::benchmarkStarting(BenchmarkInfo const &info) {
17465 m_xml.writeAttribute("samples", info.samples)
17466 .writeAttribute("resamples", info.resamples)
17467 .writeAttribute("iterations", info.iterations)
17468 .writeAttribute("clockResolution", info.clockResolution)
17469 .writeAttribute("estimatedDuration", info.estimatedDuration)
17470 .writeComment("All values in nano seconds");
17471 }
17472
17473 void XmlReporter::benchmarkEnded(BenchmarkStats<> const& benchmarkStats) {
17474 m_xml.startElement("mean")
17475 .writeAttribute("value", benchmarkStats.mean.point.count())
17476 .writeAttribute("lowerBound", benchmarkStats.mean.lower_bound.count())
17477 .writeAttribute("upperBound", benchmarkStats.mean.upper_bound.count())
17478 .writeAttribute("ci", benchmarkStats.mean.confidence_interval);
17479 m_xml.endElement();
17480 m_xml.startElement("standardDeviation")
17481 .writeAttribute("value", benchmarkStats.standardDeviation.point.count())
17482 .writeAttribute("lowerBound", benchmarkStats.standardDeviation.lower_bound.count())
17483 .writeAttribute("upperBound", benchmarkStats.standardDeviation.upper_bound.count())
17484 .writeAttribute("ci", benchmarkStats.standardDeviation.confidence_interval);
17485 m_xml.endElement();
17486 m_xml.startElement("outliers")
17487 .writeAttribute("variance", benchmarkStats.outlierVariance)
17488 .writeAttribute("lowMild", benchmarkStats.outliers.low_mild)
17489 .writeAttribute("lowSevere", benchmarkStats.outliers.low_severe)
17490 .writeAttribute("highMild", benchmarkStats.outliers.high_mild)
17491 .writeAttribute("highSevere", benchmarkStats.outliers.high_severe);
17492 m_xml.endElement();
17493 m_xml.endElement();
17494 }
17495
17496 void XmlReporter::benchmarkFailed(std::string const &error) {
17497 m_xml.scopedElement("failed").
17498 writeAttribute("message", error);
17499 m_xml.endElement();
17500 }
17501#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17502
17503 CATCH_REGISTER_REPORTER( "xml", XmlReporter )
17504
17505} // end namespace Catch
17506
17507#if defined(_MSC_VER)
17508#pragma warning(pop)
17509#endif
17510// end catch_reporter_xml.cpp
17511
17512namespace Catch {
17513 LeakDetector leakDetector;
17514}
17515
17516#ifdef __clang__
17517#pragma clang diagnostic pop
17518#endif
17519
17520// end catch_impl.hpp
17521#endif
17522
17523#ifdef CATCH_CONFIG_MAIN
17524// start catch_default_main.hpp
17525
17526#ifndef __OBJC__
17527
17528#ifndef CATCH_INTERNAL_CDECL
17529#ifdef _MSC_VER
17530#define CATCH_INTERNAL_CDECL __cdecl
17531#else
17532#define CATCH_INTERNAL_CDECL
17533#endif
17534#endif
17535
17536#if defined(CATCH_CONFIG_WCHAR) && defined(CATCH_PLATFORM_WINDOWS) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
17537// Standard C/C++ Win32 Unicode wmain entry point
17538extern "C" int CATCH_INTERNAL_CDECL wmain (int argc, wchar_t * argv[], wchar_t * []) {
17539#else
17540// Standard C/C++ main entry point
17541int CATCH_INTERNAL_CDECL main (int argc, char * argv[]) {
17542#endif
17543
17544 return Catch::Session().run( argc, argv );
17545}
17546
17547#else // __OBJC__
17548
17549// Objective-C entry point
17550int main (int argc, char * const argv[]) {
17551#if !CATCH_ARC_ENABLED
17552 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
17553#endif
17554
17555 Catch::registerTestMethods();
17556 int result = Catch::Session().run( argc, (char**)argv );
17557
17558#if !CATCH_ARC_ENABLED
17559 [pool drain];
17560#endif
17561
17562 return result;
17563}
17564
17565#endif // __OBJC__
17566
17567// end catch_default_main.hpp
17568#endif
17569
17570#if !defined(CATCH_CONFIG_IMPL_ONLY)
17571
17572#ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
17573# undef CLARA_CONFIG_MAIN
17574#endif
17575
17576#if !defined(CATCH_CONFIG_DISABLE)
17578// If this config identifier is defined then all CATCH macros are prefixed with CATCH_
17579#ifdef CATCH_CONFIG_PREFIX_ALL
17580
17581#define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17582#define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17583
17584#define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17585#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
17586#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
17587#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17588#define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
17589#endif// CATCH_CONFIG_DISABLE_MATCHERS
17590#define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17591
17592#define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17593#define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17594#define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17595#define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17596#define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
17597
17598#define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17599#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
17600#define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17601#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17602#define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17603#endif // CATCH_CONFIG_DISABLE_MATCHERS
17604#define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17605
17606#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17607#define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
17608
17609#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
17610#endif // CATCH_CONFIG_DISABLE_MATCHERS
17611
17612#define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
17613#define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
17614#define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
17615#define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
17616
17617#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
17618#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
17619#define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
17620#define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
17621#define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
17622#define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
17623#define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
17624#define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17625#define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17626
17627#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17628
17629#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17630#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17631#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
17632#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17633#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17634#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
17635#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
17636#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
17637#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17638#else
17639#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
17640#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
17641#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17642#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17643#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
17644#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
17645#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17646#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17647#endif
17648
17649#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17650#define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
17651#define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
17652#else
17653#define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
17654#define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
17655#endif
17656
17657// "BDD-style" convenience wrappers
17658#define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
17659#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
17660#define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
17661#define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
17662#define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
17663#define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
17664#define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
17665#define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
17666
17667#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17668#define CATCH_BENCHMARK(...) \
17669 INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
17670#define CATCH_BENCHMARK_ADVANCED(name) \
17671 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), name)
17672#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17673
17674// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
17675#else
17676
17677#define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17678#define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17679
17680#define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17681#define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
17682#define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
17683#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17684#define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
17685#endif // CATCH_CONFIG_DISABLE_MATCHERS
17686#define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
17687
17688#define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17689#define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
17690#define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17691#define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17692#define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
17693
17694#define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17695#define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
17696#define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17697#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17698#define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
17699#endif // CATCH_CONFIG_DISABLE_MATCHERS
17700#define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17701
17702#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17703#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
17704
17705#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
17706#endif // CATCH_CONFIG_DISABLE_MATCHERS
17707
17708#define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
17709#define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
17710#define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
17711#define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
17712
17713#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
17714#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
17715#define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
17716#define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
17717#define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
17718#define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
17719#define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
17720#define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17721#define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
17722#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
17723
17724#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17725#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17726#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
17727#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17728#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17729#define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
17730#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
17731#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
17732#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
17733#define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE(__VA_ARGS__)
17734#define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ )
17735#else
17736#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
17737#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
17738#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17739#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17740#define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
17741#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
17742#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17743#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
17744#define TEMPLATE_LIST_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE( __VA_ARGS__ ) )
17745#define TEMPLATE_LIST_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_LIST_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
17746#endif
17747
17748#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
17749#define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
17750#define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
17751#else
17752#define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
17753#define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
17754#endif
17755
17756#endif
17757
17758#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
17759
17760// "BDD-style" convenience wrappers
17761#define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
17762#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
17763
17764#define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
17765#define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
17766#define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
17767#define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
17768#define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
17769#define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
17770
17771#if defined(CATCH_CONFIG_ENABLE_BENCHMARKING)
17772#define BENCHMARK(...) \
17773 INTERNAL_CATCH_BENCHMARK(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), INTERNAL_CATCH_GET_1_ARG(__VA_ARGS__,,), INTERNAL_CATCH_GET_2_ARG(__VA_ARGS__,,))
17774#define BENCHMARK_ADVANCED(name) \
17775 INTERNAL_CATCH_BENCHMARK_ADVANCED(INTERNAL_CATCH_UNIQUE_NAME(C_A_T_C_H_B_E_N_C_H_), name)
17776#endif // CATCH_CONFIG_ENABLE_BENCHMARKING
17777
17779
17780#else // CATCH_CONFIG_DISABLE
17781
17783// If this config identifier is defined then all CATCH macros are prefixed with CATCH_
17784#ifdef CATCH_CONFIG_PREFIX_ALL
17785
17786#define CATCH_REQUIRE( ... ) (void)(0)
17787#define CATCH_REQUIRE_FALSE( ... ) (void)(0)
17788
17789#define CATCH_REQUIRE_THROWS( ... ) (void)(0)
17790#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
17791#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
17792#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17793#define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17794#endif// CATCH_CONFIG_DISABLE_MATCHERS
17795#define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
17796
17797#define CATCH_CHECK( ... ) (void)(0)
17798#define CATCH_CHECK_FALSE( ... ) (void)(0)
17799#define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
17800#define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
17801#define CATCH_CHECK_NOFAIL( ... ) (void)(0)
17802
17803#define CATCH_CHECK_THROWS( ... ) (void)(0)
17804#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
17805#define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
17806#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17807#define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17808#endif // CATCH_CONFIG_DISABLE_MATCHERS
17809#define CATCH_CHECK_NOTHROW( ... ) (void)(0)
17810
17811#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17812#define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
17813
17814#define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
17815#endif // CATCH_CONFIG_DISABLE_MATCHERS
17816
17817#define CATCH_INFO( msg ) (void)(0)
17818#define CATCH_UNSCOPED_INFO( msg ) (void)(0)
17819#define CATCH_WARN( msg ) (void)(0)
17820#define CATCH_CAPTURE( msg ) (void)(0)
17821
17822#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
17823#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
17824#define CATCH_METHOD_AS_TEST_CASE( method, ... )
17825#define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
17826#define CATCH_SECTION( ... )
17827#define CATCH_DYNAMIC_SECTION( ... )
17828#define CATCH_FAIL( ... ) (void)(0)
17829#define CATCH_FAIL_CHECK( ... ) (void)(0)
17830#define CATCH_SUCCEED( ... ) (void)(0)
17831
17832#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
17833
17834#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17835#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
17836#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
17837#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
17838#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
17839#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17840#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17841#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17842#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17843#else
17844#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
17845#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
17846#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
17847#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
17848#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17849#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
17850#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17851#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17852#endif
17853
17854// "BDD-style" convenience wrappers
17855#define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
17856#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), className )
17857#define CATCH_GIVEN( desc )
17858#define CATCH_AND_GIVEN( desc )
17859#define CATCH_WHEN( desc )
17860#define CATCH_AND_WHEN( desc )
17861#define CATCH_THEN( desc )
17862#define CATCH_AND_THEN( desc )
17863
17864#define CATCH_STATIC_REQUIRE( ... ) (void)(0)
17865#define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
17866
17867// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
17868#else
17869
17870#define REQUIRE( ... ) (void)(0)
17871#define REQUIRE_FALSE( ... ) (void)(0)
17872
17873#define REQUIRE_THROWS( ... ) (void)(0)
17874#define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
17875#define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
17876#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17877#define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17878#endif // CATCH_CONFIG_DISABLE_MATCHERS
17879#define REQUIRE_NOTHROW( ... ) (void)(0)
17880
17881#define CHECK( ... ) (void)(0)
17882#define CHECK_FALSE( ... ) (void)(0)
17883#define CHECKED_IF( ... ) if (__VA_ARGS__)
17884#define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
17885#define CHECK_NOFAIL( ... ) (void)(0)
17886
17887#define CHECK_THROWS( ... ) (void)(0)
17888#define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
17889#define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
17890#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17891#define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
17892#endif // CATCH_CONFIG_DISABLE_MATCHERS
17893#define CHECK_NOTHROW( ... ) (void)(0)
17894
17895#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
17896#define CHECK_THAT( arg, matcher ) (void)(0)
17897
17898#define REQUIRE_THAT( arg, matcher ) (void)(0)
17899#endif // CATCH_CONFIG_DISABLE_MATCHERS
17900
17901#define INFO( msg ) (void)(0)
17902#define UNSCOPED_INFO( msg ) (void)(0)
17903#define WARN( msg ) (void)(0)
17904#define CAPTURE( ... ) (void)(0)
17905
17906#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
17907#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
17908#define METHOD_AS_TEST_CASE( method, ... )
17909#define REGISTER_TEST_CASE( Function, ... ) (void)(0)
17910#define SECTION( ... )
17911#define DYNAMIC_SECTION( ... )
17912#define FAIL( ... ) (void)(0)
17913#define FAIL_CHECK( ... ) (void)(0)
17914#define SUCCEED( ... ) (void)(0)
17915#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ))
17916
17917#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
17918#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
17919#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
17920#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
17921#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
17922#define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17923#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17924#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17925#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17926#else
17927#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
17928#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
17929#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
17930#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
17931#define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17932#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
17933#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17934#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
17935#endif
17936
17937#define STATIC_REQUIRE( ... ) (void)(0)
17938#define STATIC_REQUIRE_FALSE( ... ) (void)(0)
17939
17940#endif
17941
17942#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
17943
17944// "BDD-style" convenience wrappers
17945#define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ) )
17946#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( C_A_T_C_H_T_E_S_T_ ), className )
17947
17948#define GIVEN( desc )
17949#define AND_GIVEN( desc )
17950#define WHEN( desc )
17951#define AND_WHEN( desc )
17952#define THEN( desc )
17953#define AND_THEN( desc )
17954
17956
17957#endif
17958
17959#endif // ! CATCH_CONFIG_IMPL_ONLY
17960
17961// start catch_reenable_warnings.h
17962
17963
17964#ifdef __clang__
17965# ifdef __ICC // icpc defines the __clang__ macro
17966# pragma warning(pop)
17967# else
17968# pragma clang diagnostic pop
17969# endif
17970#elif defined __GNUC__
17971# pragma GCC diagnostic pop
17972#endif
17973
17974// end catch_reenable_warnings.h
17975// end catch.hpp
17976#endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
17977
std::ostream & operator<<(std::ostream &out, const CellType celltype)
Allow Standard c++ streams to print out our enum values as text.
Definition: Cell.cpp:2038
std::vector< Item > Children(const Item &item)
The parts of an item, in reading order; empty if it has none.
Definition: OutputNavigation.cpp:254
@ Help
The "Help" button.
@ count
Not a check: the number of checks.
@ warning
Works, but not fully: some feature won't.
@ info
Not a problem, but worth knowing (e.g.
Definition: diagrams_c.h:5
Definition: catch.hpp:2549
Definition: catch.hpp:2225
Definition: catch.hpp:2653
Definition: catch.hpp:3079
Definition: catch.hpp:1565
Definition: catch.hpp:3022
Definition: catch.hpp:2339
Definition: catch.hpp:3920
Definition: catch.hpp:4298
Definition: catch.hpp:4157
Definition: catch.hpp:3968
Definition: catch.hpp:3846
Definition: catch.hpp:3987
Definition: catch.hpp:4011
Definition: catch.hpp:4713
Definition: catch.hpp:4257
Definition: catch.hpp:4668
Definition: catch.hpp:4201
Definition: catch.hpp:3954
Definition: catch.hpp:4121
Definition: catch.hpp:2527
Definition: catch.hpp:3771
Definition: catch.hpp:491
Definition: catch.hpp:4410
Definition: catch.hpp:1441
Definition: catch.hpp:2642
Definition: catch.hpp:2912
Definition: catch.hpp:4559
A non-owning string class (similar to the forthcoming std::string_view) Note that,...
Definition: catch.hpp:606
Definition: catch.hpp:4808
Definition: catch.hpp:963
Definition: catch.hpp:2895
Definition: catch.hpp:2301
Definition: diagrams_e.h:4
A class that is inherited from the external class Test.
Definition: tag.cpp:5
void func()
function in group 1
Definition: group.cpp:13
detail namespace with internal helper functions
Definition: json.hpp:249
@ object
object (unordered set of name/value pairs)
@ string
string value
std::size_t hash(const BasicJsonType &j)
hash a JSON value
Definition: json.hpp:6022
StringType escape(StringType s)
string escaping as described in RFC 6901 (Sect.
Definition: json.hpp:2990
Coord add(Coord c1, Coord c2)
This function returns the addition of c1 and c2, i.e: (c1.x+c2.x,c1.y+c2.y)
Definition: restypedef.cpp:23
Definition: catch.hpp:1398
Definition: catch.hpp:2544
Definition: catch.hpp:987
Definition: catch.hpp:486
Definition: catch.hpp:2830
Definition: catch.hpp:2415
Definition: catch.hpp:1467
Definition: catch.hpp:3942
Definition: catch.hpp:4061
Definition: catch.hpp:4513
Definition: catch.hpp:4360
Definition: catch.hpp:3016
Definition: catch.hpp:3011
Definition: catch.hpp:3860
Definition: catch.hpp:4369
Definition: catch.hpp:1477
Definition: catch.hpp:2977
Definition: catch.hpp:2966
Definition: catch.hpp:2459
Definition: catch.hpp:4841
Definition: catch.hpp:1434
Definition: catch.hpp:580
Definition: catch.hpp:572
Definition: catch.hpp:2203
Definition: catch.hpp:3289
Definition: catch.hpp:3322
Definition: catch.hpp:3357
Definition: catch.hpp:3281
Definition: catch.hpp:3263
Definition: catch.hpp:3540
Definition: catch.hpp:3682
Definition: catch.hpp:3659
Definition: catch.hpp:2628
Definition: catch.hpp:2600
Definition: catch.hpp:2617
Definition: catch.hpp:981
Definition: catch.hpp:549
Definition: catch.hpp:1378
Definition: catch.hpp:1354
Definition: catch.hpp:4494
Definition: catch.hpp:2877
Definition: catch.hpp:2861
Definition: catch.hpp:4489
Definition: catch.hpp:502
Definition: catch.hpp:534
Definition: catch.hpp:1616
Definition: catch.hpp:4773
Definition: catch.hpp:2522
Definition: catch.hpp:2843
Definition: catch.hpp:4499
Definition: catch.hpp:4504
Definition: catch.hpp:4483
Definition: catch.hpp:926
Definition: catch.hpp:1999
Definition: catch.hpp:1994
Definition: catch.hpp:929
Definition: catch.hpp:937
Definition: catch.hpp:2008
Definition: catch.hpp:3217
Definition: catch.hpp:928
Definition: catch.hpp:481
int open(const char *, int)
Opens a file descriptor.
int errno
Contains the last error code.
Definition: structcmd.h:53
int close(int)
Closes the file descriptor fd.
size_t write(int, const char *, size_t)
Writes count bytes from buf to the filedescriptor fd.