spdlog
Loading...
Searching...
No Matches
catch.hpp
Go to the documentation of this file.
1/*
2 * Catch v2.8.0
3 * Generated: 2019-05-26 21:29:22.235281
4 * ----------------------------------------------------------
5 * This file has been merged from multiple headers. Please don't edit it directly
6 * Copyright (c) 2019 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 8
18#define CATCH_VERSION_PATCH 0
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#ifdef __APPLE__
70# include <TargetConditionals.h>
71# if TARGET_OS_OSX == 1
72# define CATCH_PLATFORM_MAC
73# elif TARGET_OS_IPHONE == 1
74# define CATCH_PLATFORM_IPHONE
75# endif
76
77#elif defined(linux) || defined(__linux) || defined(__linux__)
78# define CATCH_PLATFORM_LINUX
79
80#elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
81# define CATCH_PLATFORM_WINDOWS
82#endif
83
84// end catch_platform.h
85
86#ifdef CATCH_IMPL
87# ifndef CLARA_CONFIG_MAIN
88# define CLARA_CONFIG_MAIN_NOT_DEFINED
89# define CLARA_CONFIG_MAIN
90# endif
91#endif
92
93// start catch_user_interfaces.h
94
95namespace Catch {
96 unsigned int rngSeed();
97}
98
99// end catch_user_interfaces.h
100// start catch_tag_alias_autoregistrar.h
101
102// start catch_common.h
103
104// start catch_compiler_capabilities.h
105
106// Detect a number of compiler features - by compiler
107// The following features are defined:
108//
109// CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
110// CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
111// CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
112// CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
113// ****************
114// Note to maintainers: if new toggles are added please document them
115// in configuration.md, too
116// ****************
117
118// In general each macro has a _NO_<feature name> form
119// (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
120// Many features, at point of detection, define an _INTERNAL_ macro, so they
121// can be combined, en-mass, with the _NO_ forms later.
122
123#ifdef __cplusplus
124
125# if (__cplusplus >= 201402L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
126# define CATCH_CPP14_OR_GREATER
127# endif
128
129# if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
130# define CATCH_CPP17_OR_GREATER
131# endif
132
133#endif
134
135#if defined(CATCH_CPP17_OR_GREATER)
136# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
137#endif
138
139#ifdef __clang__
140
141# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
142 _Pragma( "clang diagnostic push" ) \
143 _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
144 _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
145# define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
146 _Pragma( "clang diagnostic pop" )
147
148# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
149 _Pragma( "clang diagnostic push" ) \
150 _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
151# define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
152 _Pragma( "clang diagnostic pop" )
153
154# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
155 _Pragma( "clang diagnostic push" ) \
156 _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
157# define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS \
158 _Pragma( "clang diagnostic pop" )
159
160# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
161 _Pragma( "clang diagnostic push" ) \
162 _Pragma( "clang diagnostic ignored \"-Wgnu-zero-variadic-macro-arguments\"" )
163# define CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
164 _Pragma( "clang diagnostic pop" )
165
166#endif // __clang__
167
168////////////////////////////////////////////////////////////////////////////////
169// Assume that non-Windows platforms support posix signals by default
170#if !defined(CATCH_PLATFORM_WINDOWS)
171 #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
172#endif
173
174////////////////////////////////////////////////////////////////////////////////
175// We know some environments not to support full POSIX signals
176#if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
177 #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
178#endif
179
180#ifdef __OS400__
181# define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
182# define CATCH_CONFIG_COLOUR_NONE
183#endif
184
185////////////////////////////////////////////////////////////////////////////////
186// Android somehow still does not support std::to_string
187#if defined(__ANDROID__)
188# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
189#endif
190
191////////////////////////////////////////////////////////////////////////////////
192// Not all Windows environments support SEH properly
193#if defined(__MINGW32__)
194# define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
195#endif
196
197////////////////////////////////////////////////////////////////////////////////
198// PS4
199#if defined(__ORBIS__)
200# define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
201#endif
202
203////////////////////////////////////////////////////////////////////////////////
204// Cygwin
205#ifdef __CYGWIN__
206
207// Required for some versions of Cygwin to declare gettimeofday
208// see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
209# define _BSD_SOURCE
210// some versions of cygwin (most) do not support std::to_string. Use the libstd check.
211// https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
212# if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
213 && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
214
215# define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
216
217# endif
218#endif // __CYGWIN__
219
220////////////////////////////////////////////////////////////////////////////////
221// Visual C++
222#ifdef _MSC_VER
223
224# if _MSC_VER >= 1900 // Visual Studio 2015 or newer
225# define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
226# endif
227
228// Universal Windows platform does not support SEH
229// Or console colours (or console at all...)
230# if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
231# define CATCH_CONFIG_COLOUR_NONE
232# else
233# define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
234# endif
235
236// MSVC traditional preprocessor needs some workaround for __VA_ARGS__
237// _MSVC_TRADITIONAL == 0 means new conformant preprocessor
238// _MSVC_TRADITIONAL == 1 means old traditional non-conformant preprocessor
239# if !defined(_MSVC_TRADITIONAL) || (defined(_MSVC_TRADITIONAL) && _MSVC_TRADITIONAL)
240# define CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
241# endif
242
243#endif // _MSC_VER
244
245////////////////////////////////////////////////////////////////////////////////
246// Check if we are compiled with -fno-exceptions or equivalent
247#if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
248# define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
249#endif
250
251////////////////////////////////////////////////////////////////////////////////
252// DJGPP
253#ifdef __DJGPP__
254# define CATCH_INTERNAL_CONFIG_NO_WCHAR
255#endif // __DJGPP__
256
257////////////////////////////////////////////////////////////////////////////////
258// Embarcadero C++Build
259#if defined(__BORLANDC__)
260 #define CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN
261#endif
262
263////////////////////////////////////////////////////////////////////////////////
264
265// Use of __COUNTER__ is suppressed during code analysis in
266// CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
267// handled by it.
268// Otherwise all supported compilers support COUNTER macro,
269// but user still might want to turn it off
270#if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
271 #define CATCH_INTERNAL_CONFIG_COUNTER
272#endif
273
274////////////////////////////////////////////////////////////////////////////////
275// Check if string_view is available and usable
276// The check is split apart to work around v140 (VS2015) preprocessor issue...
277#if defined(__has_include)
278#if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
279# define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
280#endif
281#endif
282
283////////////////////////////////////////////////////////////////////////////////
284// Check if optional is available and usable
285#if defined(__has_include)
286# if __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
287# define CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL
288# endif // __has_include(<optional>) && defined(CATCH_CPP17_OR_GREATER)
289#endif // __has_include
290
291////////////////////////////////////////////////////////////////////////////////
292// Check if variant is available and usable
293#if defined(__has_include)
294# if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
295# if defined(__clang__) && (__clang_major__ < 8)
296 // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
297 // fix should be in clang 8, workaround in libstdc++ 8.2
298# include <ciso646>
299# if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
300# define CATCH_CONFIG_NO_CPP17_VARIANT
301# else
302# define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
303# endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
304# else
305# define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
306# endif // defined(__clang__) && (__clang_major__ < 8)
307# endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
308#endif // __has_include
309
310#if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
311# define CATCH_CONFIG_COUNTER
312#endif
313#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)
314# define CATCH_CONFIG_WINDOWS_SEH
315#endif
316// This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
317#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)
318# define CATCH_CONFIG_POSIX_SIGNALS
319#endif
320// This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
321#if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
322# define CATCH_CONFIG_WCHAR
323#endif
324
325#if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
326# define CATCH_CONFIG_CPP11_TO_STRING
327#endif
328
329#if defined(CATCH_INTERNAL_CONFIG_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_NO_CPP17_OPTIONAL) && !defined(CATCH_CONFIG_CPP17_OPTIONAL)
330# define CATCH_CONFIG_CPP17_OPTIONAL
331#endif
332
333#if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
334# define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
335#endif
336
337#if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
338# define CATCH_CONFIG_CPP17_STRING_VIEW
339#endif
340
341#if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
342# define CATCH_CONFIG_CPP17_VARIANT
343#endif
344
345#if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
346# define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
347#endif
348
349#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)
350# define CATCH_CONFIG_NEW_CAPTURE
351#endif
352
353#if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
354# define CATCH_CONFIG_DISABLE_EXCEPTIONS
355#endif
356
357#if defined(CATCH_INTERNAL_CONFIG_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_NO_POLYFILL_ISNAN) && !defined(CATCH_CONFIG_POLYFILL_ISNAN)
358# define CATCH_CONFIG_POLYFILL_ISNAN
359#endif
360
361#if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
362# define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
363# define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
364#endif
365#if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
366# define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
367# define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
368#endif
369#if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
370# define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
371# define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
372#endif
373#if !defined(CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS)
374# define CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS
375# define CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS
376#endif
377
378#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
379#define CATCH_TRY if ((true))
380#define CATCH_CATCH_ALL if ((false))
381#define CATCH_CATCH_ANON(type) if ((false))
382#else
383#define CATCH_TRY try
384#define CATCH_CATCH_ALL catch (...)
385#define CATCH_CATCH_ANON(type) catch (type)
386#endif
387
388#if defined(CATCH_INTERNAL_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_NO_TRADITIONAL_MSVC_PREPROCESSOR) && !defined(CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR)
389#define CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
390#endif
391
392// end catch_compiler_capabilities.h
393#define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
394#define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
395#ifdef CATCH_CONFIG_COUNTER
396# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
397#else
398# define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
399#endif
400
401#include <iosfwd>
402#include <string>
403#include <cstdint>
404
405// We need a dummy global operator<< so we can bring it into Catch namespace later
408
409namespace Catch {
410
411 struct CaseSensitive { enum Choice {
413 No
414 }; };
415
417 NonCopyable( NonCopyable const& ) = delete;
418 NonCopyable( NonCopyable && ) = delete;
421
422 protected:
424 virtual ~NonCopyable();
425 };
426
428
429 SourceLineInfo() = delete;
430 SourceLineInfo( char const* _file, std::size_t _line ) noexcept
431 : file( _file ),
432 line( _line )
433 {}
434
435 SourceLineInfo( SourceLineInfo const& other ) = default;
437 SourceLineInfo( SourceLineInfo&& ) noexcept = default;
438 SourceLineInfo& operator = ( SourceLineInfo&& ) noexcept = default;
439
440 bool empty() const noexcept;
441 bool operator == ( SourceLineInfo const& other ) const noexcept;
442 bool operator < ( SourceLineInfo const& other ) const noexcept;
443
444 char const* file;
445 std::size_t line;
446 };
447
448 std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
449
450 // Bring in operator<< from global namespace into Catch namespace
451 // This is necessary because the overload of operator<< above makes
452 // lookup stop at namespace Catch
453 using ::operator<<;
454
455 // Use this in variadic streaming macros to allow
456 // >> +StreamEndStop
457 // as well as
458 // >> stuff +StreamEndStop
461 };
462 template<typename T>
463 T const& operator + ( T const& value, StreamEndStop ) {
464 return value;
465 }
466}
467
468#define CATCH_INTERNAL_LINEINFO \
469 ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
470
471// end catch_common.h
472namespace Catch {
473
475 RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
476 };
477
478} // end namespace Catch
479
480#define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
481 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
482 namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
483 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
484
485// end catch_tag_alias_autoregistrar.h
486// start catch_test_registry.h
487
488// start catch_interfaces_testcase.h
489
490#include <vector>
491
492namespace Catch {
493
494 class TestSpec;
495
497 virtual void invoke () const = 0;
498 virtual ~ITestInvoker();
499 };
500
501 class TestCase;
502 struct IConfig;
503
506 virtual std::vector<TestCase> const& getAllTests() const = 0;
507 virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
508 };
509
510 bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
511 std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
513
514}
515
516// end catch_interfaces_testcase.h
517// start catch_stringref.h
518
519#include <cstddef>
520#include <string>
521#include <iosfwd>
522
523namespace Catch {
524
525 /// A non-owning string class (similar to the forthcoming std::string_view)
526 /// Note that, because a StringRef may be a substring of another string,
527 /// it may not be null terminated. c_str() must return a null terminated
528 /// string, however, and so the StringRef will internally take ownership
529 /// (taking a copy), if necessary. In theory this ownership is not externally
530 /// visible - but it does mean (substring) StringRefs should not be shared between
531 /// threads.
532 class StringRef {
533 public:
535
536 private:
537 friend struct StringRefTestAccess;
538
539 char const* m_start;
541
542 char* m_data = nullptr;
543
545
546 static constexpr char const* const s_empty = "";
547
548 public: // construction/ assignment
549 StringRef() noexcept
550 : StringRef( s_empty, 0 )
551 {}
552
553 StringRef( StringRef const& other ) noexcept
554 : m_start( other.m_start ),
555 m_size( other.m_size )
556 {}
557
558 StringRef( StringRef&& other ) noexcept
559 : m_start( other.m_start ),
560 m_size( other.m_size ),
561 m_data( other.m_data )
562 {
563 other.m_data = nullptr;
564 }
565
566 StringRef( char const* rawChars ) noexcept;
567
568 StringRef( char const* rawChars, size_type size ) noexcept
569 : m_start( rawChars ),
570 m_size( size )
571 {}
572
573 StringRef( std::string const& stdString ) noexcept
574 : m_start( stdString.c_str() ),
575 m_size( stdString.size() )
576 {}
577
578 ~StringRef() noexcept {
579 delete[] m_data;
580 }
581
582 auto operator = ( StringRef const &other ) noexcept -> StringRef& {
583 delete[] m_data;
584 m_data = nullptr;
585 m_start = other.m_start;
586 m_size = other.m_size;
587 return *this;
588 }
589
590 operator std::string() const;
591
592 void swap( StringRef& other ) noexcept;
593
594 public: // operators
595 auto operator == ( StringRef const& other ) const noexcept -> bool;
596 auto operator != ( StringRef const& other ) const noexcept -> bool;
597
598 auto operator[] ( size_type index ) const noexcept -> char;
599
600 public: // named queries
601 auto empty() const noexcept -> bool {
602 return m_size == 0;
603 }
604 auto size() const noexcept -> size_type {
605 return m_size;
606 }
607
608 auto numberOfCharacters() const noexcept -> size_type;
609 auto c_str() const -> char const*;
610
611 public: // substrings and searches
612 auto substr( size_type start, size_type size ) const noexcept -> StringRef;
613
614 // Returns the current start pointer.
615 // Note that the pointer can change when if the StringRef is a substring
616 auto currentData() const noexcept -> char const*;
617
618 private: // ownership queries - may not be consistent between calls
619 auto isOwned() const noexcept -> bool;
620 auto isSubstring() const noexcept -> bool;
621 };
622
623 auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
624 auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
625 auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
626
627 auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
628 auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
629
630 inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
631 return StringRef( rawChars, size );
632 }
633
634} // namespace Catch
635
636inline auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
637 return Catch::StringRef( rawChars, size );
638}
639
640// end catch_stringref.h
641// start catch_type_traits.hpp
642
643
644#include <type_traits>
645
646namespace Catch{
647
648#ifdef CATCH_CPP17_OR_GREATER
649 template <typename...>
650 inline constexpr auto is_unique = std::true_type{};
651
652 template <typename T, typename... Rest>
653 inline constexpr auto is_unique<T, Rest...> = std::bool_constant<
654 (!std::is_same_v<T, Rest> && ...) && is_unique<Rest...>
655 >{};
656#else
657
658template <typename...>
660
661template <typename T0, typename T1, typename... Rest>
662struct is_unique<T0, T1, Rest...> : std::integral_constant
663<bool,
664 !std::is_same<T0, T1>::value
665 && is_unique<T0, Rest...>::value
666 && is_unique<T1, Rest...>::value
667>{};
668
669#endif
670}
671
672// end catch_type_traits.hpp
673// start catch_preprocessor.hpp
674
675
676#define CATCH_RECURSION_LEVEL0(...) __VA_ARGS__
677#define CATCH_RECURSION_LEVEL1(...) CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(CATCH_RECURSION_LEVEL0(__VA_ARGS__)))
678#define CATCH_RECURSION_LEVEL2(...) CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(CATCH_RECURSION_LEVEL1(__VA_ARGS__)))
679#define CATCH_RECURSION_LEVEL3(...) CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(CATCH_RECURSION_LEVEL2(__VA_ARGS__)))
680#define CATCH_RECURSION_LEVEL4(...) CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(CATCH_RECURSION_LEVEL3(__VA_ARGS__)))
681#define CATCH_RECURSION_LEVEL5(...) CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(CATCH_RECURSION_LEVEL4(__VA_ARGS__)))
682
683#ifdef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
684#define INTERNAL_CATCH_EXPAND_VARGS(...) __VA_ARGS__
685// MSVC needs more evaluations
686#define CATCH_RECURSION_LEVEL6(...) CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(CATCH_RECURSION_LEVEL5(__VA_ARGS__)))
687#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL6(CATCH_RECURSION_LEVEL6(__VA_ARGS__))
688#else
689#define CATCH_RECURSE(...) CATCH_RECURSION_LEVEL5(__VA_ARGS__)
690#endif
691
692#define CATCH_REC_END(...)
693#define CATCH_REC_OUT
694
695#define CATCH_EMPTY()
696#define CATCH_DEFER(id) id CATCH_EMPTY()
697
698#define CATCH_REC_GET_END2() 0, CATCH_REC_END
699#define CATCH_REC_GET_END1(...) CATCH_REC_GET_END2
700#define CATCH_REC_GET_END(...) CATCH_REC_GET_END1
701#define CATCH_REC_NEXT0(test, next, ...) next CATCH_REC_OUT
702#define CATCH_REC_NEXT1(test, next) CATCH_DEFER ( CATCH_REC_NEXT0 ) ( test, next, 0)
703#define CATCH_REC_NEXT(test, next) CATCH_REC_NEXT1(CATCH_REC_GET_END test, next)
704
705#define CATCH_REC_LIST0(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
706#define CATCH_REC_LIST1(f, x, peek, ...) , f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST0) ) ( f, peek, __VA_ARGS__ )
707#define CATCH_REC_LIST2(f, x, peek, ...) f(x) CATCH_DEFER ( CATCH_REC_NEXT(peek, CATCH_REC_LIST1) ) ( f, peek, __VA_ARGS__ )
708
709#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__ )
710#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__ )
711#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__ )
712
713// Applies the function macro `f` to each of the remaining parameters, inserts commas between the results,
714// and passes userdata as the first parameter to each invocation,
715// e.g. CATCH_REC_LIST_UD(f, x, a, b, c) evaluates to f(x, a), f(x, b), f(x, c)
716#define CATCH_REC_LIST_UD(f, userdata, ...) CATCH_RECURSE(CATCH_REC_LIST2_UD(f, userdata, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
717
718#define CATCH_REC_LIST(f, ...) CATCH_RECURSE(CATCH_REC_LIST2(f, __VA_ARGS__, ()()(), ()()(), ()()(), 0))
719
720#define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
721#define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
722#define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
723#define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
724#define INTERNAL_CATCH_STRINGIZE(...) INTERNAL_CATCH_STRINGIZE2(__VA_ARGS__)
725#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
726#define INTERNAL_CATCH_STRINGIZE2(...) #__VA_ARGS__
727#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param))
728#else
729// MSVC is adding extra space and needs another indirection to expand INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
730#define INTERNAL_CATCH_STRINGIZE2(...) INTERNAL_CATCH_STRINGIZE3(__VA_ARGS__)
731#define INTERNAL_CATCH_STRINGIZE3(...) #__VA_ARGS__
732#define INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS(param) (INTERNAL_CATCH_STRINGIZE(INTERNAL_CATCH_REMOVE_PARENS(param)) + 1)
733#endif
734
735#define INTERNAL_CATCH_MAKE_NAMESPACE2(...) ns_##__VA_ARGS__
736#define INTERNAL_CATCH_MAKE_NAMESPACE(name) INTERNAL_CATCH_MAKE_NAMESPACE2(name)
737
738#define INTERNAL_CATCH_REMOVE_PARENS(...) INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF __VA_ARGS__)
739
740#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
741#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>())
742#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__))
743#else
744#define INTERNAL_CATCH_MAKE_TYPE_LIST2(...) INTERNAL_CATCH_EXPAND_VARGS(decltype(get_wrapper<INTERNAL_CATCH_REMOVE_PARENS_GEN(__VA_ARGS__)>()))
745#define INTERNAL_CATCH_MAKE_TYPE_LIST(...) INTERNAL_CATCH_EXPAND_VARGS(INTERNAL_CATCH_MAKE_TYPE_LIST2(INTERNAL_CATCH_REMOVE_PARENS(__VA_ARGS__)))
746#endif
747
748#define INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(...)\
749 CATCH_REC_LIST(INTERNAL_CATCH_MAKE_TYPE_LIST,__VA_ARGS__)
750
751#define INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_0) INTERNAL_CATCH_REMOVE_PARENS(_0)
752#define INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_0, _1) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_1_ARG(_1)
753#define INTERNAL_CATCH_REMOVE_PARENS_3_ARG(_0, _1, _2) INTERNAL_CATCH_REMOVE_PARENS(_0), INTERNAL_CATCH_REMOVE_PARENS_2_ARG(_1, _2)
754#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)
755#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)
756#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)
757#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, _4, _5, _6)
758#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)
759#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)
760#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)
761#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)
762
763#define INTERNAL_CATCH_VA_NARGS_IMPL(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N
764
765#define INTERNAL_CATCH_TYPE_GEN\
766 template<typename...> struct TypeList {};\
767 template<typename...Ts>\
768 constexpr auto get_wrapper() noexcept -> TypeList<Ts...> { return {}; }\
769 \
770 template<template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2> \
771 constexpr auto append(L1<E1...>, L2<E2...>) noexcept -> L1<E1...,E2...> { return {}; }\
772 template< template<typename...> class L1, typename...E1, template<typename...> class L2, typename...E2, typename...Rest>\
773 constexpr auto append(L1<E1...>, L2<E2...>, Rest...) noexcept -> decltype(append(L1<E1...,E2...>{}, Rest{}...)) { return {}; }\
774 \
775 template< template<typename...> class Container, template<typename...> class List, typename...elems>\
776 constexpr auto rewrap(List<elems...>) noexcept -> TypeList<Container<elems...>> { return {}; }\
777 template< template<typename...> class Container, template<typename...> class List, class...Elems, typename...Elements>\
778 constexpr auto rewrap(List<Elems...>,Elements...) noexcept -> decltype(append(TypeList<Container<Elems...>>{}, rewrap<Container>(Elements{}...))) { return {}; }\
779 \
780 template<template <typename...> class Final, template< typename...> class...Containers, typename...Types>\
781 constexpr auto create(TypeList<Types...>) noexcept -> decltype(append(Final<>{}, rewrap<Containers>(Types{}...)...)) { return {}; }
782
783#define INTERNAL_CATCH_NTTP_1(signature, ...)\
784 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> struct Nttp{};\
785 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
786 constexpr auto get_wrapper() noexcept -> Nttp<__VA_ARGS__> { return {}; } \
787 \
788 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature)>\
789 constexpr auto rewrap(List<__VA_ARGS__>) noexcept -> TypeList<Container<__VA_ARGS__>> { return {}; }\
790 template< template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class Container, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class List, INTERNAL_CATCH_REMOVE_PARENS(signature), typename...Elements>\
791 constexpr auto rewrap(List<__VA_ARGS__>,Elements...elems) noexcept -> decltype(append(TypeList<Container<__VA_ARGS__>>{}, rewrap<Container>(elems...))) { return {}; }\
792 template<template <typename...> class Final, template<INTERNAL_CATCH_REMOVE_PARENS(signature)> class...Containers, typename...Types>\
793 constexpr auto create(TypeList<Types...>) noexcept -> decltype(append(Final<>{}, rewrap<Containers>(Types{}...)...)) { return {}; }
794
795#define INTERNAL_CATCH_DECLARE_SIG_TEST0(TestName)
796#define INTERNAL_CATCH_DECLARE_SIG_TEST1(TestName, signature)\
797 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
798 static void TestName()
799#define INTERNAL_CATCH_DECLARE_SIG_TEST_X(TestName, signature, ...)\
800 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
801 static void TestName()
802
803#define INTERNAL_CATCH_DEFINE_SIG_TEST0(TestName)
804#define INTERNAL_CATCH_DEFINE_SIG_TEST1(TestName, signature)\
805 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
806 static void TestName()
807#define INTERNAL_CATCH_DEFINE_SIG_TEST_X(TestName, signature,...)\
808 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
809 static void TestName()
810
811#define INTERNAL_CATCH_NTTP_REGISTER0(TestFunc, signature)\
812 template<typename Type>\
813 void reg_test(TypeList<Type>, Catch::NameAndTags nameAndTags)\
814 {\
815 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<Type>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
816 }
817
818#define INTERNAL_CATCH_NTTP_REGISTER(TestFunc, signature, ...)\
819 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
820 void reg_test(Nttp<__VA_ARGS__>, Catch::NameAndTags nameAndTags)\
821 {\
822 Catch::AutoReg( Catch::makeTestInvoker(&TestFunc<__VA_ARGS__>), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), nameAndTags);\
823 }
824
825#define INTERNAL_CATCH_NTTP_REGISTER_METHOD0(TestName, signature, ...)\
826 template<typename Type>\
827 void reg_test(TypeList<Type>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
828 {\
829 Catch::AutoReg( Catch::makeTestInvoker(&TestName<Type>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
830 }
831
832#define INTERNAL_CATCH_NTTP_REGISTER_METHOD(TestName, signature, ...)\
833 template<INTERNAL_CATCH_REMOVE_PARENS(signature)>\
834 void reg_test(Nttp<__VA_ARGS__>, Catch::StringRef className, Catch::NameAndTags nameAndTags)\
835 {\
836 Catch::AutoReg( Catch::makeTestInvoker(&TestName<__VA_ARGS__>::test), CATCH_INTERNAL_LINEINFO, className, nameAndTags);\
837 }
838
839#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD0(TestName, ClassName)
840#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD1(TestName, ClassName, signature)\
841 template<typename TestType> \
842 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<TestType> { \
843 void test();\
844 }
845
846#define INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD_X(TestName, ClassName, signature, ...)\
847 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
848 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName)<__VA_ARGS__> { \
849 void test();\
850 }
851
852#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD0(TestName)
853#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD1(TestName, signature)\
854 template<typename TestType> \
855 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<TestType>::test()
856#define INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD_X(TestName, signature, ...)\
857 template<INTERNAL_CATCH_REMOVE_PARENS(signature)> \
858 void INTERNAL_CATCH_MAKE_NAMESPACE(TestName)::TestName<__VA_ARGS__>::test()
859
860#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
861#define INTERNAL_CATCH_NTTP_0
862#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)
863#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__)
864#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__)
865#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__)
866#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__)
867#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__)
868#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__)
869#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__)
870#else
871#define INTERNAL_CATCH_NTTP_0(signature)
872#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__))
873#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__))
874#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__))
875#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__))
876#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__))
877#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__))
878#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__))
879#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__))
880#endif
881
882// end catch_preprocessor.hpp
883// start catch_meta.hpp
884
885
886#include <type_traits>
887
888namespace Catch {
889 template<typename T>
891} // namespace Catch
892
893// end catch_meta.hpp
894namespace Catch {
895
896template<typename C>
898 void (C::*m_testAsMethod)();
899public:
900 TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
901
902 void invoke() const override {
903 C obj;
904 (obj.*m_testAsMethod)();
905 }
906};
907
908auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
909
910template<typename C>
911auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
912 return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
913}
914
916 NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
919};
920
922 AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
924};
925
926} // end namespace Catch
927
928#if defined(CATCH_CONFIG_DISABLE)
929 #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
930 static void TestName()
931 #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
932 namespace{ \
933 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
934 void test(); \
935 }; \
936 } \
937 void TestName::test()
938 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION_2( TestName, TestFunc, Name, Tags, Signature, ... ) \
939 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature))
940 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
941 namespace{ \
942 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
943 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
944 } \
945 } \
946 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
947
948 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
949 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
950 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__ )
951 #else
952 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(Name, Tags, ...) \
953 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__ ) )
954 #endif
955
956 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
957 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
958 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__ )
959 #else
960 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(Name, Tags, Signature, ...) \
961 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__ ) )
962 #endif
963
964 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
965 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
966 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__ )
967 #else
968 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION( ClassName, Name, Tags,... ) \
969 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__ ) )
970 #endif
971
972 #ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
973 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
974 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__ )
975 #else
976 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION( ClassName, Name, Tags, Signature, ... ) \
977 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__ ) )
978 #endif
979#endif
980
981 ///////////////////////////////////////////////////////////////////////////////
982 #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
983 static void TestName(); \
984 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
985 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
986 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
987 static void TestName()
988 #define INTERNAL_CATCH_TESTCASE( ... ) \
989 INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
990
991 ///////////////////////////////////////////////////////////////////////////////
992 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
993 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
994 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
995 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
996
997 ///////////////////////////////////////////////////////////////////////////////
998 #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
999 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1000 namespace{ \
1001 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName) { \
1002 void test(); \
1003 }; \
1004 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
1005 } \
1006 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
1007 void TestName::test()
1008 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
1009 INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
1010
1011 ///////////////////////////////////////////////////////////////////////////////
1012 #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
1013 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1014 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
1015 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
1016
1017 ///////////////////////////////////////////////////////////////////////////////
1018 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_2(TestName, TestFunc, Name, Tags, Signature, ... )\
1019 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1020 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1021 INTERNAL_CATCH_DECLARE_SIG_TEST(TestFunc, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1022 namespace {\
1023 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){\
1024 INTERNAL_CATCH_TYPE_GEN\
1025 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1026 INTERNAL_CATCH_NTTP_REG_GEN(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1027 template<typename...Types> \
1028 struct TestName{\
1029 TestName(){\
1030 int index = 0; \
1031 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1032 using expander = int[];\
1033 (void)expander{(reg_test(Types{}, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
1034 }\
1035 };\
1036 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1037 TestName<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1038 return 0;\
1039 }();\
1040 }\
1041 }\
1042 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
1043 CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
1044 INTERNAL_CATCH_DEFINE_SIG_TEST(TestFunc,INTERNAL_CATCH_REMOVE_PARENS(Signature))
1045
1046#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1047 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1048 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__ )
1049#else
1050 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE(Name, Tags, ...) \
1051 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__ ) )
1052#endif
1053
1054#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1055 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1056 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__ )
1057#else
1058 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG(Name, Tags, Signature, ...) \
1059 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__ ) )
1060#endif
1061
1062 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE2(TestName, TestFuncName, Name, Tags, Signature, TmplTypes, TypesList) \
1063 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1064 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1065 template<typename TestType> static void TestFuncName(); \
1066 namespace {\
1067 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName) { \
1068 INTERNAL_CATCH_TYPE_GEN \
1069 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature)) \
1070 template<typename... Types> \
1071 struct TestName { \
1072 void reg_tests() { \
1073 int index = 0; \
1074 using expander = int[]; \
1075 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1076 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1077 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1078 (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++, 0)... };/* NOLINT */\
1079 } \
1080 }; \
1081 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){ \
1082 using TestInit = decltype(create<TestName, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{})); \
1083 TestInit t; \
1084 t.reg_tests(); \
1085 return 0; \
1086 }(); \
1087 } \
1088 } \
1089 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
1090 CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
1091 template<typename TestType> \
1092 static void TestFuncName()
1093
1094#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1095 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1096 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__)
1097#else
1098 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE(Name, Tags, ...)\
1099 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__ ) )
1100#endif
1101
1102#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1103 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1104 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__)
1105#else
1106 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG(Name, Tags, Signature, ...)\
1107 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__ ) )
1108#endif
1109
1110 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_2( TestNameClass, TestName, ClassName, Name, Tags, Signature, ... ) \
1111 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1112 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1113 namespace {\
1114 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestName){ \
1115 INTERNAL_CATCH_TYPE_GEN\
1116 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1117 INTERNAL_CATCH_DECLARE_SIG_TEST_METHOD(TestName, ClassName, INTERNAL_CATCH_REMOVE_PARENS(Signature));\
1118 INTERNAL_CATCH_NTTP_REG_METHOD_GEN(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1119 template<typename...Types> \
1120 struct TestNameClass{\
1121 TestNameClass(){\
1122 int index = 0; \
1123 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, __VA_ARGS__)};\
1124 using expander = int[];\
1125 (void)expander{(reg_test(Types{}, #ClassName, Catch::NameAndTags{ Name " - " + std::string(tmpl_types[index]), Tags } ), index++, 0)... };/* NOLINT */ \
1126 }\
1127 };\
1128 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1129 TestNameClass<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(__VA_ARGS__)>();\
1130 return 0;\
1131 }();\
1132 }\
1133 }\
1134 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS\
1135 CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS\
1136 INTERNAL_CATCH_DEFINE_SIG_TEST_METHOD(TestName, INTERNAL_CATCH_REMOVE_PARENS(Signature))
1137
1138#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1139 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1140 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__ )
1141#else
1142 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( ClassName, Name, Tags,... ) \
1143 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__ ) )
1144#endif
1145
1146#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1147 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1148 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__ )
1149#else
1150 #define INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... ) \
1151 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__ ) )
1152#endif
1153
1154 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_2(TestNameClass, TestName, ClassName, Name, Tags, Signature, TmplTypes, TypesList)\
1155 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
1156 CATCH_INTERNAL_SUPPRESS_ZERO_VARIADIC_WARNINGS \
1157 template<typename TestType> \
1158 struct TestName : INTERNAL_CATCH_REMOVE_PARENS(ClassName <TestType>) { \
1159 void test();\
1160 };\
1161 namespace {\
1162 namespace INTERNAL_CATCH_MAKE_NAMESPACE(TestNameClass) {\
1163 INTERNAL_CATCH_TYPE_GEN \
1164 INTERNAL_CATCH_NTTP_GEN(INTERNAL_CATCH_REMOVE_PARENS(Signature))\
1165 template<typename...Types>\
1166 struct TestNameClass{\
1167 void reg_tests(){\
1168 int index = 0;\
1169 using expander = int[];\
1170 constexpr char const* tmpl_types[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes))};\
1171 constexpr char const* types_list[] = {CATCH_REC_LIST(INTERNAL_CATCH_STRINGIZE_WITHOUT_PARENS, INTERNAL_CATCH_REMOVE_PARENS(TypesList))};\
1172 constexpr auto num_types = sizeof(types_list) / sizeof(types_list[0]);\
1173 (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++, 0)... };/* NOLINT */ \
1174 }\
1175 };\
1176 static int INTERNAL_CATCH_UNIQUE_NAME( globalRegistrar ) = [](){\
1177 using TestInit = decltype(create<TestNameClass, INTERNAL_CATCH_REMOVE_PARENS(TmplTypes)>(TypeList<INTERNAL_CATCH_MAKE_TYPE_LISTS_FROM_TYPES(INTERNAL_CATCH_REMOVE_PARENS(TypesList))>{}));\
1178 TestInit t;\
1179 t.reg_tests();\
1180 return 0;\
1181 }(); \
1182 }\
1183 }\
1184 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
1185 CATCH_INTERNAL_UNSUPPRESS_ZERO_VARIADIC_WARNINGS \
1186 template<typename TestType> \
1187 void TestName<TestType>::test()
1188
1189#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1190 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1191 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__ )
1192#else
1193 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( ClassName, Name, Tags, ... )\
1194 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__ ) )
1195#endif
1196
1197#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
1198 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1199 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__ )
1200#else
1201 #define INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( ClassName, Name, Tags, Signature, ... )\
1202 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__ ) )
1203#endif
1204
1205// end catch_test_registry.h
1206// start catch_capture.hpp
1207
1208// start catch_assertionhandler.h
1209
1210// start catch_assertioninfo.h
1211
1212// start catch_result_type.h
1213
1214namespace Catch {
1215
1216 // ResultWas::OfType enum
1236
1237 bool isOk( ResultWas::OfType resultType );
1238 bool isJustInfo( int flags );
1239
1240 // ResultDisposition::Flags enum
1241 struct ResultDisposition { enum Flags {
1242 Normal = 0x01,
1243
1244 ContinueOnFailure = 0x02, // Failures fail test, but execution continues
1245 FalseTest = 0x04, // Prefix expression with !
1246 SuppressFail = 0x08 // Failures are reported but do not fail the test
1247 }; };
1248
1250
1251 bool shouldContinueOnFailure( int flags );
1252 inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
1253 bool shouldSuppressFailure( int flags );
1254
1255} // end namespace Catch
1256
1257// end catch_result_type.h
1258namespace Catch {
1259
1261 {
1266
1267 // We want to delete this constructor but a compiler bug in 4.8 means
1268 // the struct is then treated as non-aggregate
1269 //AssertionInfo() = delete;
1270 };
1271
1272} // end namespace Catch
1273
1274// end catch_assertioninfo.h
1275// start catch_decomposer.h
1276
1277// start catch_tostring.h
1278
1279#include <vector>
1280#include <cstddef>
1281#include <type_traits>
1282#include <string>
1283// start catch_stream.h
1284
1285#include <iosfwd>
1286#include <cstddef>
1287#include <ostream>
1288
1289namespace Catch {
1290
1294
1295 class StringRef;
1296
1297 struct IStream {
1298 virtual ~IStream();
1299 virtual std::ostream& stream() const = 0;
1300 };
1301
1302 auto makeStream( StringRef const &filename ) -> IStream const*;
1303
1307 public:
1310
1311 auto str() const -> std::string;
1312
1313 template<typename T>
1314 auto operator << ( T const& value ) -> ReusableStringStream& {
1315 *m_oss << value;
1316 return *this;
1317 }
1318 auto get() -> std::ostream& { return *m_oss; }
1319 };
1320}
1321
1322// end catch_stream.h
1323// start catch_interfaces_enum_values_registry.h
1324
1325#include <vector>
1326
1327namespace Catch {
1328
1329 namespace Detail {
1338 } // namespace Detail
1339
1342
1343 virtual Detail::EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values ) = 0;
1344
1345 template<typename E>
1347 std::vector<int> intValues;
1348 intValues.reserve( values.size() );
1349 for( auto enumValue : values )
1350 intValues.push_back( static_cast<int>( enumValue ) );
1351 return registerEnum( enumName, allEnums, intValues );
1352 }
1353 };
1354
1355} // Catch
1356
1357// end catch_interfaces_enum_values_registry.h
1358
1359#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1360#include <string_view>
1361#endif
1362
1363#ifdef __OBJC__
1364// start catch_objc_arc.hpp
1365
1366#import <Foundation/Foundation.h>
1367
1368#ifdef __has_feature
1369#define CATCH_ARC_ENABLED __has_feature(objc_arc)
1370#else
1371#define CATCH_ARC_ENABLED 0
1372#endif
1373
1374void arcSafeRelease( NSObject* obj );
1375id performOptionalSelector( id obj, SEL sel );
1376
1377#if !CATCH_ARC_ENABLED
1378inline void arcSafeRelease( NSObject* obj ) {
1379 [obj release];
1380}
1381inline id performOptionalSelector( id obj, SEL sel ) {
1382 if( [obj respondsToSelector: sel] )
1383 return [obj performSelector: sel];
1384 return nil;
1385}
1386#define CATCH_UNSAFE_UNRETAINED
1387#define CATCH_ARC_STRONG
1388#else
1389inline void arcSafeRelease( NSObject* ){}
1390inline id performOptionalSelector( id obj, SEL sel ) {
1391#ifdef __clang__
1392#pragma clang diagnostic push
1393#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
1394#endif
1395 if( [obj respondsToSelector: sel] )
1396 return [obj performSelector: sel];
1397#ifdef __clang__
1398#pragma clang diagnostic pop
1399#endif
1400 return nil;
1401}
1402#define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
1403#define CATCH_ARC_STRONG __strong
1404#endif
1405
1406// end catch_objc_arc.hpp
1407#endif
1408
1409#ifdef _MSC_VER
1410#pragma warning(push)
1411#pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
1412#endif
1413
1414namespace Catch {
1415 namespace Detail {
1416
1417 extern const std::string unprintableString;
1418
1419 std::string rawMemoryToString( const void *object, std::size_t size );
1420
1421 template<typename T>
1423 return rawMemoryToString( &object, sizeof(object) );
1424 }
1425
1426 template<typename T>
1428 template<typename SS, typename TT>
1429 static auto test(int)
1430 -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
1431
1432 template<typename, typename>
1433 static auto test(...)->std::false_type;
1434
1435 public:
1436 static const bool value = decltype(test<std::ostream, const T&>(0))::value;
1437 };
1438
1439 template<typename E>
1441
1442 template<typename T>
1443 typename std::enable_if<
1448 template<typename T>
1449 typename std::enable_if<
1452 return ex.what();
1453 }
1454
1455 template<typename T>
1456 typename std::enable_if<
1461
1462#if defined(_MANAGED)
1463 //! Convert a CLR string to a utf8 std::string
1464 template<typename T>
1465 std::string clrReferenceToString( T^ ref ) {
1466 if (ref == nullptr)
1467 return std::string("null");
1468 auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
1469 cli::pin_ptr<System::Byte> p = &bytes[0];
1470 return std::string(reinterpret_cast<char const *>(p), bytes->Length);
1471 }
1472#endif
1473
1474 } // namespace Detail
1475
1476 // If we decide for C++14, change these to enable_if_ts
1477 template <typename T, typename = void>
1479 template <typename Fake = T>
1480 static
1482 convert(const Fake& value) {
1484 // NB: call using the function-like syntax to avoid ambiguity with
1485 // user-defined templated operator<< under clang.
1486 rss.operator<<(value);
1487 return rss.str();
1488 }
1489
1490 template <typename Fake = T>
1491 static
1493 convert( const Fake& value ) {
1494#if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
1496#else
1497 return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
1498#endif
1499 }
1500 };
1501
1502 namespace Detail {
1503
1504 // This function dispatches all stringification requests inside of Catch.
1505 // Should be preferably called fully qualified, like ::Catch::Detail::stringify
1506 template <typename T>
1508 return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
1509 }
1510
1511 template<typename E>
1513 return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
1514 }
1515
1516#if defined(_MANAGED)
1517 template <typename T>
1518 std::string stringify( T^ e ) {
1519 return ::Catch::StringMaker<T^>::convert(e);
1520 }
1521#endif
1522
1523 } // namespace Detail
1524
1525 // Some predefined specializations
1526
1527 template<>
1528 struct StringMaker<std::string> {
1529 static std::string convert(const std::string& str);
1530 };
1531
1532#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1533 template<>
1534 struct StringMaker<std::string_view> {
1536 };
1537#endif
1538
1539 template<>
1540 struct StringMaker<char const *> {
1541 static std::string convert(char const * str);
1542 };
1543 template<>
1544 struct StringMaker<char *> {
1545 static std::string convert(char * str);
1546 };
1547
1548#ifdef CATCH_CONFIG_WCHAR
1549 template<>
1550 struct StringMaker<std::wstring> {
1551 static std::string convert(const std::wstring& wstr);
1552 };
1553
1554# ifdef CATCH_CONFIG_CPP17_STRING_VIEW
1555 template<>
1556 struct StringMaker<std::wstring_view> {
1558 };
1559# endif
1560
1561 template<>
1562 struct StringMaker<wchar_t const *> {
1563 static std::string convert(wchar_t const * str);
1564 };
1565 template<>
1567 static std::string convert(wchar_t * str);
1568 };
1569#endif
1570
1571 // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
1572 // while keeping string semantics?
1573 template<int SZ>
1574 struct StringMaker<char[SZ]> {
1575 static std::string convert(char const* str) {
1576 return ::Catch::Detail::stringify(std::string{ str });
1577 }
1578 };
1579 template<int SZ>
1580 struct StringMaker<signed char[SZ]> {
1581 static std::string convert(signed char const* str) {
1582 return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
1583 }
1584 };
1585 template<int SZ>
1586 struct StringMaker<unsigned char[SZ]> {
1587 static std::string convert(unsigned char const* str) {
1588 return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
1589 }
1590 };
1591
1592 template<>
1595 };
1596 template<>
1597 struct StringMaker<long> {
1599 };
1600 template<>
1601 struct StringMaker<long long> {
1602 static std::string convert(long long value);
1603 };
1604 template<>
1605 struct StringMaker<unsigned int> {
1606 static std::string convert(unsigned int value);
1607 };
1608 template<>
1609 struct StringMaker<unsigned long> {
1610 static std::string convert(unsigned long value);
1611 };
1612 template<>
1613 struct StringMaker<unsigned long long> {
1614 static std::string convert(unsigned long long value);
1615 };
1616
1617 template<>
1619 static std::string convert(bool b);
1620 };
1621
1622 template<>
1624 static std::string convert(char c);
1625 };
1626 template<>
1627 struct StringMaker<signed char> {
1628 static std::string convert(signed char c);
1629 };
1630 template<>
1631 struct StringMaker<unsigned char> {
1632 static std::string convert(unsigned char c);
1633 };
1634
1635 template<>
1636 struct StringMaker<std::nullptr_t> {
1638 };
1639
1640 template<>
1641 struct StringMaker<float> {
1643 static int precision;
1644 };
1645
1646 template<>
1647 struct StringMaker<double> {
1648 static std::string convert(double value);
1649 static int precision;
1650 };
1651
1652 template <typename T>
1653 struct StringMaker<T*> {
1654 template <typename U>
1655 static std::string convert(U* p) {
1656 if (p) {
1657 return ::Catch::Detail::rawMemoryToString(p);
1658 } else {
1659 return "nullptr";
1660 }
1661 }
1662 };
1663
1664 template <typename R, typename C>
1665 struct StringMaker<R C::*> {
1666 static std::string convert(R C::* p) {
1667 if (p) {
1668 return ::Catch::Detail::rawMemoryToString(p);
1669 } else {
1670 return "nullptr";
1671 }
1672 }
1673 };
1674
1675#if defined(_MANAGED)
1676 template <typename T>
1677 struct StringMaker<T^> {
1678 static std::string convert( T^ ref ) {
1679 return ::Catch::Detail::clrReferenceToString(ref);
1680 }
1681 };
1682#endif
1683
1684 namespace Detail {
1685 template<typename InputIterator>
1686 std::string rangeToString(InputIterator first, InputIterator last) {
1688 rss << "{ ";
1689 if (first != last) {
1690 rss << ::Catch::Detail::stringify(*first);
1691 for (++first; first != last; ++first)
1692 rss << ", " << ::Catch::Detail::stringify(*first);
1693 }
1694 rss << " }";
1695 return rss.str();
1696 }
1697 }
1698
1699#ifdef __OBJC__
1700 template<>
1701 struct StringMaker<NSString*> {
1702 static std::string convert(NSString * nsstring) {
1703 if (!nsstring)
1704 return "nil";
1705 return std::string("@") + [nsstring UTF8String];
1706 }
1707 };
1708 template<>
1709 struct StringMaker<NSObject*> {
1710 static std::string convert(NSObject* nsObject) {
1711 return ::Catch::Detail::stringify([nsObject description]);
1712 }
1713
1714 };
1715 namespace Detail {
1716 inline std::string stringify( NSString* nsstring ) {
1717 return StringMaker<NSString*>::convert( nsstring );
1718 }
1719
1720 } // namespace Detail
1721#endif // __OBJC__
1722
1723} // namespace Catch
1724
1725//////////////////////////////////////////////////////
1726// Separate std-lib types stringification, so it can be selectively enabled
1727// This means that we do not bring in
1728
1729#if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
1730# define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1731# define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1732# define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1733# define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
1734# define CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1735#endif
1736
1737// Separate std::pair specialization
1738#if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
1739#include <utility>
1740namespace Catch {
1741 template<typename T1, typename T2>
1742 struct StringMaker<std::pair<T1, T2> > {
1743 static std::string convert(const std::pair<T1, T2>& pair) {
1744 ReusableStringStream rss;
1745 rss << "{ "
1747 << ", "
1749 << " }";
1750 return rss.str();
1751 }
1752 };
1753}
1754#endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
1755
1756#if defined(CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_OPTIONAL)
1757#include <optional>
1758namespace Catch {
1759 template<typename T>
1760 struct StringMaker<std::optional<T> > {
1761 static std::string convert(const std::optional<T>& optional) {
1762 ReusableStringStream rss;
1763 if (optional.has_value()) {
1764 rss << ::Catch::Detail::stringify(*optional);
1765 } else {
1766 rss << "{ }";
1767 }
1768 return rss.str();
1769 }
1770 };
1771}
1772#endif // CATCH_CONFIG_ENABLE_OPTIONAL_STRINGMAKER
1773
1774// Separate std::tuple specialization
1775#if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
1776#include <tuple>
1777namespace Catch {
1778 namespace Detail {
1779 template<
1780 typename Tuple,
1781 std::size_t N = 0,
1782 bool = (N < std::tuple_size<Tuple>::value)
1783 >
1784 struct TupleElementPrinter {
1785 static void print(const Tuple& tuple, std::ostream& os) {
1786 os << (N ? ", " : " ")
1788 TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
1789 }
1790 };
1791
1792 template<
1793 typename Tuple,
1794 std::size_t N
1795 >
1796 struct TupleElementPrinter<Tuple, N, false> {
1797 static void print(const Tuple&, std::ostream&) {}
1798 };
1799
1800 }
1801
1802 template<typename ...Types>
1803 struct StringMaker<std::tuple<Types...>> {
1804 static std::string convert(const std::tuple<Types...>& tuple) {
1805 ReusableStringStream rss;
1806 rss << '{';
1807 Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
1808 rss << " }";
1809 return rss.str();
1810 }
1811 };
1812}
1813#endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
1814
1815#if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
1816#include <variant>
1817namespace Catch {
1818 template<>
1819 struct StringMaker<std::monostate> {
1820 static std::string convert(const std::monostate&) {
1821 return "{ }";
1822 }
1823 };
1824
1825 template<typename... Elements>
1826 struct StringMaker<std::variant<Elements...>> {
1827 static std::string convert(const std::variant<Elements...>& variant) {
1828 if (variant.valueless_by_exception()) {
1829 return "{valueless variant}";
1830 } else {
1831 return std::visit(
1832 [](const auto& value) {
1833 return ::Catch::Detail::stringify(value);
1834 },
1835 variant
1836 );
1837 }
1838 }
1839 };
1840}
1841#endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
1842
1843namespace Catch {
1844 struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
1845
1846 // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
1847 using std::begin;
1848 using std::end;
1849
1852
1853 template <typename T>
1859
1860#if defined(_MANAGED) // Managed types are never ranges
1861 template <typename T>
1862 struct is_range<T^> {
1863 static const bool value = false;
1864 };
1865#endif
1866
1867 template<typename Range>
1868 std::string rangeToString( Range const& range ) {
1869 return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
1870 }
1871
1872 // Handle vector<bool> specially
1873 template<typename Allocator>
1876 rss << "{ ";
1877 bool first = true;
1878 for( bool b : v ) {
1879 if( first )
1880 first = false;
1881 else
1882 rss << ", ";
1883 rss << ::Catch::Detail::stringify( b );
1884 }
1885 rss << " }";
1886 return rss.str();
1887 }
1888
1889 template<typename R>
1890 struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
1891 static std::string convert( R const& range ) {
1892 return rangeToString( range );
1893 }
1894 };
1895
1896 template <typename T, int SZ>
1897 struct StringMaker<T[SZ]> {
1898 static std::string convert(T const(&arr)[SZ]) {
1899 return rangeToString(arr);
1900 }
1901 };
1902
1903} // namespace Catch
1904
1905// Separate std::chrono::duration specialization
1906#if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
1907#include <ctime>
1908#include <ratio>
1909#include <chrono>
1910
1911namespace Catch {
1912
1913template <class Ratio>
1914struct ratio_string {
1915 static std::string symbol();
1916};
1917
1918template <class Ratio>
1919std::string ratio_string<Ratio>::symbol() {
1921 rss << '[' << Ratio::num << '/'
1922 << Ratio::den << ']';
1923 return rss.str();
1924}
1925template <>
1926struct ratio_string<std::atto> {
1927 static std::string symbol();
1928};
1929template <>
1930struct ratio_string<std::femto> {
1931 static std::string symbol();
1932};
1933template <>
1934struct ratio_string<std::pico> {
1935 static std::string symbol();
1936};
1937template <>
1938struct ratio_string<std::nano> {
1939 static std::string symbol();
1940};
1941template <>
1942struct ratio_string<std::micro> {
1943 static std::string symbol();
1944};
1945template <>
1946struct ratio_string<std::milli> {
1947 static std::string symbol();
1948};
1949
1950 ////////////
1951 // std::chrono::duration specializations
1952 template<typename Value, typename Ratio>
1953 struct StringMaker<std::chrono::duration<Value, Ratio>> {
1955 ReusableStringStream rss;
1956 rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
1957 return rss.str();
1958 }
1959 };
1960 template<typename Value>
1961 struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
1962 static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
1963 ReusableStringStream rss;
1964 rss << duration.count() << " s";
1965 return rss.str();
1966 }
1967 };
1968 template<typename Value>
1969 struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
1970 static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
1971 ReusableStringStream rss;
1972 rss << duration.count() << " m";
1973 return rss.str();
1974 }
1975 };
1976 template<typename Value>
1977 struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
1978 static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
1979 ReusableStringStream rss;
1980 rss << duration.count() << " h";
1981 return rss.str();
1982 }
1983 };
1984
1985 ////////////
1986 // std::chrono::time_point specialization
1987 // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
1988 template<typename Clock, typename Duration>
1989 struct StringMaker<std::chrono::time_point<Clock, Duration>> {
1991 return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
1992 }
1993 };
1994 // std::chrono::time_point<system_clock> specialization
1995 template<typename Duration>
1996 struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
1998 auto converted = std::chrono::system_clock::to_time_t(time_point);
1999
2000#ifdef _MSC_VER
2001 std::tm timeInfo = {};
2002 gmtime_s(&timeInfo, &converted);
2003#else
2004 std::tm* timeInfo = std::gmtime(&converted);
2005#endif
2006
2007 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
2008 char timeStamp[timeStampSize];
2009 const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
2010
2011#ifdef _MSC_VER
2012 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
2013#else
2014 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
2015#endif
2016 return std::string(timeStamp);
2017 }
2018 };
2019}
2020#endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
2021
2022#define INTERNAL_CATCH_REGISTER_ENUM( enumName, ... ) \
2023namespace Catch { \
2024 template<> struct StringMaker<enumName> { \
2025 static std::string convert( enumName value ) { \
2026 static const auto& enumInfo = ::Catch::getMutableRegistryHub().getMutableEnumValuesRegistry().registerEnum( #enumName, #__VA_ARGS__, { __VA_ARGS__ } ); \
2027 return enumInfo.lookup( static_cast<int>( value ) ); \
2028 } \
2029 }; \
2030}
2031
2032#define CATCH_REGISTER_ENUM( enumName, ... ) INTERNAL_CATCH_REGISTER_ENUM( enumName, __VA_ARGS__ )
2033
2034#ifdef _MSC_VER
2035#pragma warning(pop)
2036#endif
2037
2038// end catch_tostring.h
2039#include <iosfwd>
2040
2041#ifdef _MSC_VER
2042#pragma warning(push)
2043#pragma warning(disable:4389) // '==' : signed/unsigned mismatch
2044#pragma warning(disable:4018) // more "signed/unsigned mismatch"
2045#pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
2046#pragma warning(disable:4180) // qualifier applied to function type has no meaning
2047#pragma warning(disable:4800) // Forcing result to true or false
2048#endif
2049
2050namespace Catch {
2051
2053 auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
2054 auto getResult() const -> bool { return m_result; }
2055 virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
2056
2059 m_result( result )
2060 {}
2061
2062 // We don't actually need a virtual destructor, but many static analysers
2063 // complain if it's not here :-(
2065
2068
2069 };
2070
2072
2073 template<typename LhsT, typename RhsT>
2075 LhsT m_lhs;
2077 RhsT m_rhs;
2078
2083
2084 public:
2085 BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
2086 : ITransientExpression{ true, comparisonResult },
2087 m_lhs( lhs ),
2088 m_op( op ),
2089 m_rhs( rhs )
2090 {}
2091
2092 template<typename T>
2094 static_assert(always_false<T>::value,
2095 "chained comparisons are not supported inside assertions, "
2096 "wrap the expression inside parentheses, or decompose it");
2097 }
2098
2099 template<typename T>
2101 static_assert(always_false<T>::value,
2102 "chained comparisons are not supported inside assertions, "
2103 "wrap the expression inside parentheses, or decompose it");
2104 }
2105
2106 template<typename T>
2108 static_assert(always_false<T>::value,
2109 "chained comparisons are not supported inside assertions, "
2110 "wrap the expression inside parentheses, or decompose it");
2111 }
2112
2113 template<typename T>
2115 static_assert(always_false<T>::value,
2116 "chained comparisons are not supported inside assertions, "
2117 "wrap the expression inside parentheses, or decompose it");
2118 }
2119
2120 template<typename T>
2122 static_assert(always_false<T>::value,
2123 "chained comparisons are not supported inside assertions, "
2124 "wrap the expression inside parentheses, or decompose it");
2125 }
2126
2127 template<typename T>
2129 static_assert(always_false<T>::value,
2130 "chained comparisons are not supported inside assertions, "
2131 "wrap the expression inside parentheses, or decompose it");
2132 }
2133
2134 template<typename T>
2136 static_assert(always_false<T>::value,
2137 "chained comparisons are not supported inside assertions, "
2138 "wrap the expression inside parentheses, or decompose it");
2139 }
2140
2141 template<typename T>
2143 static_assert(always_false<T>::value,
2144 "chained comparisons are not supported inside assertions, "
2145 "wrap the expression inside parentheses, or decompose it");
2146 }
2147 };
2148
2149 template<typename LhsT>
2151 LhsT m_lhs;
2152
2153 void streamReconstructedExpression( std::ostream &os ) const override {
2155 }
2156
2157 public:
2158 explicit UnaryExpr( LhsT lhs )
2159 : ITransientExpression{ false, static_cast<bool>(lhs) },
2160 m_lhs( lhs )
2161 {}
2162 };
2163
2164 // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
2165 template<typename LhsT, typename RhsT>
2166 auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
2167 template<typename T>
2168 auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
2169 template<typename T>
2170 auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
2171 template<typename T>
2172 auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
2173 template<typename T>
2174 auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
2175
2176 template<typename LhsT, typename RhsT>
2177 auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
2178 template<typename T>
2179 auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
2180 template<typename T>
2181 auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
2182 template<typename T>
2183 auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
2184 template<typename T>
2185 auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
2186
2187 template<typename LhsT>
2188 class ExprLhs {
2189 LhsT m_lhs;
2190 public:
2191 explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
2192
2193 template<typename RhsT>
2194 auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2195 return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
2196 }
2197 auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
2198 return { m_lhs == rhs, m_lhs, "==", rhs };
2199 }
2200
2201 template<typename RhsT>
2202 auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2203 return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
2204 }
2205 auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
2206 return { m_lhs != rhs, m_lhs, "!=", rhs };
2207 }
2208
2209 template<typename RhsT>
2210 auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2211 return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
2212 }
2213 template<typename RhsT>
2214 auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2215 return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
2216 }
2217 template<typename RhsT>
2218 auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2219 return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
2220 }
2221 template<typename RhsT>
2222 auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
2223 return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
2224 }
2225
2226 template<typename RhsT>
2227 auto operator && ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
2228 static_assert(always_false<RhsT>::value,
2229 "operator&& is not supported inside assertions, "
2230 "wrap the expression inside parentheses, or decompose it");
2231 }
2232
2233 template<typename RhsT>
2234 auto operator || ( RhsT const& ) -> BinaryExpr<LhsT, RhsT const&> const {
2235 static_assert(always_false<RhsT>::value,
2236 "operator|| is not supported inside assertions, "
2237 "wrap the expression inside parentheses, or decompose it");
2238 }
2239
2240 auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
2241 return UnaryExpr<LhsT>{ m_lhs };
2242 }
2243 };
2244
2246
2247 template<typename T>
2248 void handleExpression( ExprLhs<T> const& expr ) {
2250 }
2251
2252 struct Decomposer {
2253 template<typename T>
2254 auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
2255 return ExprLhs<T const&>{ lhs };
2256 }
2257
2259 return ExprLhs<bool>{ value };
2260 }
2261 };
2262
2263} // end namespace Catch
2264
2265#ifdef _MSC_VER
2266#pragma warning(pop)
2267#endif
2268
2269// end catch_decomposer.h
2270// start catch_interfaces_capture.h
2271
2272#include <string>
2273
2274namespace Catch {
2275
2276 class AssertionResult;
2277 struct AssertionInfo;
2278 struct SectionInfo;
2279 struct SectionEndInfo;
2280 struct MessageInfo;
2281 struct MessageBuilder;
2282 struct Counts;
2283 struct BenchmarkInfo;
2284 struct BenchmarkStats;
2285 struct AssertionReaction;
2286 struct SourceLineInfo;
2287
2288 struct ITransientExpression;
2289 struct IGeneratorTracker;
2290
2292
2294
2295 virtual bool sectionStarted( SectionInfo const& sectionInfo,
2296 Counts& assertions ) = 0;
2297 virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
2298 virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
2299
2300 virtual auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
2301
2302 virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
2303 virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;
2304
2305 virtual void pushScopedMessage( MessageInfo const& message ) = 0;
2306 virtual void popScopedMessage( MessageInfo const& message ) = 0;
2307
2308 virtual void emplaceUnscopedMessage( MessageBuilder const& builder ) = 0;
2309
2310 virtual void handleFatalErrorCondition( StringRef message ) = 0;
2311
2312 virtual void handleExpr
2313 ( AssertionInfo const& info,
2314 ITransientExpression const& expr,
2315 AssertionReaction& reaction ) = 0;
2316 virtual void handleMessage
2317 ( AssertionInfo const& info,
2318 ResultWas::OfType resultType,
2319 StringRef const& message,
2320 AssertionReaction& reaction ) = 0;
2322 ( AssertionInfo const& info,
2323 AssertionReaction& reaction ) = 0;
2325 ( AssertionInfo const& info,
2326 std::string const& message,
2327 AssertionReaction& reaction ) = 0;
2328 virtual void handleIncomplete
2329 ( AssertionInfo const& info ) = 0;
2330 virtual void handleNonExpr
2331 ( AssertionInfo const &info,
2332 ResultWas::OfType resultType,
2333 AssertionReaction &reaction ) = 0;
2334
2335 virtual bool lastAssertionPassed() = 0;
2336 virtual void assertionPassed() = 0;
2337
2338 // Deprecated, do not use:
2339 virtual std::string getCurrentTestName() const = 0;
2340 virtual const AssertionResult* getLastResult() const = 0;
2341 virtual void exceptionEarlyReported() = 0;
2342 };
2343
2345}
2346
2347// end catch_interfaces_capture.h
2348namespace Catch {
2349
2351 struct AssertionResultData;
2352 struct IResultCapture;
2353 class RunContext;
2354
2356 friend class AssertionHandler;
2357 friend struct AssertionStats;
2358 friend class RunContext;
2359
2362 public:
2363 LazyExpression( bool isNegated );
2366
2367 explicit operator bool() const;
2368
2369 friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
2370 };
2371
2373 bool shouldDebugBreak = false;
2374 bool shouldThrow = false;
2375 };
2376
2380 bool m_completed = false;
2382
2383 public:
2385 ( StringRef const& macroName,
2386 SourceLineInfo const& lineInfo,
2387 StringRef capturedExpression,
2388 ResultDisposition::Flags resultDisposition );
2394
2395 template<typename T>
2396 void handleExpr( ExprLhs<T> const& expr ) {
2397 handleExpr( expr.makeUnaryExpr() );
2398 }
2400
2401 void handleMessage(ResultWas::OfType resultType, StringRef const& message);
2402
2408
2409 void complete();
2411
2412 // query
2413 auto allowThrows() const -> bool;
2414 };
2415
2416 void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
2417
2418} // namespace Catch
2419
2420// end catch_assertionhandler.h
2421// start catch_message.h
2422
2423#include <string>
2424#include <vector>
2425
2426namespace Catch {
2427
2429 MessageInfo( StringRef const& _macroName,
2430 SourceLineInfo const& _lineInfo,
2431 ResultWas::OfType _type );
2432
2437 unsigned int sequence;
2438
2439 bool operator == ( MessageInfo const& other ) const;
2440 bool operator < ( MessageInfo const& other ) const;
2441 private:
2442 static unsigned int globalCount;
2443 };
2444
2446
2447 template<typename T>
2449 m_stream << value;
2450 return *this;
2451 }
2452
2454 };
2455
2457 MessageBuilder( StringRef const& macroName,
2458 SourceLineInfo const& lineInfo,
2460
2461 template<typename T>
2463 m_stream << value;
2464 return *this;
2465 }
2466
2468 };
2469
2471 public:
2472 explicit ScopedMessage( MessageBuilder const& builder );
2473 ScopedMessage( ScopedMessage& duplicate ) = delete;
2476
2479 };
2480
2481 class Capturer {
2483 IResultCapture& m_resultCapture = getResultCapture();
2484 size_t m_captured = 0;
2485 public:
2486 Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
2488
2489 void captureValue( size_t index, std::string const& value );
2490
2491 template<typename T>
2492 void captureValues( size_t index, T const& value ) {
2493 captureValue( index, Catch::Detail::stringify( value ) );
2494 }
2495
2496 template<typename T, typename... Ts>
2497 void captureValues( size_t index, T const& value, Ts const&... values ) {
2498 captureValue( index, Catch::Detail::stringify(value) );
2499 captureValues( index+1, values... );
2500 }
2501 };
2502
2503} // end namespace Catch
2504
2505// end catch_message.h
2506#if !defined(CATCH_CONFIG_DISABLE)
2507
2508#if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
2509 #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
2510#else
2511 #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
2512#endif
2513
2514#if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
2515
2516///////////////////////////////////////////////////////////////////////////////
2517// Another way to speed-up compilation is to omit local try-catch for REQUIRE*
2518// macros.
2519#define INTERNAL_CATCH_TRY
2520#define INTERNAL_CATCH_CATCH( capturer )
2521
2522#else // CATCH_CONFIG_FAST_COMPILE
2523
2524#define INTERNAL_CATCH_TRY try
2525#define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
2526
2527#endif
2528
2529#define INTERNAL_CATCH_REACT( handler ) handler.complete();
2530
2531///////////////////////////////////////////////////////////////////////////////
2532#define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
2533 do { \
2534 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2535 INTERNAL_CATCH_TRY { \
2536 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
2537 catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
2538 CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
2539 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
2540 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2541 } while( (void)0, (false) && static_cast<bool>( !!(__VA_ARGS__) ) ) // the expression here is never evaluated at runtime but it forces the compiler to give it a look
2542 // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
2543
2544///////////////////////////////////////////////////////////////////////////////
2545#define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
2546 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2547 if( Catch::getResultCapture().lastAssertionPassed() )
2548
2549///////////////////////////////////////////////////////////////////////////////
2550#define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
2551 INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
2552 if( !Catch::getResultCapture().lastAssertionPassed() )
2553
2554///////////////////////////////////////////////////////////////////////////////
2555#define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
2556 do { \
2557 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
2558 try { \
2559 static_cast<void>(__VA_ARGS__); \
2560 catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
2561 } \
2562 catch( ... ) { \
2563 catchAssertionHandler.handleUnexpectedInflightException(); \
2564 } \
2565 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2566 } while( false )
2567
2568///////////////////////////////////////////////////////////////////////////////
2569#define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
2570 do { \
2571 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
2572 if( catchAssertionHandler.allowThrows() ) \
2573 try { \
2574 static_cast<void>(__VA_ARGS__); \
2575 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2576 } \
2577 catch( ... ) { \
2578 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2579 } \
2580 else \
2581 catchAssertionHandler.handleThrowingCallSkipped(); \
2582 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2583 } while( false )
2584
2585///////////////////////////////////////////////////////////////////////////////
2586#define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
2587 do { \
2588 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
2589 if( catchAssertionHandler.allowThrows() ) \
2590 try { \
2591 static_cast<void>(expr); \
2592 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2593 } \
2594 catch( exceptionType const& ) { \
2595 catchAssertionHandler.handleExceptionThrownAsExpected(); \
2596 } \
2597 catch( ... ) { \
2598 catchAssertionHandler.handleUnexpectedInflightException(); \
2599 } \
2600 else \
2601 catchAssertionHandler.handleThrowingCallSkipped(); \
2602 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2603 } while( false )
2604
2605///////////////////////////////////////////////////////////////////////////////
2606#define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
2607 do { \
2608 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
2609 catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
2610 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2611 } while( false )
2612
2613///////////////////////////////////////////////////////////////////////////////
2614#define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
2615 auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
2616 varName.captureValues( 0, __VA_ARGS__ )
2617
2618///////////////////////////////////////////////////////////////////////////////
2619#define INTERNAL_CATCH_INFO( macroName, log ) \
2620 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
2621
2622///////////////////////////////////////////////////////////////////////////////
2623#define INTERNAL_CATCH_UNSCOPED_INFO( macroName, log ) \
2624 Catch::getResultCapture().emplaceUnscopedMessage( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log )
2625
2626///////////////////////////////////////////////////////////////////////////////
2627// Although this is matcher-based, it can be used with just a string
2628#define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
2629 do { \
2630 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
2631 if( catchAssertionHandler.allowThrows() ) \
2632 try { \
2633 static_cast<void>(__VA_ARGS__); \
2634 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
2635 } \
2636 catch( ... ) { \
2637 Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
2638 } \
2639 else \
2640 catchAssertionHandler.handleThrowingCallSkipped(); \
2641 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
2642 } while( false )
2643
2644#endif // CATCH_CONFIG_DISABLE
2645
2646// end catch_capture.hpp
2647// start catch_section.h
2648
2649// start catch_section_info.h
2650
2651// start catch_totals.h
2652
2653#include <cstddef>
2654
2655namespace Catch {
2656
2657 struct Counts {
2658 Counts operator - ( Counts const& other ) const;
2659 Counts& operator += ( Counts const& other );
2660
2662 bool allPassed() const;
2663 bool allOk() const;
2664
2665 std::size_t passed = 0;
2666 std::size_t failed = 0;
2667 std::size_t failedButOk = 0;
2668 };
2669
2670 struct Totals {
2671
2672 Totals operator - ( Totals const& other ) const;
2673 Totals& operator += ( Totals const& other );
2674
2675 Totals delta( Totals const& prevTotals ) const;
2676
2677 int error = 0;
2680 };
2681}
2682
2683// end catch_totals.h
2684#include <string>
2685
2686namespace Catch {
2687
2690 ( SourceLineInfo const& _lineInfo,
2691 std::string const& _name );
2692
2693 // Deprecated
2695 ( SourceLineInfo const& _lineInfo,
2696 std::string const& _name,
2697 std::string const& ) : SectionInfo( _lineInfo, _name ) {}
2698
2700 std::string description; // !Deprecated: this will always be empty
2702 };
2703
2709
2710} // end namespace Catch
2711
2712// end catch_section_info.h
2713// start catch_timer.h
2714
2715#include <cstdint>
2716
2717namespace Catch {
2718
2721
2722 class Timer {
2723 uint64_t m_nanoseconds = 0;
2724 public:
2725 void start();
2726 auto getElapsedNanoseconds() const -> uint64_t;
2727 auto getElapsedMicroseconds() const -> uint64_t;
2728 auto getElapsedMilliseconds() const -> unsigned int;
2729 auto getElapsedSeconds() const -> double;
2730 };
2731
2732} // namespace Catch
2733
2734// end catch_timer.h
2735#include <string>
2736
2737namespace Catch {
2738
2740 public:
2741 Section( SectionInfo const& info );
2743
2744 // This indicates whether the section should be executed or not
2745 explicit operator bool() const;
2746
2747 private:
2749
2754 };
2755
2756} // end namespace Catch
2757
2758#define INTERNAL_CATCH_SECTION( ... ) \
2759 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2760 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
2761 CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
2762
2763#define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
2764 CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
2765 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
2766 CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
2767
2768// end catch_section.h
2769// start catch_benchmark.h
2770
2771#include <cstdint>
2772#include <string>
2773
2774namespace Catch {
2775
2777
2779 std::size_t m_count = 0;
2780 std::size_t m_iterationsToRun = 1;
2783
2784 static auto getResolution() -> uint64_t;
2785 public:
2786 // Keep most of this inline as it's on the code path that is being timed
2788 : m_name( name ),
2789 m_resolution( getResolution() )
2790 {
2791 reportStart();
2792 m_timer.start();
2793 }
2794
2795 explicit operator bool() {
2796 if( m_count < m_iterationsToRun )
2797 return true;
2798 return needsMoreIterations();
2799 }
2800
2801 void increment() {
2802 ++m_count;
2803 }
2804
2807 };
2808
2809} // end namespace Catch
2810
2811#define BENCHMARK( name ) \
2812 for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )
2813
2814// end catch_benchmark.h
2815// start catch_interfaces_exception.h
2816
2817// start catch_interfaces_registry_hub.h
2818
2819#include <string>
2820#include <memory>
2821
2822namespace Catch {
2823
2824 class TestCase;
2825 struct ITestCaseRegistry;
2826 struct IExceptionTranslatorRegistry;
2827 struct IExceptionTranslator;
2828 struct IReporterRegistry;
2829 struct IReporterFactory;
2830 struct ITagAliasRegistry;
2831 struct IMutableEnumValuesRegistry;
2832
2833 class StartupExceptionRegistry;
2834
2836
2838 virtual ~IRegistryHub();
2839
2840 virtual IReporterRegistry const& getReporterRegistry() const = 0;
2841 virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
2842 virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
2844
2845 virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
2846 };
2847
2850 virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
2851 virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
2852 virtual void registerTest( TestCase const& testInfo ) = 0;
2853 virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
2854 virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
2855 virtual void registerStartupException() noexcept = 0;
2856 virtual IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() = 0;
2857 };
2858
2859 IRegistryHub const& getRegistryHub();
2860 IMutableRegistryHub& getMutableRegistryHub();
2861 void cleanUp();
2862 std::string translateActiveException();
2863
2864}
2865
2866// end catch_interfaces_registry_hub.h
2867#if defined(CATCH_CONFIG_DISABLE)
2868 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
2869 static std::string translatorName( signature )
2870#endif
2871
2872#include <exception>
2873#include <string>
2874#include <vector>
2875
2876namespace Catch {
2878
2879 struct IExceptionTranslator;
2881
2884 virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
2885 };
2886
2892
2894 template<typename T>
2896 public:
2897
2898 ExceptionTranslator( std::string(*translateFunction)( T& ) )
2899 : m_translateFunction( translateFunction )
2900 {}
2901
2902 std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
2903 try {
2904 if( it == itEnd )
2906 else
2907 return (*it)->translate( it+1, itEnd );
2908 }
2909 catch( T& ex ) {
2910 return m_translateFunction( ex );
2911 }
2912 }
2913
2914 protected:
2915 std::string(*m_translateFunction)( T& );
2916 };
2917
2918 public:
2919 template<typename T>
2920 ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
2922 ( new ExceptionTranslator<T>( translateFunction ) );
2923 }
2924 };
2925}
2926
2927///////////////////////////////////////////////////////////////////////////////
2928#define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
2929 static std::string translatorName( signature ); \
2930 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
2931 namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
2932 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
2933 static std::string translatorName( signature )
2934
2935#define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
2936
2937// end catch_interfaces_exception.h
2938// start catch_approx.h
2939
2940#include <type_traits>
2941
2942namespace Catch {
2943namespace Detail {
2944
2945 class Approx {
2946 private:
2947 bool equalityComparisonImpl(double other) const;
2948 // Validates the new margin (margin >= 0)
2949 // out-of-line to avoid including stdexcept in the header
2950 void setMargin(double margin);
2951 // Validates the new epsilon (0 < epsilon < 1)
2952 // out-of-line to avoid including stdexcept in the header
2953 void setEpsilon(double epsilon);
2954
2955 public:
2956 explicit Approx ( double value );
2957
2958 static Approx custom();
2959
2961
2962 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2964 Approx approx( static_cast<double>(value) );
2965 approx.m_epsilon = m_epsilon;
2966 approx.m_margin = m_margin;
2967 approx.m_scale = m_scale;
2968 return approx;
2969 }
2970
2971 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2972 explicit Approx( T const& value ): Approx(static_cast<double>(value))
2973 {}
2974
2975 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2976 friend bool operator == ( const T& lhs, Approx const& rhs ) {
2977 auto lhs_v = static_cast<double>(lhs);
2978 return rhs.equalityComparisonImpl(lhs_v);
2979 }
2980
2981 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2982 friend bool operator == ( Approx const& lhs, const T& rhs ) {
2983 return operator==( rhs, lhs );
2984 }
2985
2986 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2987 friend bool operator != ( T const& lhs, Approx const& rhs ) {
2988 return !operator==( lhs, rhs );
2989 }
2990
2991 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2992 friend bool operator != ( Approx const& lhs, T const& rhs ) {
2993 return !operator==( rhs, lhs );
2994 }
2995
2996 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2997 friend bool operator <= ( T const& lhs, Approx const& rhs ) {
2998 return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
2999 }
3000
3001 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3002 friend bool operator <= ( Approx const& lhs, T const& rhs ) {
3003 return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
3004 }
3005
3006 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3007 friend bool operator >= ( T const& lhs, Approx const& rhs ) {
3008 return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
3009 }
3010
3011 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3012 friend bool operator >= ( Approx const& lhs, T const& rhs ) {
3013 return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
3014 }
3015
3016 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3017 Approx& epsilon( T const& newEpsilon ) {
3018 double epsilonAsDouble = static_cast<double>(newEpsilon);
3019 setEpsilon(epsilonAsDouble);
3020 return *this;
3021 }
3022
3023 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3024 Approx& margin( T const& newMargin ) {
3025 double marginAsDouble = static_cast<double>(newMargin);
3026 setMargin(marginAsDouble);
3027 return *this;
3028 }
3029
3030 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3031 Approx& scale( T const& newScale ) {
3032 m_scale = static_cast<double>(newScale);
3033 return *this;
3034 }
3035
3037
3038 private:
3040 double m_margin;
3041 double m_scale;
3042 double m_value;
3043 };
3044} // end namespace Detail
3045
3046namespace literals {
3047 Detail::Approx operator "" _a(long double val);
3048 Detail::Approx operator "" _a(unsigned long long val);
3049} // end namespace literals
3050
3051template<>
3055
3056} // end namespace Catch
3057
3058// end catch_approx.h
3059// start catch_string_manip.h
3060
3061#include <string>
3062#include <iosfwd>
3063#include <vector>
3064
3065namespace Catch {
3066
3067 bool startsWith( std::string const& s, std::string const& prefix );
3068 bool startsWith( std::string const& s, char prefix );
3069 bool endsWith( std::string const& s, std::string const& suffix );
3070 bool endsWith( std::string const& s, char suffix );
3071 bool contains( std::string const& s, std::string const& infix );
3075
3076 // !!! Be aware, returns refs into original string - make sure original string outlives them
3078 bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
3079
3088}
3089
3090// end catch_string_manip.h
3091#ifndef CATCH_CONFIG_DISABLE_MATCHERS
3092// start catch_capture_matchers.h
3093
3094// start catch_matchers.h
3095
3096#include <string>
3097#include <vector>
3098
3099namespace Catch {
3100namespace Matchers {
3101 namespace Impl {
3102
3103 template<typename ArgT> struct MatchAllOf;
3104 template<typename ArgT> struct MatchAnyOf;
3105 template<typename ArgT> struct MatchNotOf;
3106
3108 public:
3111 MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
3113
3114 protected:
3116 virtual std::string describe() const = 0;
3118 };
3119
3120#ifdef __clang__
3121# pragma clang diagnostic push
3122# pragma clang diagnostic ignored "-Wnon-virtual-dtor"
3123#endif
3124
3125 template<typename ObjectT>
3127 virtual bool match( ObjectT const& arg ) const = 0;
3128 };
3129
3130#ifdef __clang__
3131# pragma clang diagnostic pop
3132#endif
3133
3134 template<typename T>
3136
3137 MatchAllOf<T> operator && ( MatcherBase const& other ) const;
3138 MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
3139 MatchNotOf<T> operator ! () const;
3140 };
3141
3142 template<typename ArgT>
3143 struct MatchAllOf : MatcherBase<ArgT> {
3144 bool match( ArgT const& arg ) const override {
3145 for( auto matcher : m_matchers ) {
3146 if (!matcher->match(arg))
3147 return false;
3148 }
3149 return true;
3150 }
3151 std::string describe() const override {
3152 std::string description;
3153 description.reserve( 4 + m_matchers.size()*32 );
3154 description += "( ";
3155 bool first = true;
3156 for( auto matcher : m_matchers ) {
3157 if( first )
3158 first = false;
3159 else
3160 description += " and ";
3161 description += matcher->toString();
3162 }
3163 description += " )";
3164 return description;
3165 }
3166
3167 MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
3168 m_matchers.push_back( &other );
3169 return *this;
3170 }
3171
3173 };
3174 template<typename ArgT>
3175 struct MatchAnyOf : MatcherBase<ArgT> {
3176
3177 bool match( ArgT const& arg ) const override {
3178 for( auto matcher : m_matchers ) {
3179 if (matcher->match(arg))
3180 return true;
3181 }
3182 return false;
3183 }
3184 std::string describe() const override {
3185 std::string description;
3186 description.reserve( 4 + m_matchers.size()*32 );
3187 description += "( ";
3188 bool first = true;
3189 for( auto matcher : m_matchers ) {
3190 if( first )
3191 first = false;
3192 else
3193 description += " or ";
3194 description += matcher->toString();
3195 }
3196 description += " )";
3197 return description;
3198 }
3199
3200 MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
3201 m_matchers.push_back( &other );
3202 return *this;
3203 }
3204
3206 };
3207
3208 template<typename ArgT>
3209 struct MatchNotOf : MatcherBase<ArgT> {
3210
3211 MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
3212
3213 bool match( ArgT const& arg ) const override {
3214 return !m_underlyingMatcher.match( arg );
3215 }
3216
3217 std::string describe() const override {
3218 return "not " + m_underlyingMatcher.toString();
3219 }
3221 };
3222
3223 template<typename T>
3225 return MatchAllOf<T>() && *this && other;
3226 }
3227 template<typename T>
3229 return MatchAnyOf<T>() || *this || other;
3230 }
3231 template<typename T>
3233 return MatchNotOf<T>( *this );
3234 }
3235
3236 } // namespace Impl
3237
3238} // namespace Matchers
3239
3240using namespace Matchers;
3242
3243} // namespace Catch
3244
3245// end catch_matchers.h
3246// start catch_matchers_floating.h
3247
3248#include <type_traits>
3249#include <cmath>
3250
3251namespace Catch {
3252namespace Matchers {
3253
3254 namespace Floating {
3255
3256 enum class FloatingPointKind : uint8_t;
3257
3259 WithinAbsMatcher(double target, double margin);
3260 bool match(double const& matchee) const override;
3261 std::string describe() const override;
3262 private:
3263 double m_target;
3264 double m_margin;
3265 };
3266
3268 WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
3269 bool match(double const& matchee) const override;
3270 std::string describe() const override;
3271 private:
3272 double m_target;
3274 FloatingPointKind m_type;
3275 };
3276
3277 } // namespace Floating
3278
3279 // The following functions create the actual matcher objects.
3280 // This allows the types to be inferred
3281 Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
3282 Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
3283 Floating::WithinAbsMatcher WithinAbs(double target, double margin);
3284
3285} // namespace Matchers
3286} // namespace Catch
3287
3288// end catch_matchers_floating.h
3289// start catch_matchers_generic.hpp
3290
3291#include <functional>
3292#include <string>
3293
3294namespace Catch {
3295namespace Matchers {
3296namespace Generic {
3297
3298namespace Detail {
3300}
3301
3302template <typename T>
3306public:
3307
3308 PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
3309 :m_predicate(std::move(elem)),
3310 m_description(Detail::finalizeDescription(descr))
3311 {}
3312
3313 bool match( T const& item ) const override {
3314 return m_predicate(item);
3315 }
3316
3317 std::string describe() const override {
3318 return m_description;
3319 }
3320};
3321
3322} // namespace Generic
3323
3324 // The following functions create the actual matcher objects.
3325 // The user has to explicitly specify type to the function, because
3326 // inferring std::function<bool(T const&)> is hard (but possible) and
3327 // requires a lot of TMP.
3328 template<typename T>
3329 Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
3330 return Generic::PredicateMatcher<T>(predicate, description);
3331 }
3332
3333} // namespace Matchers
3334} // namespace Catch
3335
3336// end catch_matchers_generic.hpp
3337// start catch_matchers_string.h
3338
3339#include <string>
3340
3341namespace Catch {
3342namespace Matchers {
3343
3344 namespace StdString {
3345
3355
3356 struct StringMatcherBase : MatcherBase<std::string> {
3357 StringMatcherBase( std::string const& operation, CasedString const& comparator );
3358 std::string describe() const override;
3359
3362 };
3363
3365 EqualsMatcher( CasedString const& comparator );
3366 bool match( std::string const& source ) const override;
3367 };
3369 ContainsMatcher( CasedString const& comparator );
3370 bool match( std::string const& source ) const override;
3371 };
3373 StartsWithMatcher( CasedString const& comparator );
3374 bool match( std::string const& source ) const override;
3375 };
3377 EndsWithMatcher( CasedString const& comparator );
3378 bool match( std::string const& source ) const override;
3379 };
3380
3381 struct RegexMatcher : MatcherBase<std::string> {
3383 bool match( std::string const& matchee ) const override;
3384 std::string describe() const override;
3385
3386 private:
3389 };
3390
3391 } // namespace StdString
3392
3393 // The following functions create the actual matcher objects.
3394 // This allows the types to be inferred
3395
3396 StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3397 StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3398 StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3399 StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3400 StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3401
3402} // namespace Matchers
3403} // namespace Catch
3404
3405// end catch_matchers_string.h
3406// start catch_matchers_vector.h
3407
3408#include <algorithm>
3409
3410namespace Catch {
3411namespace Matchers {
3412
3413 namespace Vector {
3414 template<typename T>
3415 struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
3416
3417 ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
3418
3419 bool match(std::vector<T> const &v) const override {
3420 for (auto const& el : v) {
3421 if (el == m_comparator) {
3422 return true;
3423 }
3424 }
3425 return false;
3426 }
3427
3428 std::string describe() const override {
3429 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3430 }
3431
3433 };
3434
3435 template<typename T>
3436 struct ContainsMatcher : MatcherBase<std::vector<T>> {
3437
3438 ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
3439
3440 bool match(std::vector<T> const &v) const override {
3441 // !TBD: see note in EqualsMatcher
3442 if (m_comparator.size() > v.size())
3443 return false;
3444 for (auto const& comparator : m_comparator) {
3445 auto present = false;
3446 for (const auto& el : v) {
3447 if (el == comparator) {
3448 present = true;
3449 break;
3450 }
3451 }
3452 if (!present) {
3453 return false;
3454 }
3455 }
3456 return true;
3457 }
3458 std::string describe() const override {
3459 return "Contains: " + ::Catch::Detail::stringify( m_comparator );
3460 }
3461
3463 };
3464
3465 template<typename T>
3466 struct EqualsMatcher : MatcherBase<std::vector<T>> {
3467
3468 EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
3469
3470 bool match(std::vector<T> const &v) const override {
3471 // !TBD: This currently works if all elements can be compared using !=
3472 // - a more general approach would be via a compare template that defaults
3473 // to using !=. but could be specialised for, e.g. std::vector<T> etc
3474 // - then just call that directly
3475 if (m_comparator.size() != v.size())
3476 return false;
3477 for (std::size_t i = 0; i < v.size(); ++i)
3478 if (m_comparator[i] != v[i])
3479 return false;
3480 return true;
3481 }
3482 std::string describe() const override {
3483 return "Equals: " + ::Catch::Detail::stringify( m_comparator );
3484 }
3486 };
3487
3488 template<typename T>
3489 struct ApproxMatcher : MatcherBase<std::vector<T>> {
3490
3491 ApproxMatcher(std::vector<T> const& comparator) : m_comparator( comparator ) {}
3492
3493 bool match(std::vector<T> const &v) const override {
3494 if (m_comparator.size() != v.size())
3495 return false;
3496 for (std::size_t i = 0; i < v.size(); ++i)
3497 if (m_comparator[i] != approx(v[i]))
3498 return false;
3499 return true;
3500 }
3501 std::string describe() const override {
3502 return "is approx: " + ::Catch::Detail::stringify( m_comparator );
3503 }
3504 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3505 ApproxMatcher& epsilon( T const& newEpsilon ) {
3506 approx.epsilon(newEpsilon);
3507 return *this;
3508 }
3509 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3510 ApproxMatcher& margin( T const& newMargin ) {
3511 approx.margin(newMargin);
3512 return *this;
3513 }
3514 template <typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
3515 ApproxMatcher& scale( T const& newScale ) {
3516 approx.scale(newScale);
3517 return *this;
3518 }
3519
3522 };
3523
3524 template<typename T>
3525 struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
3526 UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
3527 bool match(std::vector<T> const& vec) const override {
3528 // Note: This is a reimplementation of std::is_permutation,
3529 // because I don't want to include <algorithm> inside the common path
3530 if (m_target.size() != vec.size()) {
3531 return false;
3532 }
3533 return std::is_permutation(m_target.begin(), m_target.end(), vec.begin());
3534 }
3535
3536 std::string describe() const override {
3537 return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
3538 }
3539 private:
3541 };
3542
3543 } // namespace Vector
3544
3545 // The following functions create the actual matcher objects.
3546 // This allows the types to be inferred
3547
3548 template<typename T>
3550 return Vector::ContainsMatcher<T>( comparator );
3551 }
3552
3553 template<typename T>
3555 return Vector::ContainsElementMatcher<T>( comparator );
3556 }
3557
3558 template<typename T>
3560 return Vector::EqualsMatcher<T>( comparator );
3561 }
3562
3563 template<typename T>
3565 return Vector::ApproxMatcher<T>( comparator );
3566 }
3567
3568 template<typename T>
3572
3573} // namespace Matchers
3574} // namespace Catch
3575
3576// end catch_matchers_vector.h
3577namespace Catch {
3578
3579 template<typename ArgT, typename MatcherT>
3581 ArgT const& m_arg;
3582 MatcherT m_matcher;
3584 public:
3585 MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
3586 : ITransientExpression{ true, matcher.match( arg ) },
3587 m_arg( arg ),
3588 m_matcher( matcher ),
3589 m_matcherString( matcherString )
3590 {}
3591
3592 void streamReconstructedExpression( std::ostream &os ) const override {
3593 auto matcherAsString = m_matcher.toString();
3594 os << Catch::Detail::stringify( m_arg ) << ' ';
3595 if( matcherAsString == Detail::unprintableString )
3596 os << m_matcherString;
3597 else
3598 os << matcherAsString;
3599 }
3600 };
3601
3603
3604 void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
3605
3606 template<typename ArgT, typename MatcherT>
3607 auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
3608 return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
3609 }
3610
3611} // namespace Catch
3612
3613///////////////////////////////////////////////////////////////////////////////
3614#define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
3615 do { \
3616 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3617 INTERNAL_CATCH_TRY { \
3618 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
3619 } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
3620 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3621 } while( false )
3622
3623///////////////////////////////////////////////////////////////////////////////
3624#define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
3625 do { \
3626 Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
3627 if( catchAssertionHandler.allowThrows() ) \
3628 try { \
3629 static_cast<void>(__VA_ARGS__ ); \
3630 catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
3631 } \
3632 catch( exceptionType const& ex ) { \
3633 catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
3634 } \
3635 catch( ... ) { \
3636 catchAssertionHandler.handleUnexpectedInflightException(); \
3637 } \
3638 else \
3639 catchAssertionHandler.handleThrowingCallSkipped(); \
3640 INTERNAL_CATCH_REACT( catchAssertionHandler ) \
3641 } while( false )
3642
3643// end catch_capture_matchers.h
3644#endif
3645// start catch_generators.hpp
3646
3647// start catch_interfaces_generatortracker.h
3648
3649
3650#include <memory>
3651
3652namespace Catch {
3653
3654 namespace Generators {
3656 public:
3659 // Attempts to move the generator to the next element
3660 //
3661 // Returns true iff the move succeeded (and a valid element
3662 // can be retrieved).
3663 virtual bool next() = 0;
3664 };
3666
3667 } // namespace Generators
3668
3671 virtual auto hasGenerator() const -> bool = 0;
3672 virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
3673 virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
3674 };
3675
3676} // namespace Catch
3677
3678// end catch_interfaces_generatortracker.h
3679// start catch_enforce.h
3680
3681#include <stdexcept>
3682
3683namespace Catch {
3684#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
3685 template <typename Ex>
3686 [[noreturn]]
3687 void throw_exception(Ex const& e) {
3688 throw e;
3689 }
3690#else // ^^ Exceptions are enabled // Exceptions are disabled vv
3691 [[noreturn]]
3693#endif
3694} // namespace Catch;
3695
3696#define CATCH_PREPARE_EXCEPTION( type, msg ) \
3697 type( ( Catch::ReusableStringStream() << msg ).str() )
3698#define CATCH_INTERNAL_ERROR( msg ) \
3699 Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg))
3700#define CATCH_ERROR( msg ) \
3701 Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::domain_error, msg ))
3702#define CATCH_RUNTIME_ERROR( msg ) \
3703 Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::runtime_error, msg ))
3704#define CATCH_ENFORCE( condition, msg ) \
3705 do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
3706
3707// end catch_enforce.h
3708#include <memory>
3709#include <vector>
3710#include <cassert>
3711
3712#include <utility>
3713#include <exception>
3714
3715namespace Catch {
3716
3718 const char* const m_msg = "";
3719
3720public:
3721 GeneratorException(const char* msg):
3722 m_msg(msg)
3723 {}
3724
3725 const char* what() const noexcept override final;
3726};
3727
3728namespace Generators {
3729
3730 // !TBD move this into its own location?
3731 namespace pf{
3732 template<typename T, typename... Args>
3733 std::unique_ptr<T> make_unique( Args&&... args ) {
3734 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
3735 }
3736 }
3737
3738 template<typename T>
3740 virtual ~IGenerator() = default;
3741
3742 // Returns the current element of the generator
3743 //
3744 // \Precondition The generator is either freshly constructed,
3745 // or the last call to `next()` returned true
3746 virtual T const& get() const = 0;
3747 using type = T;
3748 };
3749
3750 template<typename T>
3751 class SingleValueGenerator final : public IGenerator<T> {
3753 public:
3754 SingleValueGenerator(T const& value) : m_value( value ) {}
3755 SingleValueGenerator(T&& value) : m_value(std::move(value)) {}
3756
3757 T const& get() const override {
3758 return m_value;
3759 }
3760 bool next() override {
3761 return false;
3762 }
3763 };
3764
3765 template<typename T>
3766 class FixedValuesGenerator final : public IGenerator<T> {
3768 size_t m_idx = 0;
3769 public:
3771
3772 T const& get() const override {
3773 return m_values[m_idx];
3774 }
3775 bool next() override {
3776 ++m_idx;
3777 return m_idx < m_values.size();
3778 }
3779 };
3780
3781 template <typename T>
3782 class GeneratorWrapper final {
3784 public:
3786 m_generator(std::move(generator))
3787 {}
3788 T const& get() const {
3789 return m_generator->get();
3790 }
3791 bool next() {
3792 return m_generator->next();
3793 }
3794 };
3795
3796 template <typename T>
3800 template <typename T>
3804
3805 template<typename T>
3806 class Generators : public IGenerator<T> {
3808 size_t m_current = 0;
3809
3810 void populate(GeneratorWrapper<T>&& generator) {
3811 m_generators.emplace_back(std::move(generator));
3812 }
3813 void populate(T&& val) {
3814 m_generators.emplace_back(value(std::move(val)));
3815 }
3816 template<typename U>
3817 void populate(U&& val) {
3818 populate(T(std::move(val)));
3819 }
3820 template<typename U, typename... Gs>
3821 void populate(U&& valueOrGenerator, Gs... moreGenerators) {
3822 populate(std::forward<U>(valueOrGenerator));
3823 populate(std::forward<Gs>(moreGenerators)...);
3824 }
3825
3826 public:
3827 template <typename... Gs>
3828 Generators(Gs... moreGenerators) {
3829 m_generators.reserve(sizeof...(Gs));
3830 populate(std::forward<Gs>(moreGenerators)...);
3831 }
3832
3833 T const& get() const override {
3834 return m_generators[m_current].get();
3835 }
3836
3837 bool next() override {
3838 if (m_current >= m_generators.size()) {
3839 return false;
3840 }
3841 const bool current_status = m_generators[m_current].next();
3842 if (!current_status) {
3843 ++m_current;
3844 }
3845 return m_current < m_generators.size();
3846 }
3847 };
3848
3849 template<typename... Ts>
3851 return values<std::tuple<Ts...>>( tuples );
3852 }
3853
3854 // Tag type to signal that a generator sequence should convert arguments to a specific type
3855 template <typename T>
3856 struct as {};
3857
3858 template<typename T, typename... Gs>
3859 auto makeGenerators( GeneratorWrapper<T>&& generator, Gs... moreGenerators ) -> Generators<T> {
3860 return Generators<T>(std::move(generator), std::forward<Gs>(moreGenerators)...);
3861 }
3862 template<typename T>
3864 return Generators<T>(std::move(generator));
3865 }
3866 template<typename T, typename... Gs>
3867 auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators<T> {
3868 return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
3869 }
3870 template<typename T, typename U, typename... Gs>
3871 auto makeGenerators( as<T>, U&& val, Gs... moreGenerators ) -> Generators<T> {
3872 return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
3873 }
3874
3876
3877 template<typename L>
3878 // Note: The type after -> is weird, because VS2015 cannot parse
3879 // the expression used in the typedef inside, when it is in
3880 // return type. Yeah.
3881 auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>().get()) {
3882 using UnderlyingType = typename decltype(generatorExpression())::type;
3883
3884 IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo );
3885 if (!tracker.hasGenerator()) {
3886 tracker.setGenerator(pf::make_unique<Generators<UnderlyingType>>(generatorExpression()));
3887 }
3888
3889 auto const& generator = static_cast<IGenerator<UnderlyingType> const&>( *tracker.getGenerator() );
3890 return generator.get();
3891 }
3892
3893} // namespace Generators
3894} // namespace Catch
3895
3896#define GENERATE( ... ) \
3897 Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [ ]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
3898#define GENERATE_COPY( ... ) \
3899 Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [=]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
3900#define GENERATE_REF( ... ) \
3901 Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, [&]{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
3902
3903// end catch_generators.hpp
3904// start catch_generators_generic.hpp
3905
3906namespace Catch {
3907namespace Generators {
3908
3909 template <typename T>
3910 class TakeGenerator : public IGenerator<T> {
3912 size_t m_returned = 0;
3913 size_t m_target;
3914 public:
3915 TakeGenerator(size_t target, GeneratorWrapper<T>&& generator):
3916 m_generator(std::move(generator)),
3917 m_target(target)
3918 {
3919 assert(target != 0 && "Empty generators are not allowed");
3920 }
3921 T const& get() const override {
3922 return m_generator.get();
3923 }
3924 bool next() override {
3925 ++m_returned;
3926 if (m_returned >= m_target) {
3927 return false;
3928 }
3929
3930 const auto success = m_generator.next();
3931 // If the underlying generator does not contain enough values
3932 // then we cut short as well
3933 if (!success) {
3934 m_returned = m_target;
3935 }
3936 return success;
3937 }
3938 };
3939
3940 template <typename T>
3941 GeneratorWrapper<T> take(size_t target, GeneratorWrapper<T>&& generator) {
3942 return GeneratorWrapper<T>(pf::make_unique<TakeGenerator<T>>(target, std::move(generator)));
3943 }
3944
3945 template <typename T, typename Predicate>
3946 class FilterGenerator : public IGenerator<T> {
3949 public:
3950 template <typename P = Predicate>
3951 FilterGenerator(P&& pred, GeneratorWrapper<T>&& generator):
3952 m_generator(std::move(generator)),
3953 m_predicate(std::forward<P>(pred))
3954 {
3955 if (!m_predicate(m_generator.get())) {
3956 // It might happen that there are no values that pass the
3957 // filter. In that case we throw an exception.
3958 auto has_initial_value = next();
3959 if (!has_initial_value) {
3960 Catch::throw_exception(GeneratorException("No valid value found in filtered generator"));
3961 }
3962 }
3963 }
3964
3965 T const& get() const override {
3966 return m_generator.get();
3967 }
3968
3969 bool next() override {
3970 bool success = m_generator.next();
3971 if (!success) {
3972 return false;
3973 }
3974 while (!m_predicate(m_generator.get()) && (success = m_generator.next()) == true);
3975 return success;
3976 }
3977 };
3978
3979 template <typename T, typename Predicate>
3980 GeneratorWrapper<T> filter(Predicate&& pred, GeneratorWrapper<T>&& generator) {
3981 return GeneratorWrapper<T>(std::unique_ptr<IGenerator<T>>(pf::make_unique<FilterGenerator<T, Predicate>>(std::forward<Predicate>(pred), std::move(generator))));
3982 }
3983
3984 template <typename T>
3985 class RepeatGenerator : public IGenerator<T> {
3989 size_t m_current_repeat = 0;
3990 size_t m_repeat_index = 0;
3991 public:
3992 RepeatGenerator(size_t repeats, GeneratorWrapper<T>&& generator):
3993 m_generator(std::move(generator)),
3994 m_target_repeats(repeats)
3995 {
3996 assert(m_target_repeats > 0 && "Repeat generator must repeat at least once");
3997 }
3998
3999 T const& get() const override {
4000 if (m_current_repeat == 0) {
4001 m_returned.push_back(m_generator.get());
4002 return m_returned.back();
4003 }
4004 return m_returned[m_repeat_index];
4005 }
4006
4007 bool next() override {
4008 // There are 2 basic cases:
4009 // 1) We are still reading the generator
4010 // 2) We are reading our own cache
4011
4012 // In the first case, we need to poke the underlying generator.
4013 // If it happily moves, we are left in that state, otherwise it is time to start reading from our cache
4014 if (m_current_repeat == 0) {
4015 const auto success = m_generator.next();
4016 if (!success) {
4017 ++m_current_repeat;
4018 }
4019 return m_current_repeat < m_target_repeats;
4020 }
4021
4022 // In the second case, we need to move indices forward and check that we haven't run up against the end
4023 ++m_repeat_index;
4024 if (m_repeat_index == m_returned.size()) {
4025 m_repeat_index = 0;
4026 ++m_current_repeat;
4027 }
4028 return m_current_repeat < m_target_repeats;
4029 }
4030 };
4031
4032 template <typename T>
4033 GeneratorWrapper<T> repeat(size_t repeats, GeneratorWrapper<T>&& generator) {
4034 return GeneratorWrapper<T>(pf::make_unique<RepeatGenerator<T>>(repeats, std::move(generator)));
4035 }
4036
4037 template <typename T, typename U, typename Func>
4038 class MapGenerator : public IGenerator<T> {
4039 // TBD: provide static assert for mapping function, for friendly error message
4042 // To avoid returning dangling reference, we have to save the values
4044 public:
4045 template <typename F2 = Func>
4046 MapGenerator(F2&& function, GeneratorWrapper<U>&& generator) :
4047 m_generator(std::move(generator)),
4048 m_function(std::forward<F2>(function)),
4049 m_cache(m_function(m_generator.get()))
4050 {}
4051
4052 T const& get() const override {
4053 return m_cache;
4054 }
4055 bool next() override {
4056 const auto success = m_generator.next();
4057 if (success) {
4058 m_cache = m_function(m_generator.get());
4059 }
4060 return success;
4061 }
4062 };
4063
4064#if defined(__cpp_lib_is_invocable) && __cpp_lib_is_invocable >= 201703
4065 // std::result_of is deprecated in C++17 and removed in C++20. Hence, it is
4066 // replaced with std::invoke_result here. Also *_t format is preferred over
4067 // typename *::type format.
4068 template <typename Func, typename U>
4070#else
4071 template <typename Func, typename U>
4073#endif
4074
4075 template <typename Func, typename U, typename T = MapFunctionReturnType<Func, U>>
4076 GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4077 return GeneratorWrapper<T>(
4078 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
4079 );
4080 }
4081
4082 template <typename T, typename U, typename Func>
4083 GeneratorWrapper<T> map(Func&& function, GeneratorWrapper<U>&& generator) {
4084 return GeneratorWrapper<T>(
4085 pf::make_unique<MapGenerator<T, U, Func>>(std::forward<Func>(function), std::move(generator))
4086 );
4087 }
4088
4089 template <typename T>
4090 class ChunkGenerator final : public IGenerator<std::vector<T>> {
4094 bool m_used_up = false;
4095 public:
4096 ChunkGenerator(size_t size, GeneratorWrapper<T> generator) :
4097 m_chunk_size(size), m_generator(std::move(generator))
4098 {
4099 m_chunk.reserve(m_chunk_size);
4100 m_chunk.push_back(m_generator.get());
4101 for (size_t i = 1; i < m_chunk_size; ++i) {
4102 if (!m_generator.next()) {
4103 Catch::throw_exception(GeneratorException("Not enough values to initialize the first chunk"));
4104 }
4105 m_chunk.push_back(m_generator.get());
4106 }
4107 }
4108 std::vector<T> const& get() const override {
4109 return m_chunk;
4110 }
4111 bool next() override {
4112 m_chunk.clear();
4113 for (size_t idx = 0; idx < m_chunk_size; ++idx) {
4114 if (!m_generator.next()) {
4115 return false;
4116 }
4117 m_chunk.push_back(m_generator.get());
4118 }
4119 return true;
4120 }
4121 };
4122
4123 template <typename T>
4126 pf::make_unique<ChunkGenerator<T>>(size, std::move(generator))
4127 );
4128 }
4129
4130} // namespace Generators
4131} // namespace Catch
4132
4133// end catch_generators_generic.hpp
4134// start catch_generators_specific.hpp
4135
4136// start catch_context.h
4137
4138#include <memory>
4139
4140namespace Catch {
4141
4142 struct IResultCapture;
4143 struct IRunner;
4144 struct IConfig;
4145 struct IMutableContext;
4146
4148
4150 {
4151 virtual ~IContext();
4152
4154 virtual IRunner* getRunner() = 0;
4155 virtual IConfigPtr const& getConfig() const = 0;
4156 };
4157
4159 {
4161 virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
4162 virtual void setRunner( IRunner* runner ) = 0;
4163 virtual void setConfig( IConfigPtr const& config ) = 0;
4164
4165 private:
4168 friend void cleanUpContext();
4169 static void createContext();
4170 };
4171
4173 {
4174 if( !IMutableContext::currentContext )
4175 IMutableContext::createContext();
4176 return *IMutableContext::currentContext;
4177 }
4178
4180 {
4181 return getCurrentMutableContext();
4182 }
4183
4185}
4186
4187// end catch_context.h
4188// start catch_interfaces_config.h
4189
4190#include <iosfwd>
4191#include <string>
4192#include <vector>
4193#include <memory>
4194
4195namespace Catch {
4196
4197 enum class Verbosity {
4198 Quiet = 0,
4199 Normal,
4200 High
4201 };
4202
4203 struct WarnAbout { enum What {
4204 Nothing = 0x00,
4205 NoAssertions = 0x01,
4206 NoTests = 0x02
4207 }; };
4208
4219 struct UseColour { enum YesOrNo {
4222 No
4223 }; };
4224 struct WaitForKeypress { enum When {
4226 BeforeStart = 1,
4227 BeforeExit = 2,
4228 BeforeStartAndExit = BeforeStart | BeforeExit
4229 }; };
4230
4231 class TestSpec;
4232
4234
4235 virtual ~IConfig();
4236
4237 virtual bool allowThrows() const = 0;
4238 virtual std::ostream& stream() const = 0;
4239 virtual std::string name() const = 0;
4240 virtual bool includeSuccessfulResults() const = 0;
4241 virtual bool shouldDebugBreak() const = 0;
4242 virtual bool warnAboutMissingAssertions() const = 0;
4243 virtual bool warnAboutNoTests() const = 0;
4244 virtual int abortAfter() const = 0;
4245 virtual bool showInvisibles() const = 0;
4247 virtual TestSpec const& testSpec() const = 0;
4248 virtual bool hasTestFilters() const = 0;
4249 virtual std::vector<std::string> const& getTestsOrTags() const = 0;
4250 virtual RunTests::InWhatOrder runOrder() const = 0;
4251 virtual unsigned int rngSeed() const = 0;
4252 virtual int benchmarkResolutionMultiple() const = 0;
4253 virtual UseColour::YesOrNo useColour() const = 0;
4254 virtual std::vector<std::string> const& getSectionsToRun() const = 0;
4255 virtual Verbosity verbosity() const = 0;
4256 };
4257
4259}
4260
4261// end catch_interfaces_config.h
4262#include <random>
4263
4264namespace Catch {
4265namespace Generators {
4266
4267template <typename Float>
4268class RandomFloatingGenerator final : public IGenerator<Float> {
4269 // FIXME: What is the right seed?
4273public:
4274
4275 RandomFloatingGenerator(Float a, Float b):
4276 m_rand(getCurrentContext().getConfig()->rngSeed()),
4277 m_dist(a, b) {
4278 static_cast<void>(next());
4279 }
4280
4281 Float const& get() const override {
4282 return m_current_number;
4283 }
4284 bool next() override {
4285 m_current_number = m_dist(m_rand);
4286 return true;
4287 }
4288};
4289
4290template <typename Integer>
4291class RandomIntegerGenerator final : public IGenerator<Integer> {
4295public:
4296
4297 RandomIntegerGenerator(Integer a, Integer b):
4298 m_rand(getCurrentContext().getConfig()->rngSeed()),
4299 m_dist(a, b) {
4300 static_cast<void>(next());
4301 }
4302
4303 Integer const& get() const override {
4304 return m_current_number;
4305 }
4306 bool next() override {
4307 m_current_number = m_dist(m_rand);
4308 return true;
4309 }
4310};
4311
4312// TODO: Ideally this would be also constrained against the various char types,
4313// but I don't expect users to run into that in practice.
4314template <typename T>
4316GeneratorWrapper<T>>::type
4317random(T a, T b) {
4318 return GeneratorWrapper<T>(
4319 pf::make_unique<RandomIntegerGenerator<T>>(a, b)
4320 );
4321}
4322
4323template <typename T>
4325GeneratorWrapper<T>>::type
4326random(T a, T b) {
4327 return GeneratorWrapper<T>(
4328 pf::make_unique<RandomFloatingGenerator<T>>(a, b)
4329 );
4330}
4331
4332template <typename T>
4333class RangeGenerator final : public IGenerator<T> {
4338
4339public:
4340 RangeGenerator(T const& start, T const& end, T const& step):
4341 m_current(start),
4342 m_end(end),
4343 m_step(step),
4344 m_positive(m_step > T(0))
4345 {
4346 assert(m_current != m_end && "Range start and end cannot be equal");
4347 assert(m_step != T(0) && "Step size cannot be zero");
4348 assert(((m_positive && m_current <= m_end) || (!m_positive && m_current >= m_end)) && "Step moves away from end");
4349 }
4350
4351 RangeGenerator(T const& start, T const& end):
4352 RangeGenerator(start, end, (start < end) ? T(1) : T(-1))
4353 {}
4354
4355 T const& get() const override {
4356 return m_current;
4357 }
4358
4359 bool next() override {
4360 m_current += m_step;
4361 return (m_positive) ? (m_current < m_end) : (m_current > m_end);
4362 }
4363};
4364
4365template <typename T>
4366GeneratorWrapper<T> range(T const& start, T const& end, T const& step) {
4367 static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
4368 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end, step));
4369}
4370
4371template <typename T>
4372GeneratorWrapper<T> range(T const& start, T const& end) {
4373 static_assert(std::is_integral<T>::value && !std::is_same<T, bool>::value, "Type must be an integer");
4374 return GeneratorWrapper<T>(pf::make_unique<RangeGenerator<T>>(start, end));
4375}
4376
4377} // namespace Generators
4378} // namespace Catch
4379
4380// end catch_generators_specific.hpp
4381
4382// These files are included here so the single_include script doesn't put them
4383// in the conditionally compiled sections
4384// start catch_test_case_info.h
4385
4386#include <string>
4387#include <vector>
4388#include <memory>
4389
4390#ifdef __clang__
4391#pragma clang diagnostic push
4392#pragma clang diagnostic ignored "-Wpadded"
4393#endif
4394
4395namespace Catch {
4396
4397 struct ITestInvoker;
4398
4401 None = 0,
4402 IsHidden = 1 << 1,
4403 ShouldFail = 1 << 2,
4404 MayFail = 1 << 3,
4405 Throws = 1 << 4,
4406 NonPortable = 1 << 5,
4407 Benchmark = 1 << 6
4409
4411 std::string const& _className,
4412 std::string const& _description,
4413 std::vector<std::string> const& _tags,
4414 SourceLineInfo const& _lineInfo );
4415
4416 friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
4417
4418 bool isHidden() const;
4419 bool throws() const;
4420 bool okToFail() const;
4421 bool expectedToFail() const;
4422
4424
4432 };
4433
4434 class TestCase : public TestCaseInfo {
4435 public:
4436
4437 TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
4438
4439 TestCase withName( std::string const& _newName ) const;
4440
4441 void invoke() const;
4442
4444
4445 bool operator == ( TestCase const& other ) const;
4446 bool operator < ( TestCase const& other ) const;
4447
4448 private:
4450 };
4451
4453 std::string const& className,
4454 NameAndTags const& nameAndTags,
4455 SourceLineInfo const& lineInfo );
4456}
4457
4458#ifdef __clang__
4459#pragma clang diagnostic pop
4460#endif
4461
4462// end catch_test_case_info.h
4463// start catch_interfaces_runner.h
4464
4465namespace Catch {
4466
4467 struct IRunner {
4468 virtual ~IRunner();
4469 virtual bool aborting() const = 0;
4470 };
4471}
4472
4473// end catch_interfaces_runner.h
4474
4475#ifdef __OBJC__
4476// start catch_objc.hpp
4477
4478#import <objc/runtime.h>
4479
4480#include <string>
4481
4482// NB. Any general catch headers included here must be included
4483// in catch.hpp first to make sure they are included by the single
4484// header for non obj-usage
4485
4486///////////////////////////////////////////////////////////////////////////////
4487// This protocol is really only here for (self) documenting purposes, since
4488// all its methods are optional.
4489@protocol OcFixture
4490
4491@optional
4492
4493-(void) setUp;
4494-(void) tearDown;
4495
4496@end
4497
4498namespace Catch {
4499
4500 class OcMethod : public ITestInvoker {
4501
4502 public:
4503 OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
4504
4505 virtual void invoke() const {
4506 id obj = [[m_cls alloc] init];
4507
4508 performOptionalSelector( obj, @selector(setUp) );
4509 performOptionalSelector( obj, m_sel );
4510 performOptionalSelector( obj, @selector(tearDown) );
4511
4512 arcSafeRelease( obj );
4513 }
4514 private:
4515 virtual ~OcMethod() {}
4516
4517 Class m_cls;
4518 SEL m_sel;
4519 };
4520
4521 namespace Detail{
4522
4523 inline std::string getAnnotation( Class cls,
4524 std::string const& annotationName,
4525 std::string const& testCaseName ) {
4526 NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
4527 SEL sel = NSSelectorFromString( selStr );
4528 arcSafeRelease( selStr );
4529 id value = performOptionalSelector( cls, sel );
4530 if( value )
4531 return [(NSString*)value UTF8String];
4532 return "";
4533 }
4534 }
4535
4536 inline std::size_t registerTestMethods() {
4537 std::size_t noTestMethods = 0;
4538 int noClasses = objc_getClassList( nullptr, 0 );
4539
4540 Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
4541 objc_getClassList( classes, noClasses );
4542
4543 for( int c = 0; c < noClasses; c++ ) {
4544 Class cls = classes[c];
4545 {
4546 u_int count;
4547 Method* methods = class_copyMethodList( cls, &count );
4548 for( u_int m = 0; m < count ; m++ ) {
4549 SEL selector = method_getName(methods[m]);
4550 std::string methodName = sel_getName(selector);
4551 if( startsWith( methodName, "Catch_TestCase_" ) ) {
4552 std::string testCaseName = methodName.substr( 15 );
4553 std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
4554 std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
4555 const char* className = class_getName( cls );
4556
4557 getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
4558 noTestMethods++;
4559 }
4560 }
4561 free(methods);
4562 }
4563 }
4564 return noTestMethods;
4565 }
4566
4567#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
4568
4569 namespace Matchers {
4570 namespace Impl {
4571 namespace NSStringMatchers {
4572
4573 struct StringHolder : MatcherBase<NSString*>{
4574 StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
4575 StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
4576 StringHolder() {
4577 arcSafeRelease( m_substr );
4578 }
4579
4580 bool match( NSString* const& str ) const override {
4581 return false;
4582 }
4583
4584 NSString* CATCH_ARC_STRONG m_substr;
4585 };
4586
4587 struct Equals : StringHolder {
4588 Equals( NSString* substr ) : StringHolder( substr ){}
4589
4590 bool match( NSString* const& str ) const override {
4591 return (str != nil || m_substr == nil ) &&
4592 [str isEqualToString:m_substr];
4593 }
4594
4595 std::string describe() const override {
4596 return "equals string: " + Catch::Detail::stringify( m_substr );
4597 }
4598 };
4599
4600 struct Contains : StringHolder {
4601 Contains( NSString* substr ) : StringHolder( substr ){}
4602
4603 bool match( NSString* const& str ) const override {
4604 return (str != nil || m_substr == nil ) &&
4605 [str rangeOfString:m_substr].location != NSNotFound;
4606 }
4607
4608 std::string describe() const override {
4609 return "contains string: " + Catch::Detail::stringify( m_substr );
4610 }
4611 };
4612
4613 struct StartsWith : StringHolder {
4614 StartsWith( NSString* substr ) : StringHolder( substr ){}
4615
4616 bool match( NSString* const& str ) const override {
4617 return (str != nil || m_substr == nil ) &&
4618 [str rangeOfString:m_substr].location == 0;
4619 }
4620
4621 std::string describe() const override {
4622 return "starts with: " + Catch::Detail::stringify( m_substr );
4623 }
4624 };
4625 struct EndsWith : StringHolder {
4626 EndsWith( NSString* substr ) : StringHolder( substr ){}
4627
4628 bool match( NSString* const& str ) const override {
4629 return (str != nil || m_substr == nil ) &&
4630 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
4631 }
4632
4633 std::string describe() const override {
4634 return "ends with: " + Catch::Detail::stringify( m_substr );
4635 }
4636 };
4637
4638 } // namespace NSStringMatchers
4639 } // namespace Impl
4640
4641 inline Impl::NSStringMatchers::Equals
4642 Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
4643
4644 inline Impl::NSStringMatchers::Contains
4645 Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
4646
4647 inline Impl::NSStringMatchers::StartsWith
4648 StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
4649
4650 inline Impl::NSStringMatchers::EndsWith
4651 EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
4652
4653 } // namespace Matchers
4654
4655 using namespace Matchers;
4656
4657#endif // CATCH_CONFIG_DISABLE_MATCHERS
4658
4659} // namespace Catch
4660
4661///////////////////////////////////////////////////////////////////////////////
4662#define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
4663#define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
4664+(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
4665{ \
4666return @ name; \
4667} \
4668+(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
4669{ \
4670return @ desc; \
4671} \
4672-(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
4673
4674#define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
4675
4676// end catch_objc.hpp
4677#endif
4678
4679#ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
4680// start catch_external_interfaces.h
4681
4682// start catch_reporter_bases.hpp
4683
4684// start catch_interfaces_reporter.h
4685
4686// start catch_config.hpp
4687
4688// start catch_test_spec_parser.h
4689
4690#ifdef __clang__
4691#pragma clang diagnostic push
4692#pragma clang diagnostic ignored "-Wpadded"
4693#endif
4694
4695// start catch_test_spec.h
4696
4697#ifdef __clang__
4698#pragma clang diagnostic push
4699#pragma clang diagnostic ignored "-Wpadded"
4700#endif
4701
4702// start catch_wildcard_pattern.h
4703
4704namespace Catch
4705{
4706 class WildcardPattern {
4707 enum WildcardPosition {
4708 NoWildcard = 0,
4709 WildcardAtStart = 1,
4710 WildcardAtEnd = 2,
4711 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
4712 };
4713
4714 public:
4715
4716 WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
4717 virtual ~WildcardPattern() = default;
4718 virtual bool matches( std::string const& str ) const;
4719
4720 private:
4721 std::string adjustCase( std::string const& str ) const;
4722 CaseSensitive::Choice m_caseSensitivity;
4723 WildcardPosition m_wildcard = NoWildcard;
4724 std::string m_pattern;
4725 };
4726}
4727
4728// end catch_wildcard_pattern.h
4729#include <string>
4730#include <vector>
4731#include <memory>
4732
4733namespace Catch {
4734
4735 class TestSpec {
4736 struct Pattern {
4737 virtual ~Pattern();
4738 virtual bool matches( TestCaseInfo const& testCase ) const = 0;
4739 };
4740 using PatternPtr = std::shared_ptr<Pattern>;
4741
4742 class NamePattern : public Pattern {
4743 public:
4744 NamePattern( std::string const& name );
4745 virtual ~NamePattern();
4746 bool matches( TestCaseInfo const& testCase ) const override;
4747 private:
4748 WildcardPattern m_wildcardPattern;
4749 };
4750
4751 class TagPattern : public Pattern {
4752 public:
4753 TagPattern( std::string const& tag );
4754 virtual ~TagPattern();
4755 bool matches( TestCaseInfo const& testCase ) const override;
4756 private:
4757 std::string m_tag;
4758 };
4759
4760 class ExcludedPattern : public Pattern {
4761 public:
4762 ExcludedPattern( PatternPtr const& underlyingPattern );
4763 virtual ~ExcludedPattern();
4764 bool matches( TestCaseInfo const& testCase ) const override;
4765 private:
4766 PatternPtr m_underlyingPattern;
4767 };
4768
4769 struct Filter {
4770 std::vector<PatternPtr> m_patterns;
4771
4772 bool matches( TestCaseInfo const& testCase ) const;
4773 };
4774
4775 public:
4776 bool hasFilters() const;
4777 bool matches( TestCaseInfo const& testCase ) const;
4778
4779 private:
4780 std::vector<Filter> m_filters;
4781
4782 friend class TestSpecParser;
4783 };
4784}
4785
4786#ifdef __clang__
4787#pragma clang diagnostic pop
4788#endif
4789
4790// end catch_test_spec.h
4791// start catch_interfaces_tag_alias_registry.h
4792
4793#include <string>
4794
4795namespace Catch {
4796
4797 struct TagAlias;
4798
4799 struct ITagAliasRegistry {
4800 virtual ~ITagAliasRegistry();
4801 // Nullptr if not present
4802 virtual TagAlias const* find( std::string const& alias ) const = 0;
4803 virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
4804
4805 static ITagAliasRegistry const& get();
4806 };
4807
4808} // end namespace Catch
4809
4810// end catch_interfaces_tag_alias_registry.h
4811namespace Catch {
4812
4813 class TestSpecParser {
4814 enum Mode{ None, Name, QuotedName, Tag, EscapedName };
4815 Mode m_mode = None;
4816 bool m_exclusion = false;
4817 std::size_t m_start = std::string::npos, m_pos = 0;
4818 std::string m_arg;
4819 std::vector<std::size_t> m_escapeChars;
4820 TestSpec::Filter m_currentFilter;
4821 TestSpec m_testSpec;
4822 ITagAliasRegistry const* m_tagAliases = nullptr;
4823
4824 public:
4825 TestSpecParser( ITagAliasRegistry const& tagAliases );
4826
4827 TestSpecParser& parse( std::string const& arg );
4828 TestSpec testSpec();
4829
4830 private:
4831 void visitChar( char c );
4832 void startNewMode( Mode mode, std::size_t start );
4833 void escape();
4834 std::string subString() const;
4835
4836 template<typename T>
4837 void addPattern() {
4838 std::string token = subString();
4839 for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
4840 token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
4841 m_escapeChars.clear();
4842 if( startsWith( token, "exclude:" ) ) {
4843 m_exclusion = true;
4844 token = token.substr( 8 );
4845 }
4846 if( !token.empty() ) {
4847 TestSpec::PatternPtr pattern = std::make_shared<T>( token );
4848 if( m_exclusion )
4849 pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
4850 m_currentFilter.m_patterns.push_back( pattern );
4851 }
4852 m_exclusion = false;
4853 m_mode = None;
4854 }
4855
4856 void addFilter();
4857 };
4858 TestSpec parseTestSpec( std::string const& arg );
4859
4860} // namespace Catch
4861
4862#ifdef __clang__
4863#pragma clang diagnostic pop
4864#endif
4865
4866// end catch_test_spec_parser.h
4867// Libstdc++ doesn't like incomplete classes for unique_ptr
4868
4869#include <memory>
4870#include <vector>
4871#include <string>
4872
4873#ifndef CATCH_CONFIG_CONSOLE_WIDTH
4874#define CATCH_CONFIG_CONSOLE_WIDTH 80
4875#endif
4876
4877namespace Catch {
4878
4879 struct IStream;
4880
4881 struct ConfigData {
4882 bool listTests = false;
4883 bool listTags = false;
4884 bool listReporters = false;
4885 bool listTestNamesOnly = false;
4886
4887 bool showSuccessfulTests = false;
4888 bool shouldDebugBreak = false;
4889 bool noThrow = false;
4890 bool showHelp = false;
4891 bool showInvisibles = false;
4892 bool filenamesAsTags = false;
4893 bool libIdentify = false;
4894
4895 int abortAfter = -1;
4896 unsigned int rngSeed = 0;
4897 int benchmarkResolutionMultiple = 100;
4898
4899 Verbosity verbosity = Verbosity::Normal;
4900 WarnAbout::What warnings = WarnAbout::Nothing;
4901 ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
4902 RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
4903 UseColour::YesOrNo useColour = UseColour::Auto;
4904 WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
4905
4906 std::string outputFilename;
4908 std::string processName;
4909#ifndef CATCH_CONFIG_DEFAULT_REPORTER
4910#define CATCH_CONFIG_DEFAULT_REPORTER "console"
4911#endif
4912 std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
4913#undef CATCH_CONFIG_DEFAULT_REPORTER
4914
4915 std::vector<std::string> testsOrTags;
4916 std::vector<std::string> sectionsToRun;
4917 };
4918
4919 class Config : public IConfig {
4920 public:
4921
4922 Config() = default;
4923 Config( ConfigData const& data );
4924 virtual ~Config() = default;
4925
4926 std::string const& getFilename() const;
4927
4928 bool listTests() const;
4929 bool listTestNamesOnly() const;
4930 bool listTags() const;
4931 bool listReporters() const;
4932
4933 std::string getProcessName() const;
4934 std::string const& getReporterName() const;
4935
4936 std::vector<std::string> const& getTestsOrTags() const override;
4937 std::vector<std::string> const& getSectionsToRun() const override;
4938
4939 TestSpec const& testSpec() const override;
4940 bool hasTestFilters() const override;
4941
4942 bool showHelp() const;
4943
4944 // IConfig interface
4945 bool allowThrows() const override;
4946 std::ostream& stream() const override;
4947 std::string name() const override;
4948 bool includeSuccessfulResults() const override;
4949 bool warnAboutMissingAssertions() const override;
4950 bool warnAboutNoTests() const override;
4951 ShowDurations::OrNot showDurations() const override;
4952 RunTests::InWhatOrder runOrder() const override;
4953 unsigned int rngSeed() const override;
4954 int benchmarkResolutionMultiple() const override;
4955 UseColour::YesOrNo useColour() const override;
4956 bool shouldDebugBreak() const override;
4957 int abortAfter() const override;
4958 bool showInvisibles() const override;
4959 Verbosity verbosity() const override;
4960
4961 private:
4962
4963 IStream const* openStream();
4964 ConfigData m_data;
4965
4967 TestSpec m_testSpec;
4968 bool m_hasTestFilters = false;
4969 };
4970
4971} // end namespace Catch
4972
4973// end catch_config.hpp
4974// start catch_assertionresult.h
4975
4976#include <string>
4977
4978namespace Catch {
4979
4980 struct AssertionResultData
4981 {
4982 AssertionResultData() = delete;
4983
4984 AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
4985
4986 std::string message;
4987 mutable std::string reconstructedExpression;
4988 LazyExpression lazyExpression;
4989 ResultWas::OfType resultType;
4990
4991 std::string reconstructExpression() const;
4992 };
4993
4994 class AssertionResult {
4995 public:
4996 AssertionResult() = delete;
4997 AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
4998
4999 bool isOk() const;
5000 bool succeeded() const;
5001 ResultWas::OfType getResultType() const;
5002 bool hasExpression() const;
5003 bool hasMessage() const;
5004 std::string getExpression() const;
5005 std::string getExpressionInMacro() const;
5006 bool hasExpandedExpression() const;
5007 std::string getExpandedExpression() const;
5008 std::string getMessage() const;
5009 SourceLineInfo getSourceInfo() const;
5010 StringRef getTestMacroName() const;
5011
5012 //protected:
5013 AssertionInfo m_info;
5014 AssertionResultData m_resultData;
5015 };
5016
5017} // end namespace Catch
5018
5019// end catch_assertionresult.h
5020// start catch_option.hpp
5021
5022namespace Catch {
5023
5024 // An optional type
5025 template<typename T>
5026 class Option {
5027 public:
5028 Option() : nullableValue( nullptr ) {}
5029 Option( T const& _value )
5030 : nullableValue( new( storage ) T( _value ) )
5031 {}
5032 Option( Option const& _other )
5033 : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
5034 {}
5035
5036 ~Option() {
5037 reset();
5038 }
5039
5040 Option& operator= ( Option const& _other ) {
5041 if( &_other != this ) {
5042 reset();
5043 if( _other )
5044 nullableValue = new( storage ) T( *_other );
5045 }
5046 return *this;
5047 }
5048 Option& operator = ( T const& _value ) {
5049 reset();
5050 nullableValue = new( storage ) T( _value );
5051 return *this;
5052 }
5053
5054 void reset() {
5055 if( nullableValue )
5056 nullableValue->~T();
5057 nullableValue = nullptr;
5058 }
5059
5060 T& operator*() { return *nullableValue; }
5061 T const& operator*() const { return *nullableValue; }
5062 T* operator->() { return nullableValue; }
5063 const T* operator->() const { return nullableValue; }
5064
5065 T valueOr( T const& defaultValue ) const {
5066 return nullableValue ? *nullableValue : defaultValue;
5067 }
5068
5069 bool some() const { return nullableValue != nullptr; }
5070 bool none() const { return nullableValue == nullptr; }
5071
5072 bool operator !() const { return nullableValue == nullptr; }
5073 explicit operator bool() const {
5074 return some();
5075 }
5076
5077 private:
5078 T *nullableValue;
5079 alignas(alignof(T)) char storage[sizeof(T)];
5080 };
5081
5082} // end namespace Catch
5083
5084// end catch_option.hpp
5085#include <string>
5086#include <iosfwd>
5087#include <map>
5088#include <set>
5089#include <memory>
5090
5091namespace Catch {
5092
5093 struct ReporterConfig {
5094 explicit ReporterConfig( IConfigPtr const& _fullConfig );
5095
5096 ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
5097
5098 std::ostream& stream() const;
5099 IConfigPtr fullConfig() const;
5100
5101 private:
5102 std::ostream* m_stream;
5103 IConfigPtr m_fullConfig;
5104 };
5105
5106 struct ReporterPreferences {
5107 bool shouldRedirectStdOut = false;
5108 bool shouldReportAllAssertions = false;
5109 };
5110
5111 template<typename T>
5112 struct LazyStat : Option<T> {
5113 LazyStat& operator=( T const& _value ) {
5114 Option<T>::operator=( _value );
5115 used = false;
5116 return *this;
5117 }
5118 void reset() {
5119 Option<T>::reset();
5120 used = false;
5121 }
5122 bool used = false;
5123 };
5124
5125 struct TestRunInfo {
5126 TestRunInfo( std::string const& _name );
5128 };
5129 struct GroupInfo {
5130 GroupInfo( std::string const& _name,
5131 std::size_t _groupIndex,
5132 std::size_t _groupsCount );
5133
5135 std::size_t groupIndex;
5136 std::size_t groupsCounts;
5137 };
5138
5139 struct AssertionStats {
5140 AssertionStats( AssertionResult const& _assertionResult,
5141 std::vector<MessageInfo> const& _infoMessages,
5142 Totals const& _totals );
5143
5144 AssertionStats( AssertionStats const& ) = default;
5145 AssertionStats( AssertionStats && ) = default;
5146 AssertionStats& operator = ( AssertionStats const& ) = delete;
5147 AssertionStats& operator = ( AssertionStats && ) = delete;
5148 virtual ~AssertionStats();
5149
5150 AssertionResult assertionResult;
5151 std::vector<MessageInfo> infoMessages;
5152 Totals totals;
5153 };
5154
5155 struct SectionStats {
5156 SectionStats( SectionInfo const& _sectionInfo,
5157 Counts const& _assertions,
5158 double _durationInSeconds,
5159 bool _missingAssertions );
5160 SectionStats( SectionStats const& ) = default;
5161 SectionStats( SectionStats && ) = default;
5162 SectionStats& operator = ( SectionStats const& ) = default;
5163 SectionStats& operator = ( SectionStats && ) = default;
5164 virtual ~SectionStats();
5165
5166 SectionInfo sectionInfo;
5167 Counts assertions;
5168 double durationInSeconds;
5169 bool missingAssertions;
5170 };
5171
5172 struct TestCaseStats {
5173 TestCaseStats( TestCaseInfo const& _testInfo,
5174 Totals const& _totals,
5175 std::string const& _stdOut,
5176 std::string const& _stdErr,
5177 bool _aborting );
5178
5179 TestCaseStats( TestCaseStats const& ) = default;
5180 TestCaseStats( TestCaseStats && ) = default;
5181 TestCaseStats& operator = ( TestCaseStats const& ) = default;
5182 TestCaseStats& operator = ( TestCaseStats && ) = default;
5183 virtual ~TestCaseStats();
5184
5185 TestCaseInfo testInfo;
5186 Totals totals;
5187 std::string stdOut;
5188 std::string stdErr;
5189 bool aborting;
5190 };
5191
5192 struct TestGroupStats {
5193 TestGroupStats( GroupInfo const& _groupInfo,
5194 Totals const& _totals,
5195 bool _aborting );
5196 TestGroupStats( GroupInfo const& _groupInfo );
5197
5198 TestGroupStats( TestGroupStats const& ) = default;
5199 TestGroupStats( TestGroupStats && ) = default;
5200 TestGroupStats& operator = ( TestGroupStats const& ) = default;
5201 TestGroupStats& operator = ( TestGroupStats && ) = default;
5202 virtual ~TestGroupStats();
5203
5204 GroupInfo groupInfo;
5205 Totals totals;
5206 bool aborting;
5207 };
5208
5209 struct TestRunStats {
5210 TestRunStats( TestRunInfo const& _runInfo,
5211 Totals const& _totals,
5212 bool _aborting );
5213
5214 TestRunStats( TestRunStats const& ) = default;
5215 TestRunStats( TestRunStats && ) = default;
5216 TestRunStats& operator = ( TestRunStats const& ) = default;
5217 TestRunStats& operator = ( TestRunStats && ) = default;
5218 virtual ~TestRunStats();
5219
5220 TestRunInfo runInfo;
5221 Totals totals;
5222 bool aborting;
5223 };
5224
5225 struct BenchmarkInfo {
5227 };
5228 struct BenchmarkStats {
5229 BenchmarkInfo info;
5230 std::size_t iterations;
5231 uint64_t elapsedTimeInNanoseconds;
5232 };
5233
5234 struct IStreamingReporter {
5235 virtual ~IStreamingReporter() = default;
5236
5237 // Implementing class must also provide the following static methods:
5238 // static std::string getDescription();
5239 // static std::set<Verbosity> getSupportedVerbosities()
5240
5241 virtual ReporterPreferences getPreferences() const = 0;
5242
5243 virtual void noMatchingTestCases( std::string const& spec ) = 0;
5244
5245 virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
5246 virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
5247
5248 virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
5249 virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
5250
5251 // *** experimental ***
5252 virtual void benchmarkStarting( BenchmarkInfo const& ) {}
5253
5254 virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
5255
5256 // The return value indicates if the messages buffer should be cleared:
5257 virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
5258
5259 // *** experimental ***
5260 virtual void benchmarkEnded( BenchmarkStats const& ) {}
5261
5262 virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
5263 virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
5264 virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
5265 virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
5266
5267 virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
5268
5269 // Default empty implementation provided
5270 virtual void fatalErrorEncountered( StringRef name );
5271
5272 virtual bool isMulti() const;
5273 };
5274 using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
5275
5276 struct IReporterFactory {
5277 virtual ~IReporterFactory();
5278 virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
5279 virtual std::string getDescription() const = 0;
5280 };
5282
5283 struct IReporterRegistry {
5285 using Listeners = std::vector<IReporterFactoryPtr>;
5286
5287 virtual ~IReporterRegistry();
5288 virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
5289 virtual FactoryMap const& getFactories() const = 0;
5290 virtual Listeners const& getListeners() const = 0;
5291 };
5292
5293} // end namespace Catch
5294
5295// end catch_interfaces_reporter.h
5296#include <algorithm>
5297#include <cstring>
5298#include <cfloat>
5299#include <cstdio>
5300#include <cassert>
5301#include <memory>
5302#include <ostream>
5303
5304namespace Catch {
5305 void prepareExpandedExpression(AssertionResult& result);
5306
5307 // Returns double formatted as %.3f (format expected on output)
5308 std::string getFormattedDuration( double duration );
5309
5310 std::string serializeFilters( std::vector<std::string> const& container );
5311
5312 template<typename DerivedT>
5313 struct StreamingReporterBase : IStreamingReporter {
5314
5315 StreamingReporterBase( ReporterConfig const& _config )
5316 : m_config( _config.fullConfig() ),
5317 stream( _config.stream() )
5318 {
5319 m_reporterPrefs.shouldRedirectStdOut = false;
5320 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5321 CATCH_ERROR( "Verbosity level not supported by this reporter" );
5322 }
5323
5324 ReporterPreferences getPreferences() const override {
5325 return m_reporterPrefs;
5326 }
5327
5328 static std::set<Verbosity> getSupportedVerbosities() {
5329 return { Verbosity::Normal };
5330 }
5331
5332 ~StreamingReporterBase() override = default;
5333
5334 void noMatchingTestCases(std::string const&) override {}
5335
5336 void testRunStarting(TestRunInfo const& _testRunInfo) override {
5337 currentTestRunInfo = _testRunInfo;
5338 }
5339
5340 void testGroupStarting(GroupInfo const& _groupInfo) override {
5341 currentGroupInfo = _groupInfo;
5342 }
5343
5344 void testCaseStarting(TestCaseInfo const& _testInfo) override {
5345 currentTestCaseInfo = _testInfo;
5346 }
5347 void sectionStarting(SectionInfo const& _sectionInfo) override {
5348 m_sectionStack.push_back(_sectionInfo);
5349 }
5350
5351 void sectionEnded(SectionStats const& /* _sectionStats */) override {
5352 m_sectionStack.pop_back();
5353 }
5354 void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
5355 currentTestCaseInfo.reset();
5356 }
5357 void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
5358 currentGroupInfo.reset();
5359 }
5360 void testRunEnded(TestRunStats const& /* _testRunStats */) override {
5361 currentTestCaseInfo.reset();
5362 currentGroupInfo.reset();
5363 currentTestRunInfo.reset();
5364 }
5365
5366 void skipTest(TestCaseInfo const&) override {
5367 // Don't do anything with this by default.
5368 // It can optionally be overridden in the derived class.
5369 }
5370
5371 IConfigPtr m_config;
5372 std::ostream& stream;
5373
5374 LazyStat<TestRunInfo> currentTestRunInfo;
5375 LazyStat<GroupInfo> currentGroupInfo;
5376 LazyStat<TestCaseInfo> currentTestCaseInfo;
5377
5378 std::vector<SectionInfo> m_sectionStack;
5379 ReporterPreferences m_reporterPrefs;
5380 };
5381
5382 template<typename DerivedT>
5383 struct CumulativeReporterBase : IStreamingReporter {
5384 template<typename T, typename ChildNodeT>
5385 struct Node {
5386 explicit Node( T const& _value ) : value( _value ) {}
5387 virtual ~Node() {}
5388
5389 using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
5390 T value;
5391 ChildNodes children;
5392 };
5393 struct SectionNode {
5394 explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
5395 virtual ~SectionNode() = default;
5396
5397 bool operator == (SectionNode const& other) const {
5398 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
5399 }
5400 bool operator == (std::shared_ptr<SectionNode> const& other) const {
5401 return operator==(*other);
5402 }
5403
5404 SectionStats stats;
5405 using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
5406 using Assertions = std::vector<AssertionStats>;
5407 ChildSections childSections;
5408 Assertions assertions;
5409 std::string stdOut;
5410 std::string stdErr;
5411 };
5412
5413 struct BySectionInfo {
5414 BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
5415 BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
5416 bool operator() (std::shared_ptr<SectionNode> const& node) const {
5417 return ((node->stats.sectionInfo.name == m_other.name) &&
5418 (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
5419 }
5420 void operator=(BySectionInfo const&) = delete;
5421
5422 private:
5423 SectionInfo const& m_other;
5424 };
5425
5426 using TestCaseNode = Node<TestCaseStats, SectionNode>;
5427 using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
5428 using TestRunNode = Node<TestRunStats, TestGroupNode>;
5429
5430 CumulativeReporterBase( ReporterConfig const& _config )
5431 : m_config( _config.fullConfig() ),
5432 stream( _config.stream() )
5433 {
5434 m_reporterPrefs.shouldRedirectStdOut = false;
5435 if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
5436 CATCH_ERROR( "Verbosity level not supported by this reporter" );
5437 }
5438 ~CumulativeReporterBase() override = default;
5439
5440 ReporterPreferences getPreferences() const override {
5441 return m_reporterPrefs;
5442 }
5443
5444 static std::set<Verbosity> getSupportedVerbosities() {
5445 return { Verbosity::Normal };
5446 }
5447
5448 void testRunStarting( TestRunInfo const& ) override {}
5449 void testGroupStarting( GroupInfo const& ) override {}
5450
5451 void testCaseStarting( TestCaseInfo const& ) override {}
5452
5453 void sectionStarting( SectionInfo const& sectionInfo ) override {
5454 SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
5456 if( m_sectionStack.empty() ) {
5457 if( !m_rootSection )
5458 m_rootSection = std::make_shared<SectionNode>( incompleteStats );
5459 node = m_rootSection;
5460 }
5461 else {
5462 SectionNode& parentNode = *m_sectionStack.back();
5463 auto it =
5464 std::find_if( parentNode.childSections.begin(),
5465 parentNode.childSections.end(),
5466 BySectionInfo( sectionInfo ) );
5467 if( it == parentNode.childSections.end() ) {
5468 node = std::make_shared<SectionNode>( incompleteStats );
5469 parentNode.childSections.push_back( node );
5470 }
5471 else
5472 node = *it;
5473 }
5474 m_sectionStack.push_back( node );
5475 m_deepestSection = std::move(node);
5476 }
5477
5478 void assertionStarting(AssertionInfo const&) override {}
5479
5480 bool assertionEnded(AssertionStats const& assertionStats) override {
5481 assert(!m_sectionStack.empty());
5482 // AssertionResult holds a pointer to a temporary DecomposedExpression,
5483 // which getExpandedExpression() calls to build the expression string.
5484 // Our section stack copy of the assertionResult will likely outlive the
5485 // temporary, so it must be expanded or discarded now to avoid calling
5486 // a destroyed object later.
5487 prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
5488 SectionNode& sectionNode = *m_sectionStack.back();
5489 sectionNode.assertions.push_back(assertionStats);
5490 return true;
5491 }
5492 void sectionEnded(SectionStats const& sectionStats) override {
5493 assert(!m_sectionStack.empty());
5494 SectionNode& node = *m_sectionStack.back();
5495 node.stats = sectionStats;
5496 m_sectionStack.pop_back();
5497 }
5498 void testCaseEnded(TestCaseStats const& testCaseStats) override {
5499 auto node = std::make_shared<TestCaseNode>(testCaseStats);
5500 assert(m_sectionStack.size() == 0);
5501 node->children.push_back(m_rootSection);
5502 m_testCases.push_back(node);
5503 m_rootSection.reset();
5504
5505 assert(m_deepestSection);
5506 m_deepestSection->stdOut = testCaseStats.stdOut;
5507 m_deepestSection->stdErr = testCaseStats.stdErr;
5508 }
5509 void testGroupEnded(TestGroupStats const& testGroupStats) override {
5510 auto node = std::make_shared<TestGroupNode>(testGroupStats);
5511 node->children.swap(m_testCases);
5512 m_testGroups.push_back(node);
5513 }
5514 void testRunEnded(TestRunStats const& testRunStats) override {
5515 auto node = std::make_shared<TestRunNode>(testRunStats);
5516 node->children.swap(m_testGroups);
5517 m_testRuns.push_back(node);
5518 testRunEndedCumulative();
5519 }
5520 virtual void testRunEndedCumulative() = 0;
5521
5522 void skipTest(TestCaseInfo const&) override {}
5523
5524 IConfigPtr m_config;
5525 std::ostream& stream;
5526 std::vector<AssertionStats> m_assertions;
5530
5532
5533 std::shared_ptr<SectionNode> m_rootSection;
5534 std::shared_ptr<SectionNode> m_deepestSection;
5536 ReporterPreferences m_reporterPrefs;
5537 };
5538
5539 template<char C>
5540 char const* getLineOfChars() {
5541 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
5542 if( !*line ) {
5543 std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
5544 line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
5545 }
5546 return line;
5547 }
5548
5549 struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
5550 TestEventListenerBase( ReporterConfig const& _config );
5551
5552 static std::set<Verbosity> getSupportedVerbosities();
5553
5554 void assertionStarting(AssertionInfo const&) override;
5555 bool assertionEnded(AssertionStats const&) override;
5556 };
5557
5558} // end namespace Catch
5559
5560// end catch_reporter_bases.hpp
5561// start catch_console_colour.h
5562
5563namespace Catch {
5564
5565 struct Colour {
5566 enum Code {
5567 None = 0,
5568
5569 White,
5570 Red,
5571 Green,
5572 Blue,
5573 Cyan,
5574 Yellow,
5575 Grey,
5576
5577 Bright = 0x10,
5578
5579 BrightRed = Bright | Red,
5580 BrightGreen = Bright | Green,
5581 LightGrey = Bright | Grey,
5582 BrightWhite = Bright | White,
5583 BrightYellow = Bright | Yellow,
5584
5585 // By intention
5586 FileName = LightGrey,
5587 Warning = BrightYellow,
5588 ResultError = BrightRed,
5589 ResultSuccess = BrightGreen,
5590 ResultExpectedFailure = Warning,
5591
5592 Error = BrightRed,
5593 Success = Green,
5594
5595 OriginalExpression = Cyan,
5596 ReconstructedExpression = BrightYellow,
5597
5598 SecondaryText = LightGrey,
5599 Headers = White
5600 };
5601
5602 // Use constructed object for RAII guard
5603 Colour( Code _colourCode );
5604 Colour( Colour&& other ) noexcept;
5605 Colour& operator=( Colour&& other ) noexcept;
5606 ~Colour();
5607
5608 // Use static method for one-shot changes
5609 static void use( Code _colourCode );
5610
5611 private:
5612 bool m_moved = false;
5613 };
5614
5615 std::ostream& operator << ( std::ostream& os, Colour const& );
5616
5617} // end namespace Catch
5618
5619// end catch_console_colour.h
5620// start catch_reporter_registrars.hpp
5621
5622
5623namespace Catch {
5624
5625 template<typename T>
5626 class ReporterRegistrar {
5627
5628 class ReporterFactory : public IReporterFactory {
5629
5630 IStreamingReporterPtr create( ReporterConfig const& config ) const override {
5631 return std::unique_ptr<T>( new T( config ) );
5632 }
5633
5634 std::string getDescription() const override {
5635 return T::getDescription();
5636 }
5637 };
5638
5639 public:
5640
5641 explicit ReporterRegistrar( std::string const& name ) {
5643 }
5644 };
5645
5646 template<typename T>
5647 class ListenerRegistrar {
5648
5649 class ListenerFactory : public IReporterFactory {
5650
5651 IStreamingReporterPtr create( ReporterConfig const& config ) const override {
5652 return std::unique_ptr<T>( new T( config ) );
5653 }
5654 std::string getDescription() const override {
5655 return std::string();
5656 }
5657 };
5658
5659 public:
5660
5661 ListenerRegistrar() {
5663 }
5664 };
5665}
5666
5667#if !defined(CATCH_CONFIG_DISABLE)
5668
5669#define CATCH_REGISTER_REPORTER( name, reporterType ) \
5670 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
5671 namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
5672 CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
5673
5674#define CATCH_REGISTER_LISTENER( listenerType ) \
5675 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
5676 namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
5677 CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
5678#else // CATCH_CONFIG_DISABLE
5679
5680#define CATCH_REGISTER_REPORTER(name, reporterType)
5681#define CATCH_REGISTER_LISTENER(listenerType)
5682
5683#endif // CATCH_CONFIG_DISABLE
5684
5685// end catch_reporter_registrars.hpp
5686// Allow users to base their work off existing reporters
5687// start catch_reporter_compact.h
5688
5689namespace Catch {
5690
5691 struct CompactReporter : StreamingReporterBase<CompactReporter> {
5692
5693 using StreamingReporterBase::StreamingReporterBase;
5694
5695 ~CompactReporter() override;
5696
5697 static std::string getDescription();
5698
5699 ReporterPreferences getPreferences() const override;
5700
5701 void noMatchingTestCases(std::string const& spec) override;
5702
5703 void assertionStarting(AssertionInfo const&) override;
5704
5705 bool assertionEnded(AssertionStats const& _assertionStats) override;
5706
5707 void sectionEnded(SectionStats const& _sectionStats) override;
5708
5709 void testRunEnded(TestRunStats const& _testRunStats) override;
5710
5711 };
5712
5713} // end namespace Catch
5714
5715// end catch_reporter_compact.h
5716// start catch_reporter_console.h
5717
5718#if defined(_MSC_VER)
5719#pragma warning(push)
5720#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
5721 // Note that 4062 (not all labels are handled
5722 // and default is missing) is enabled
5723#endif
5724
5725namespace Catch {
5726 // Fwd decls
5727 struct SummaryColumn;
5728 class TablePrinter;
5729
5730 struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
5731 std::unique_ptr<TablePrinter> m_tablePrinter;
5732
5733 ConsoleReporter(ReporterConfig const& config);
5734 ~ConsoleReporter() override;
5735 static std::string getDescription();
5736
5737 void noMatchingTestCases(std::string const& spec) override;
5738
5739 void assertionStarting(AssertionInfo const&) override;
5740
5741 bool assertionEnded(AssertionStats const& _assertionStats) override;
5742
5743 void sectionStarting(SectionInfo const& _sectionInfo) override;
5744 void sectionEnded(SectionStats const& _sectionStats) override;
5745
5746 void benchmarkStarting(BenchmarkInfo const& info) override;
5747 void benchmarkEnded(BenchmarkStats const& stats) override;
5748
5749 void testCaseEnded(TestCaseStats const& _testCaseStats) override;
5750 void testGroupEnded(TestGroupStats const& _testGroupStats) override;
5751 void testRunEnded(TestRunStats const& _testRunStats) override;
5752 void testRunStarting(TestRunInfo const& _testRunInfo) override;
5753 private:
5754
5755 void lazyPrint();
5756
5757 void lazyPrintWithoutClosingBenchmarkTable();
5758 void lazyPrintRunInfo();
5759 void lazyPrintGroupInfo();
5760 void printTestCaseAndSectionHeader();
5761
5762 void printClosedHeader(std::string const& _name);
5763 void printOpenHeader(std::string const& _name);
5764
5765 // if string has a : in first line will set indent to follow it on
5766 // subsequent lines
5767 void printHeaderString(std::string const& _string, std::size_t indent = 0);
5768
5769 void printTotals(Totals const& totals);
5770 void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
5771
5772 void printTotalsDivider(Totals const& totals);
5773 void printSummaryDivider();
5774 void printTestFilters();
5775
5776 private:
5777 bool m_headerPrinted = false;
5778 };
5779
5780} // end namespace Catch
5781
5782#if defined(_MSC_VER)
5783#pragma warning(pop)
5784#endif
5785
5786// end catch_reporter_console.h
5787// start catch_reporter_junit.h
5788
5789// start catch_xmlwriter.h
5790
5791#include <vector>
5792
5793namespace Catch {
5794
5795 class XmlEncode {
5796 public:
5797 enum ForWhat { ForTextNodes, ForAttributes };
5798
5799 XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
5800
5801 void encodeTo( std::ostream& os ) const;
5802
5803 friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
5804
5805 private:
5806 std::string m_str;
5807 ForWhat m_forWhat;
5808 };
5809
5810 class XmlWriter {
5811 public:
5812
5813 class ScopedElement {
5814 public:
5815 ScopedElement( XmlWriter* writer );
5816
5817 ScopedElement( ScopedElement&& other ) noexcept;
5818 ScopedElement& operator=( ScopedElement&& other ) noexcept;
5819
5820 ~ScopedElement();
5821
5822 ScopedElement& writeText( std::string const& text, bool indent = true );
5823
5824 template<typename T>
5825 ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
5826 m_writer->writeAttribute( name, attribute );
5827 return *this;
5828 }
5829
5830 private:
5831 mutable XmlWriter* m_writer = nullptr;
5832 };
5833
5834 XmlWriter( std::ostream& os = Catch::cout() );
5835 ~XmlWriter();
5836
5837 XmlWriter( XmlWriter const& ) = delete;
5838 XmlWriter& operator=( XmlWriter const& ) = delete;
5839
5840 XmlWriter& startElement( std::string const& name );
5841
5842 ScopedElement scopedElement( std::string const& name );
5843
5844 XmlWriter& endElement();
5845
5846 XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
5847
5848 XmlWriter& writeAttribute( std::string const& name, bool attribute );
5849
5850 template<typename T>
5851 XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
5852 ReusableStringStream rss;
5853 rss << attribute;
5854 return writeAttribute( name, rss.str() );
5855 }
5856
5857 XmlWriter& writeText( std::string const& text, bool indent = true );
5858
5859 XmlWriter& writeComment( std::string const& text );
5860
5861 void writeStylesheetRef( std::string const& url );
5862
5863 XmlWriter& writeBlankLine();
5864
5865 void ensureTagClosed();
5866
5867 private:
5868
5869 void writeDeclaration();
5870
5871 void newlineIfNecessary();
5872
5873 bool m_tagIsOpen = false;
5874 bool m_needsNewline = false;
5876 std::string m_indent;
5877 std::ostream& m_os;
5878 };
5879
5880}
5881
5882// end catch_xmlwriter.h
5883namespace Catch {
5884
5885 class JunitReporter : public CumulativeReporterBase<JunitReporter> {
5886 public:
5887 JunitReporter(ReporterConfig const& _config);
5888
5889 ~JunitReporter() override;
5890
5891 static std::string getDescription();
5892
5893 void noMatchingTestCases(std::string const& /*spec*/) override;
5894
5895 void testRunStarting(TestRunInfo const& runInfo) override;
5896
5897 void testGroupStarting(GroupInfo const& groupInfo) override;
5898
5899 void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
5900 bool assertionEnded(AssertionStats const& assertionStats) override;
5901
5902 void testCaseEnded(TestCaseStats const& testCaseStats) override;
5903
5904 void testGroupEnded(TestGroupStats const& testGroupStats) override;
5905
5906 void testRunEndedCumulative() override;
5907
5908 void writeGroup(TestGroupNode const& groupNode, double suiteTime);
5909
5910 void writeTestCase(TestCaseNode const& testCaseNode);
5911
5912 void writeSection(std::string const& className,
5913 std::string const& rootName,
5914 SectionNode const& sectionNode);
5915
5916 void writeAssertions(SectionNode const& sectionNode);
5917 void writeAssertion(AssertionStats const& stats);
5918
5919 XmlWriter xml;
5920 Timer suiteTimer;
5921 std::string stdOutForSuite;
5922 std::string stdErrForSuite;
5923 unsigned int unexpectedExceptions = 0;
5924 bool m_okToFail = false;
5925 };
5926
5927} // end namespace Catch
5928
5929// end catch_reporter_junit.h
5930// start catch_reporter_xml.h
5931
5932namespace Catch {
5933 class XmlReporter : public StreamingReporterBase<XmlReporter> {
5934 public:
5935 XmlReporter(ReporterConfig const& _config);
5936
5937 ~XmlReporter() override;
5938
5939 static std::string getDescription();
5940
5941 virtual std::string getStylesheetRef() const;
5942
5943 void writeSourceInfo(SourceLineInfo const& sourceInfo);
5944
5945 public: // StreamingReporterBase
5946
5947 void noMatchingTestCases(std::string const& s) override;
5948
5949 void testRunStarting(TestRunInfo const& testInfo) override;
5950
5951 void testGroupStarting(GroupInfo const& groupInfo) override;
5952
5953 void testCaseStarting(TestCaseInfo const& testInfo) override;
5954
5955 void sectionStarting(SectionInfo const& sectionInfo) override;
5956
5957 void assertionStarting(AssertionInfo const&) override;
5958
5959 bool assertionEnded(AssertionStats const& assertionStats) override;
5960
5961 void sectionEnded(SectionStats const& sectionStats) override;
5962
5963 void testCaseEnded(TestCaseStats const& testCaseStats) override;
5964
5965 void testGroupEnded(TestGroupStats const& testGroupStats) override;
5966
5967 void testRunEnded(TestRunStats const& testRunStats) override;
5968
5969 private:
5970 Timer m_testCaseTimer;
5971 XmlWriter m_xml;
5972 int m_sectionDepth = 0;
5973 };
5974
5975} // end namespace Catch
5976
5977// end catch_reporter_xml.h
5978
5979// end catch_external_interfaces.h
5980#endif
5981
5982#endif // ! CATCH_CONFIG_IMPL_ONLY
5983
5984#ifdef CATCH_IMPL
5985// start catch_impl.hpp
5986
5987#ifdef __clang__
5988#pragma clang diagnostic push
5989#pragma clang diagnostic ignored "-Wweak-vtables"
5990#endif
5991
5992// Keep these here for external reporters
5993// start catch_test_case_tracker.h
5994
5995#include <string>
5996#include <vector>
5997#include <memory>
5998
5999namespace Catch {
6000namespace TestCaseTracking {
6001
6002 struct NameAndLocation {
6004 SourceLineInfo location;
6005
6006 NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
6007 };
6008
6009 struct ITracker;
6010
6011 using ITrackerPtr = std::shared_ptr<ITracker>;
6012
6013 struct ITracker {
6014 virtual ~ITracker();
6015
6016 // static queries
6017 virtual NameAndLocation const& nameAndLocation() const = 0;
6018
6019 // dynamic queries
6020 virtual bool isComplete() const = 0; // Successfully completed or failed
6021 virtual bool isSuccessfullyCompleted() const = 0;
6022 virtual bool isOpen() const = 0; // Started but not complete
6023 virtual bool hasChildren() const = 0;
6024
6025 virtual ITracker& parent() = 0;
6026
6027 // actions
6028 virtual void close() = 0; // Successfully complete
6029 virtual void fail() = 0;
6030 virtual void markAsNeedingAnotherRun() = 0;
6031
6032 virtual void addChild( ITrackerPtr const& child ) = 0;
6033 virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
6034 virtual void openChild() = 0;
6035
6036 // Debug/ checking
6037 virtual bool isSectionTracker() const = 0;
6038 virtual bool isGeneratorTracker() const = 0;
6039 };
6040
6041 class TrackerContext {
6042
6043 enum RunState {
6044 NotStarted,
6045 Executing,
6046 CompletedCycle
6047 };
6048
6049 ITrackerPtr m_rootTracker;
6050 ITracker* m_currentTracker = nullptr;
6051 RunState m_runState = NotStarted;
6052
6053 public:
6054
6055 ITracker& startRun();
6056 void endRun();
6057
6058 void startCycle();
6059 void completeCycle();
6060
6061 bool completedCycle() const;
6062 ITracker& currentTracker();
6063 void setCurrentTracker( ITracker* tracker );
6064 };
6065
6066 class TrackerBase : public ITracker {
6067 protected:
6068 enum CycleState {
6069 NotStarted,
6070 Executing,
6071 ExecutingChildren,
6072 NeedsAnotherRun,
6073 CompletedSuccessfully,
6074 Failed
6075 };
6076
6077 using Children = std::vector<ITrackerPtr>;
6078 NameAndLocation m_nameAndLocation;
6079 TrackerContext& m_ctx;
6080 ITracker* m_parent;
6081 Children m_children;
6082 CycleState m_runState = NotStarted;
6083
6084 public:
6085 TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
6086
6087 NameAndLocation const& nameAndLocation() const override;
6088 bool isComplete() const override;
6089 bool isSuccessfullyCompleted() const override;
6090 bool isOpen() const override;
6091 bool hasChildren() const override;
6092
6093 void addChild( ITrackerPtr const& child ) override;
6094
6095 ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
6096 ITracker& parent() override;
6097
6098 void openChild() override;
6099
6100 bool isSectionTracker() const override;
6101 bool isGeneratorTracker() const override;
6102
6103 void open();
6104
6105 void close() override;
6106 void fail() override;
6107 void markAsNeedingAnotherRun() override;
6108
6109 private:
6110 void moveToParent();
6111 void moveToThis();
6112 };
6113
6114 class SectionTracker : public TrackerBase {
6115 std::vector<std::string> m_filters;
6116 public:
6117 SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
6118
6119 bool isSectionTracker() const override;
6120
6121 bool isComplete() const override;
6122
6123 static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
6124
6125 void tryOpen();
6126
6127 void addInitialFilters( std::vector<std::string> const& filters );
6128 void addNextFilters( std::vector<std::string> const& filters );
6129 };
6130
6131} // namespace TestCaseTracking
6132
6133using TestCaseTracking::ITracker;
6134using TestCaseTracking::TrackerContext;
6135using TestCaseTracking::SectionTracker;
6136
6137} // namespace Catch
6138
6139// end catch_test_case_tracker.h
6140
6141// start catch_leak_detector.h
6142
6143namespace Catch {
6144
6145 struct LeakDetector {
6146 LeakDetector();
6147 ~LeakDetector();
6148 };
6149
6150}
6151// end catch_leak_detector.h
6152// Cpp files will be included in the single-header file here
6153// start catch_approx.cpp
6154
6155#include <cmath>
6156#include <limits>
6157
6158namespace {
6159
6160// Performs equivalent check of std::fabs(lhs - rhs) <= margin
6161// But without the subtraction to allow for INFINITY in comparison
6162bool marginComparison(double lhs, double rhs, double margin) {
6163 return (lhs + margin >= rhs) && (rhs + margin >= lhs);
6164}
6165
6166}
6167
6168namespace Catch {
6169namespace Detail {
6170
6171 Approx::Approx ( double value )
6172 : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
6173 m_margin( 0.0 ),
6174 m_scale( 0.0 ),
6175 m_value( value )
6176 {}
6177
6178 Approx Approx::custom() {
6179 return Approx( 0 );
6180 }
6181
6182 Approx Approx::operator-() const {
6183 auto temp(*this);
6184 temp.m_value = -temp.m_value;
6185 return temp;
6186 }
6187
6188 std::string Approx::toString() const {
6189 ReusableStringStream rss;
6190 rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
6191 return rss.str();
6192 }
6193
6194 bool Approx::equalityComparisonImpl(const double other) const {
6195 // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
6196 // Thanks to Richard Harris for his help refining the scaled margin value
6197 return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
6198 }
6199
6200 void Approx::setMargin(double newMargin) {
6201 CATCH_ENFORCE(newMargin >= 0,
6202 "Invalid Approx::margin: " << newMargin << '.'
6203 << " Approx::Margin has to be non-negative.");
6204 m_margin = newMargin;
6205 }
6206
6207 void Approx::setEpsilon(double newEpsilon) {
6208 CATCH_ENFORCE(newEpsilon >= 0 && newEpsilon <= 1.0,
6209 "Invalid Approx::epsilon: " << newEpsilon << '.'
6210 << " Approx::epsilon has to be in [0, 1]");
6211 m_epsilon = newEpsilon;
6212 }
6213
6214} // end namespace Detail
6215
6216namespace literals {
6217 Detail::Approx operator "" _a(long double val) {
6218 return Detail::Approx(val);
6219 }
6220 Detail::Approx operator "" _a(unsigned long long val) {
6221 return Detail::Approx(val);
6222 }
6223} // end namespace literals
6224
6225std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
6226 return value.toString();
6227}
6228
6229} // end namespace Catch
6230// end catch_approx.cpp
6231// start catch_assertionhandler.cpp
6232
6233// start catch_debugger.h
6234
6235namespace Catch {
6236 bool isDebuggerActive();
6237}
6238
6239#ifdef CATCH_PLATFORM_MAC
6240
6241 #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
6242
6243#elif defined(CATCH_PLATFORM_LINUX)
6244 // If we can use inline assembler, do it because this allows us to break
6245 // directly at the location of the failing check instead of breaking inside
6246 // raise() called from it, i.e. one stack frame below.
6247 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
6248 #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
6249 #else // Fall back to the generic way.
6250 #include <signal.h>
6251
6252 #define CATCH_TRAP() raise(SIGTRAP)
6253 #endif
6254#elif defined(_MSC_VER)
6255 #define CATCH_TRAP() __debugbreak()
6256#elif defined(__MINGW32__)
6257 extern "C" __declspec(dllimport) void __stdcall DebugBreak();
6258 #define CATCH_TRAP() DebugBreak()
6259#endif
6260
6261#ifdef CATCH_TRAP
6262 #define CATCH_BREAK_INTO_DEBUGGER() []{ if( Catch::isDebuggerActive() ) { CATCH_TRAP(); } }()
6263#else
6264 #define CATCH_BREAK_INTO_DEBUGGER() []{}()
6265#endif
6266
6267// end catch_debugger.h
6268// start catch_run_context.h
6269
6270// start catch_fatal_condition.h
6271
6272// start catch_windows_h_proxy.h
6273
6274
6275#if defined(CATCH_PLATFORM_WINDOWS)
6276
6277#if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
6278# define CATCH_DEFINED_NOMINMAX
6279# define NOMINMAX
6280#endif
6281#if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
6282# define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
6283# define WIN32_LEAN_AND_MEAN
6284#endif
6285
6286#ifdef __AFXDLL
6287#include <AfxWin.h>
6288#else
6289#include <windows.h>
6290#endif
6291
6292#ifdef CATCH_DEFINED_NOMINMAX
6293# undef NOMINMAX
6294#endif
6295#ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
6296# undef WIN32_LEAN_AND_MEAN
6297#endif
6298
6299#endif // defined(CATCH_PLATFORM_WINDOWS)
6300
6301// end catch_windows_h_proxy.h
6302#if defined( CATCH_CONFIG_WINDOWS_SEH )
6303
6304namespace Catch {
6305
6306 struct FatalConditionHandler {
6307
6308 static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
6309 FatalConditionHandler();
6310 static void reset();
6311 ~FatalConditionHandler();
6312
6313 private:
6314 static bool isSet;
6315 static ULONG guaranteeSize;
6316 static PVOID exceptionHandlerHandle;
6317 };
6318
6319} // namespace Catch
6320
6321#elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
6322
6323#include <signal.h>
6324
6325namespace Catch {
6326
6327 struct FatalConditionHandler {
6328
6329 static bool isSet;
6330 static struct sigaction oldSigActions[];
6331 static stack_t oldSigStack;
6332 static char altStackMem[];
6333
6334 static void handleSignal( int sig );
6335
6336 FatalConditionHandler();
6337 ~FatalConditionHandler();
6338 static void reset();
6339 };
6340
6341} // namespace Catch
6342
6343#else
6344
6345namespace Catch {
6346 struct FatalConditionHandler {
6347 void reset();
6348 };
6349}
6350
6351#endif
6352
6353// end catch_fatal_condition.h
6354#include <string>
6355
6356namespace Catch {
6357
6358 struct IMutableContext;
6359
6360 ///////////////////////////////////////////////////////////////////////////
6361
6362 class RunContext : public IResultCapture, public IRunner {
6363
6364 public:
6365 RunContext( RunContext const& ) = delete;
6366 RunContext& operator =( RunContext const& ) = delete;
6367
6368 explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
6369
6370 ~RunContext() override;
6371
6372 void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
6373 void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
6374
6375 Totals runTest(TestCase const& testCase);
6376
6377 IConfigPtr config() const;
6378 IStreamingReporter& reporter() const;
6379
6380 public: // IResultCapture
6381
6382 // Assertion handlers
6383 void handleExpr
6384 ( AssertionInfo const& info,
6385 ITransientExpression const& expr,
6386 AssertionReaction& reaction ) override;
6387 void handleMessage
6388 ( AssertionInfo const& info,
6389 ResultWas::OfType resultType,
6390 StringRef const& message,
6391 AssertionReaction& reaction ) override;
6392 void handleUnexpectedExceptionNotThrown
6393 ( AssertionInfo const& info,
6394 AssertionReaction& reaction ) override;
6395 void handleUnexpectedInflightException
6396 ( AssertionInfo const& info,
6397 std::string const& message,
6398 AssertionReaction& reaction ) override;
6399 void handleIncomplete
6400 ( AssertionInfo const& info ) override;
6401 void handleNonExpr
6402 ( AssertionInfo const &info,
6403 ResultWas::OfType resultType,
6404 AssertionReaction &reaction ) override;
6405
6406 bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
6407
6408 void sectionEnded( SectionEndInfo const& endInfo ) override;
6409 void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
6410
6411 auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
6412
6413 void benchmarkStarting( BenchmarkInfo const& info ) override;
6414 void benchmarkEnded( BenchmarkStats const& stats ) override;
6415
6416 void pushScopedMessage( MessageInfo const& message ) override;
6417 void popScopedMessage( MessageInfo const& message ) override;
6418
6419 void emplaceUnscopedMessage( MessageBuilder const& builder ) override;
6420
6421 std::string getCurrentTestName() const override;
6422
6423 const AssertionResult* getLastResult() const override;
6424
6425 void exceptionEarlyReported() override;
6426
6427 void handleFatalErrorCondition( StringRef message ) override;
6428
6429 bool lastAssertionPassed() override;
6430
6431 void assertionPassed() override;
6432
6433 public:
6434 // !TBD We need to do this another way!
6435 bool aborting() const final;
6436
6437 private:
6438
6439 void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
6440 void invokeActiveTestCase();
6441
6442 void resetAssertionInfo();
6443 bool testForMissingAssertions( Counts& assertions );
6444
6445 void assertionEnded( AssertionResult const& result );
6446 void reportExpr
6447 ( AssertionInfo const &info,
6448 ResultWas::OfType resultType,
6449 ITransientExpression const *expr,
6450 bool negated );
6451
6452 void populateReaction( AssertionReaction& reaction );
6453
6454 private:
6455
6456 void handleUnfinishedSections();
6457
6458 TestRunInfo m_runInfo;
6459 IMutableContext& m_context;
6460 TestCase const* m_activeTestCase = nullptr;
6461 ITracker* m_testCaseTracker = nullptr;
6462 Option<AssertionResult> m_lastResult;
6463
6464 IConfigPtr m_config;
6465 Totals m_totals;
6466 IStreamingReporterPtr m_reporter;
6467 std::vector<MessageInfo> m_messages;
6468 std::vector<ScopedMessage> m_messageScopes; /* Keeps owners of so-called unscoped messages. */
6469 AssertionInfo m_lastAssertionInfo;
6470 std::vector<SectionEndInfo> m_unfinishedSections;
6471 std::vector<ITracker*> m_activeSections;
6472 TrackerContext m_trackerContext;
6473 bool m_lastAssertionPassed = false;
6474 bool m_shouldReportUnexpected = true;
6475 bool m_includeSuccessfulResults;
6476 };
6477
6478} // end namespace Catch
6479
6480// end catch_run_context.h
6481namespace Catch {
6482
6483 namespace {
6484 auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
6485 expr.streamReconstructedExpression( os );
6486 return os;
6487 }
6488 }
6489
6490 LazyExpression::LazyExpression( bool isNegated )
6491 : m_isNegated( isNegated )
6492 {}
6493
6494 LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
6495
6496 LazyExpression::operator bool() const {
6497 return m_transientExpression != nullptr;
6498 }
6499
6500 auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
6501 if( lazyExpr.m_isNegated )
6502 os << "!";
6503
6504 if( lazyExpr ) {
6505 if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
6506 os << "(" << *lazyExpr.m_transientExpression << ")";
6507 else
6508 os << *lazyExpr.m_transientExpression;
6509 }
6510 else {
6511 os << "{** error - unchecked empty expression requested **}";
6512 }
6513 return os;
6514 }
6515
6517 ( StringRef const& macroName,
6518 SourceLineInfo const& lineInfo,
6519 StringRef capturedExpression,
6520 ResultDisposition::Flags resultDisposition )
6521 : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
6522 m_resultCapture( getResultCapture() )
6523 {}
6524
6525 void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
6527 }
6528 void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
6530 }
6531
6532 auto AssertionHandler::allowThrows() const -> bool {
6533 return getCurrentContext().getConfig()->allowThrows();
6534 }
6535
6537 setCompleted();
6539
6540 // If you find your debugger stopping you here then go one level up on the
6541 // call-stack for the code that caused it (typically a failed assertion)
6542
6543 // (To go back to the test and change execution, jump over the throw, next)
6544 CATCH_BREAK_INTO_DEBUGGER();
6545 }
6546 if (m_reaction.shouldThrow) {
6547#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
6549#else
6550 CATCH_ERROR( "Test failure requires aborting test!" );
6551#endif
6552 }
6553 }
6555 m_completed = true;
6556 }
6557
6560 }
6561
6564 }
6567 }
6568
6571 }
6572
6575 }
6576
6577 // This is the overload that takes a string and infers the Equals matcher from it
6578 // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
6579 void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
6580 handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
6581 }
6582
6583} // namespace Catch
6584// end catch_assertionhandler.cpp
6585// start catch_assertionresult.cpp
6586
6587namespace Catch {
6588 AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
6589 lazyExpression(_lazyExpression),
6590 resultType(_resultType) {}
6591
6592 std::string AssertionResultData::reconstructExpression() const {
6593
6594 if( reconstructedExpression.empty() ) {
6595 if( lazyExpression ) {
6596 ReusableStringStream rss;
6597 rss << lazyExpression;
6598 reconstructedExpression = rss.str();
6599 }
6600 }
6601 return reconstructedExpression;
6602 }
6603
6604 AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
6605 : m_info( info ),
6606 m_resultData( data )
6607 {}
6608
6609 // Result was a success
6610 bool AssertionResult::succeeded() const {
6611 return Catch::isOk( m_resultData.resultType );
6612 }
6613
6614 // Result was a success, or failure is suppressed
6615 bool AssertionResult::isOk() const {
6616 return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
6617 }
6618
6619 ResultWas::OfType AssertionResult::getResultType() const {
6620 return m_resultData.resultType;
6621 }
6622
6623 bool AssertionResult::hasExpression() const {
6624 return m_info.capturedExpression[0] != 0;
6625 }
6626
6627 bool AssertionResult::hasMessage() const {
6628 return !m_resultData.message.empty();
6629 }
6630
6631 std::string AssertionResult::getExpression() const {
6632 if( isFalseTest( m_info.resultDisposition ) )
6633 return "!(" + m_info.capturedExpression + ")";
6634 else
6635 return m_info.capturedExpression;
6636 }
6637
6638 std::string AssertionResult::getExpressionInMacro() const {
6639 std::string expr;
6640 if( m_info.macroName[0] == 0 )
6641 expr = m_info.capturedExpression;
6642 else {
6643 expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
6644 expr += m_info.macroName;
6645 expr += "( ";
6646 expr += m_info.capturedExpression;
6647 expr += " )";
6648 }
6649 return expr;
6650 }
6651
6652 bool AssertionResult::hasExpandedExpression() const {
6653 return hasExpression() && getExpandedExpression() != getExpression();
6654 }
6655
6656 std::string AssertionResult::getExpandedExpression() const {
6657 std::string expr = m_resultData.reconstructExpression();
6658 return expr.empty()
6659 ? getExpression()
6660 : expr;
6661 }
6662
6663 std::string AssertionResult::getMessage() const {
6664 return m_resultData.message;
6665 }
6666 SourceLineInfo AssertionResult::getSourceInfo() const {
6667 return m_info.lineInfo;
6668 }
6669
6670 StringRef AssertionResult::getTestMacroName() const {
6671 return m_info.macroName;
6672 }
6673
6674} // end namespace Catch
6675// end catch_assertionresult.cpp
6676// start catch_benchmark.cpp
6677
6678namespace Catch {
6679
6680 auto BenchmarkLooper::getResolution() -> uint64_t {
6681 return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
6682 }
6683
6686 }
6688 auto elapsed = m_timer.getElapsedNanoseconds();
6689
6690 // Exponentially increasing iterations until we're confident in our timer resolution
6691 if( elapsed < m_resolution ) {
6692 m_iterationsToRun *= 10;
6693 return true;
6694 }
6695
6696 getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
6697 return false;
6698 }
6699
6700} // end namespace Catch
6701// end catch_benchmark.cpp
6702// start catch_capture_matchers.cpp
6703
6704namespace Catch {
6705
6706 using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
6707
6708 // This is the general overload that takes a any string matcher
6709 // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
6710 // the Equals matcher (so the header does not mention matchers)
6711 void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
6712 std::string exceptionMessage = Catch::translateActiveException();
6713 MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
6714 handler.handleExpr( expr );
6715 }
6716
6717} // namespace Catch
6718// end catch_capture_matchers.cpp
6719// start catch_commandline.cpp
6720
6721// start catch_commandline.h
6722
6723// start catch_clara.h
6724
6725// Use Catch's value for console width (store Clara's off to the side, if present)
6726#ifdef CLARA_CONFIG_CONSOLE_WIDTH
6727#define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
6728#undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
6729#endif
6730#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
6731
6732#ifdef __clang__
6733#pragma clang diagnostic push
6734#pragma clang diagnostic ignored "-Wweak-vtables"
6735#pragma clang diagnostic ignored "-Wexit-time-destructors"
6736#pragma clang diagnostic ignored "-Wshadow"
6737#endif
6738
6739// start clara.hpp
6740// Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
6741//
6742// Distributed under the Boost Software License, Version 1.0. (See accompanying
6743// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6744//
6745// See https://github.com/philsquared/Clara for more details
6746
6747// Clara v1.1.5
6748
6749
6750#ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
6751#define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
6752#endif
6753
6754#ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
6755#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
6756#endif
6757
6758#ifndef CLARA_CONFIG_OPTIONAL_TYPE
6759#ifdef __has_include
6760#if __has_include(<optional>) && __cplusplus >= 201703L
6761#include <optional>
6762#define CLARA_CONFIG_OPTIONAL_TYPE std::optional
6763#endif
6764#endif
6765#endif
6766
6767// ----------- #included from clara_textflow.hpp -----------
6768
6769// TextFlowCpp
6770//
6771// A single-header library for wrapping and laying out basic text, by Phil Nash
6772//
6773// Distributed under the Boost Software License, Version 1.0. (See accompanying
6774// file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6775//
6776// This project is hosted at https://github.com/philsquared/textflowcpp
6777
6778
6779#include <cassert>
6780#include <ostream>
6781#include <sstream>
6782#include <vector>
6783
6784#ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
6785#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
6786#endif
6787
6788namespace Catch {
6789namespace clara {
6790namespace TextFlow {
6791
6792inline auto isWhitespace(char c) -> bool {
6793 static std::string chars = " \t\n\r";
6794 return chars.find(c) != std::string::npos;
6795}
6796inline auto isBreakableBefore(char c) -> bool {
6797 static std::string chars = "[({<|";
6798 return chars.find(c) != std::string::npos;
6799}
6800inline auto isBreakableAfter(char c) -> bool {
6801 static std::string chars = "])}>.,:;*+-=&/\\";
6802 return chars.find(c) != std::string::npos;
6803}
6804
6805class Columns;
6806
6807class Column {
6808 std::vector<std::string> m_strings;
6809 size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
6810 size_t m_indent = 0;
6811 size_t m_initialIndent = std::string::npos;
6812
6813public:
6814 class iterator {
6815 friend Column;
6816
6817 Column const& m_column;
6818 size_t m_stringIndex = 0;
6819 size_t m_pos = 0;
6820
6821 size_t m_len = 0;
6822 size_t m_end = 0;
6823 bool m_suffix = false;
6824
6825 iterator(Column const& column, size_t stringIndex)
6826 : m_column(column),
6827 m_stringIndex(stringIndex) {}
6828
6829 auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
6830
6831 auto isBoundary(size_t at) const -> bool {
6832 assert(at > 0);
6833 assert(at <= line().size());
6834
6835 return at == line().size() ||
6836 (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
6837 isBreakableBefore(line()[at]) ||
6838 isBreakableAfter(line()[at - 1]);
6839 }
6840
6841 void calcLength() {
6842 assert(m_stringIndex < m_column.m_strings.size());
6843
6844 m_suffix = false;
6845 auto width = m_column.m_width - indent();
6846 m_end = m_pos;
6847 if (line()[m_pos] == '\n') {
6848 ++m_end;
6849 }
6850 while (m_end < line().size() && line()[m_end] != '\n')
6851 ++m_end;
6852
6853 if (m_end < m_pos + width) {
6854 m_len = m_end - m_pos;
6855 } else {
6856 size_t len = width;
6857 while (len > 0 && !isBoundary(m_pos + len))
6858 --len;
6859 while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
6860 --len;
6861
6862 if (len > 0) {
6863 m_len = len;
6864 } else {
6865 m_suffix = true;
6866 m_len = width - 1;
6867 }
6868 }
6869 }
6870
6871 auto indent() const -> size_t {
6872 auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
6873 return initial == std::string::npos ? m_column.m_indent : initial;
6874 }
6875
6876 auto addIndentAndSuffix(std::string const &plain) const -> std::string {
6877 return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
6878 }
6879
6880 public:
6881 using difference_type = std::ptrdiff_t;
6882 using value_type = std::string;
6883 using pointer = value_type * ;
6884 using reference = value_type & ;
6885 using iterator_category = std::forward_iterator_tag;
6886
6887 explicit iterator(Column const& column) : m_column(column) {
6888 assert(m_column.m_width > m_column.m_indent);
6889 assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
6890 calcLength();
6891 if (m_len == 0)
6892 m_stringIndex++; // Empty string
6893 }
6894
6895 auto operator *() const -> std::string {
6896 assert(m_stringIndex < m_column.m_strings.size());
6897 assert(m_pos <= m_end);
6898 return addIndentAndSuffix(line().substr(m_pos, m_len));
6899 }
6900
6901 auto operator ++() -> iterator& {
6902 m_pos += m_len;
6903 if (m_pos < line().size() && line()[m_pos] == '\n')
6904 m_pos += 1;
6905 else
6906 while (m_pos < line().size() && isWhitespace(line()[m_pos]))
6907 ++m_pos;
6908
6909 if (m_pos == line().size()) {
6910 m_pos = 0;
6911 ++m_stringIndex;
6912 }
6913 if (m_stringIndex < m_column.m_strings.size())
6914 calcLength();
6915 return *this;
6916 }
6917 auto operator ++(int) -> iterator {
6918 iterator prev(*this);
6919 operator++();
6920 return prev;
6921 }
6922
6923 auto operator ==(iterator const& other) const -> bool {
6924 return
6925 m_pos == other.m_pos &&
6926 m_stringIndex == other.m_stringIndex &&
6927 &m_column == &other.m_column;
6928 }
6929 auto operator !=(iterator const& other) const -> bool {
6930 return !operator==(other);
6931 }
6932 };
6933 using const_iterator = iterator;
6934
6935 explicit Column(std::string const& text) { m_strings.push_back(text); }
6936
6937 auto width(size_t newWidth) -> Column& {
6938 assert(newWidth > 0);
6939 m_width = newWidth;
6940 return *this;
6941 }
6942 auto indent(size_t newIndent) -> Column& {
6943 m_indent = newIndent;
6944 return *this;
6945 }
6946 auto initialIndent(size_t newIndent) -> Column& {
6947 m_initialIndent = newIndent;
6948 return *this;
6949 }
6950
6951 auto width() const -> size_t { return m_width; }
6952 auto begin() const -> iterator { return iterator(*this); }
6953 auto end() const -> iterator { return { *this, m_strings.size() }; }
6954
6955 inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
6956 bool first = true;
6957 for (auto line : col) {
6958 if (first)
6959 first = false;
6960 else
6961 os << "\n";
6962 os << line;
6963 }
6964 return os;
6965 }
6966
6967 auto operator + (Column const& other)->Columns;
6968
6969 auto toString() const -> std::string {
6971 oss << *this;
6972 return oss.str();
6973 }
6974};
6975
6976class Spacer : public Column {
6977
6978public:
6979 explicit Spacer(size_t spaceWidth) : Column("") {
6980 width(spaceWidth);
6981 }
6982};
6983
6984class Columns {
6985 std::vector<Column> m_columns;
6986
6987public:
6988
6989 class iterator {
6990 friend Columns;
6991 struct EndTag {};
6992
6993 std::vector<Column> const& m_columns;
6995 size_t m_activeIterators;
6996
6997 iterator(Columns const& columns, EndTag)
6998 : m_columns(columns.m_columns),
6999 m_activeIterators(0) {
7000 m_iterators.reserve(m_columns.size());
7001
7002 for (auto const& col : m_columns)
7003 m_iterators.push_back(col.end());
7004 }
7005
7006 public:
7007 using difference_type = std::ptrdiff_t;
7008 using value_type = std::string;
7009 using pointer = value_type * ;
7010 using reference = value_type & ;
7011 using iterator_category = std::forward_iterator_tag;
7012
7013 explicit iterator(Columns const& columns)
7014 : m_columns(columns.m_columns),
7015 m_activeIterators(m_columns.size()) {
7016 m_iterators.reserve(m_columns.size());
7017
7018 for (auto const& col : m_columns)
7019 m_iterators.push_back(col.begin());
7020 }
7021
7022 auto operator ==(iterator const& other) const -> bool {
7023 return m_iterators == other.m_iterators;
7024 }
7025 auto operator !=(iterator const& other) const -> bool {
7026 return m_iterators != other.m_iterators;
7027 }
7028 auto operator *() const -> std::string {
7029 std::string row, padding;
7030
7031 for (size_t i = 0; i < m_columns.size(); ++i) {
7032 auto width = m_columns[i].width();
7033 if (m_iterators[i] != m_columns[i].end()) {
7034 std::string col = *m_iterators[i];
7035 row += padding + col;
7036 if (col.size() < width)
7037 padding = std::string(width - col.size(), ' ');
7038 else
7039 padding = "";
7040 } else {
7041 padding += std::string(width, ' ');
7042 }
7043 }
7044 return row;
7045 }
7046 auto operator ++() -> iterator& {
7047 for (size_t i = 0; i < m_columns.size(); ++i) {
7048 if (m_iterators[i] != m_columns[i].end())
7049 ++m_iterators[i];
7050 }
7051 return *this;
7052 }
7053 auto operator ++(int) -> iterator {
7054 iterator prev(*this);
7055 operator++();
7056 return prev;
7057 }
7058 };
7059 using const_iterator = iterator;
7060
7061 auto begin() const -> iterator { return iterator(*this); }
7062 auto end() const -> iterator { return { *this, iterator::EndTag() }; }
7063
7064 auto operator += (Column const& col) -> Columns& {
7065 m_columns.push_back(col);
7066 return *this;
7067 }
7068 auto operator + (Column const& col) -> Columns {
7069 Columns combined = *this;
7070 combined += col;
7071 return combined;
7072 }
7073
7074 inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
7075
7076 bool first = true;
7077 for (auto line : cols) {
7078 if (first)
7079 first = false;
7080 else
7081 os << "\n";
7082 os << line;
7083 }
7084 return os;
7085 }
7086
7087 auto toString() const -> std::string {
7089 oss << *this;
7090 return oss.str();
7091 }
7092};
7093
7094inline auto Column::operator + (Column const& other) -> Columns {
7095 Columns cols;
7096 cols += *this;
7097 cols += other;
7098 return cols;
7099}
7100}
7101
7102}
7103}
7104
7105// ----------- end of #include from clara_textflow.hpp -----------
7106// ........... back in clara.hpp
7107
7108#include <cctype>
7109#include <string>
7110#include <memory>
7111#include <set>
7112#include <algorithm>
7113
7114#if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
7115#define CATCH_PLATFORM_WINDOWS
7116#endif
7117
7118namespace Catch { namespace clara {
7119namespace detail {
7120
7121 // Traits for extracting arg and return type of lambdas (for single argument lambdas)
7122 template<typename L>
7123 struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
7124
7125 template<typename ClassT, typename ReturnT, typename... Args>
7126 struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
7127 static const bool isValid = false;
7128 };
7129
7130 template<typename ClassT, typename ReturnT, typename ArgT>
7131 struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
7132 static const bool isValid = true;
7134 using ReturnType = ReturnT;
7135 };
7136
7137 class TokenStream;
7138
7139 // Transport for raw args (copied from main args, or supplied via init list for testing)
7140 class Args {
7141 friend TokenStream;
7142 std::string m_exeName;
7144
7145 public:
7146 Args( int argc, char const* const* argv )
7147 : m_exeName(argv[0]),
7148 m_args(argv + 1, argv + argc) {}
7149
7151 : m_exeName( *args.begin() ),
7152 m_args( args.begin()+1, args.end() )
7153 {}
7154
7155 auto exeName() const -> std::string {
7156 return m_exeName;
7157 }
7158 };
7159
7160 // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
7161 // may encode an option + its argument if the : or = form is used
7162 enum class TokenType {
7163 Option, Argument
7164 };
7165 struct Token {
7166 TokenType type;
7167 std::string token;
7168 };
7169
7170 inline auto isOptPrefix( char c ) -> bool {
7171 return c == '-'
7172#ifdef CATCH_PLATFORM_WINDOWS
7173 || c == '/'
7174#endif
7175 ;
7176 }
7177
7178 // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
7179 class TokenStream {
7181 Iterator it;
7182 Iterator itEnd;
7183 std::vector<Token> m_tokenBuffer;
7184
7185 void loadBuffer() {
7186 m_tokenBuffer.resize( 0 );
7187
7188 // Skip any empty strings
7189 while( it != itEnd && it->empty() )
7190 ++it;
7191
7192 if( it != itEnd ) {
7193 auto const &next = *it;
7194 if( isOptPrefix( next[0] ) ) {
7195 auto delimiterPos = next.find_first_of( " :=" );
7196 if( delimiterPos != std::string::npos ) {
7197 m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
7198 m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
7199 } else {
7200 if( next[1] != '-' && next.size() > 2 ) {
7201 std::string opt = "- ";
7202 for( size_t i = 1; i < next.size(); ++i ) {
7203 opt[1] = next[i];
7204 m_tokenBuffer.push_back( { TokenType::Option, opt } );
7205 }
7206 } else {
7207 m_tokenBuffer.push_back( { TokenType::Option, next } );
7208 }
7209 }
7210 } else {
7211 m_tokenBuffer.push_back( { TokenType::Argument, next } );
7212 }
7213 }
7214 }
7215
7216 public:
7217 explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
7218
7219 TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
7220 loadBuffer();
7221 }
7222
7223 explicit operator bool() const {
7224 return !m_tokenBuffer.empty() || it != itEnd;
7225 }
7226
7227 auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
7228
7229 auto operator*() const -> Token {
7230 assert( !m_tokenBuffer.empty() );
7231 return m_tokenBuffer.front();
7232 }
7233
7234 auto operator->() const -> Token const * {
7235 assert( !m_tokenBuffer.empty() );
7236 return &m_tokenBuffer.front();
7237 }
7238
7239 auto operator++() -> TokenStream & {
7240 if( m_tokenBuffer.size() >= 2 ) {
7241 m_tokenBuffer.erase( m_tokenBuffer.begin() );
7242 } else {
7243 if( it != itEnd )
7244 ++it;
7245 loadBuffer();
7246 }
7247 return *this;
7248 }
7249 };
7250
7251 class ResultBase {
7252 public:
7253 enum Type {
7254 Ok, LogicError, RuntimeError
7255 };
7256
7257 protected:
7258 ResultBase( Type type ) : m_type( type ) {}
7259 virtual ~ResultBase() = default;
7260
7261 virtual void enforceOk() const = 0;
7262
7263 Type m_type;
7264 };
7265
7266 template<typename T>
7267 class ResultValueBase : public ResultBase {
7268 public:
7269 auto value() const -> T const & {
7270 enforceOk();
7271 return m_value;
7272 }
7273
7274 protected:
7275 ResultValueBase( Type type ) : ResultBase( type ) {}
7276
7277 ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
7278 if( m_type == ResultBase::Ok )
7279 new( &m_value ) T( other.m_value );
7280 }
7281
7282 ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
7283 new( &m_value ) T( value );
7284 }
7285
7286 auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
7287 if( m_type == ResultBase::Ok )
7288 m_value.~T();
7289 ResultBase::operator=(other);
7290 if( m_type == ResultBase::Ok )
7291 new( &m_value ) T( other.m_value );
7292 return *this;
7293 }
7294
7295 ~ResultValueBase() override {
7296 if( m_type == Ok )
7297 m_value.~T();
7298 }
7299
7300 union {
7301 T m_value;
7302 };
7303 };
7304
7305 template<>
7306 class ResultValueBase<void> : public ResultBase {
7307 protected:
7308 using ResultBase::ResultBase;
7309 };
7310
7311 template<typename T = void>
7312 class BasicResult : public ResultValueBase<T> {
7313 public:
7314 template<typename U>
7315 explicit BasicResult( BasicResult<U> const &other )
7316 : ResultValueBase<T>( other.type() ),
7317 m_errorMessage( other.errorMessage() )
7318 {
7319 assert( type() != ResultBase::Ok );
7320 }
7321
7322 template<typename U>
7323 static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
7324 static auto ok() -> BasicResult { return { ResultBase::Ok }; }
7325 static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
7326 static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
7327
7328 explicit operator bool() const { return m_type == ResultBase::Ok; }
7329 auto type() const -> ResultBase::Type { return m_type; }
7330 auto errorMessage() const -> std::string { return m_errorMessage; }
7331
7332 protected:
7333 void enforceOk() const override {
7334
7335 // Errors shouldn't reach this point, but if they do
7336 // the actual error message will be in m_errorMessage
7337 assert( m_type != ResultBase::LogicError );
7338 assert( m_type != ResultBase::RuntimeError );
7339 if( m_type != ResultBase::Ok )
7340 std::abort();
7341 }
7342
7343 std::string m_errorMessage; // Only populated if resultType is an error
7344
7345 BasicResult( ResultBase::Type type, std::string const &message )
7346 : ResultValueBase<T>(type),
7347 m_errorMessage(message)
7348 {
7349 assert( m_type != ResultBase::Ok );
7350 }
7351
7352 using ResultValueBase<T>::ResultValueBase;
7353 using ResultBase::m_type;
7354 };
7355
7356 enum class ParseResultType {
7357 Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
7358 };
7359
7360 class ParseState {
7361 public:
7362
7363 ParseState( ParseResultType type, TokenStream const &remainingTokens )
7364 : m_type(type),
7365 m_remainingTokens( remainingTokens )
7366 {}
7367
7368 auto type() const -> ParseResultType { return m_type; }
7369 auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
7370
7371 private:
7372 ParseResultType m_type;
7373 TokenStream m_remainingTokens;
7374 };
7375
7376 using Result = BasicResult<void>;
7377 using ParserResult = BasicResult<ParseResultType>;
7378 using InternalParseResult = BasicResult<ParseState>;
7379
7380 struct HelpColumns {
7383 };
7384
7385 template<typename T>
7386 inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
7388 ss << source;
7389 ss >> target;
7390 if( ss.fail() )
7391 return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
7392 else
7393 return ParserResult::ok( ParseResultType::Matched );
7394 }
7395 inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
7396 target = source;
7397 return ParserResult::ok( ParseResultType::Matched );
7398 }
7399 inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
7400 std::string srcLC = source;
7401 std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( std::tolower(c) ); } );
7402 if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
7403 target = true;
7404 else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
7405 target = false;
7406 else
7407 return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
7408 return ParserResult::ok( ParseResultType::Matched );
7409 }
7410#ifdef CLARA_CONFIG_OPTIONAL_TYPE
7411 template<typename T>
7412 inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
7413 T temp;
7414 auto result = convertInto( source, temp );
7415 if( result )
7416 target = std::move(temp);
7417 return result;
7418 }
7419#endif // CLARA_CONFIG_OPTIONAL_TYPE
7420
7421 struct NonCopyable {
7422 NonCopyable() = default;
7423 NonCopyable( NonCopyable const & ) = delete;
7424 NonCopyable( NonCopyable && ) = delete;
7425 NonCopyable &operator=( NonCopyable const & ) = delete;
7426 NonCopyable &operator=( NonCopyable && ) = delete;
7427 };
7428
7429 struct BoundRef : NonCopyable {
7430 virtual ~BoundRef() = default;
7431 virtual auto isContainer() const -> bool { return false; }
7432 virtual auto isFlag() const -> bool { return false; }
7433 };
7434 struct BoundValueRefBase : BoundRef {
7435 virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
7436 };
7437 struct BoundFlagRefBase : BoundRef {
7438 virtual auto setFlag( bool flag ) -> ParserResult = 0;
7439 virtual auto isFlag() const -> bool { return true; }
7440 };
7441
7442 template<typename T>
7443 struct BoundValueRef : BoundValueRefBase {
7444 T &m_ref;
7445
7446 explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
7447
7448 auto setValue( std::string const &arg ) -> ParserResult override {
7449 return convertInto( arg, m_ref );
7450 }
7451 };
7452
7453 template<typename T>
7454 struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
7455 std::vector<T> &m_ref;
7456
7457 explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
7458
7459 auto isContainer() const -> bool override { return true; }
7460
7461 auto setValue( std::string const &arg ) -> ParserResult override {
7462 T temp;
7463 auto result = convertInto( arg, temp );
7464 if( result )
7465 m_ref.push_back( temp );
7466 return result;
7467 }
7468 };
7469
7470 struct BoundFlagRef : BoundFlagRefBase {
7471 bool &m_ref;
7472
7473 explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
7474
7475 auto setFlag( bool flag ) -> ParserResult override {
7476 m_ref = flag;
7477 return ParserResult::ok( ParseResultType::Matched );
7478 }
7479 };
7480
7481 template<typename ReturnType>
7482 struct LambdaInvoker {
7483 static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
7484
7485 template<typename L, typename ArgType>
7486 static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
7487 return lambda( arg );
7488 }
7489 };
7490
7491 template<>
7492 struct LambdaInvoker<void> {
7493 template<typename L, typename ArgType>
7494 static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
7495 lambda( arg );
7496 return ParserResult::ok( ParseResultType::Matched );
7497 }
7498 };
7499
7500 template<typename ArgType, typename L>
7501 inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
7502 ArgType temp{};
7503 auto result = convertInto( arg, temp );
7504 return !result
7505 ? result
7506 : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
7507 }
7508
7509 template<typename L>
7510 struct BoundLambda : BoundValueRefBase {
7511 L m_lambda;
7512
7513 static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
7514 explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
7515
7516 auto setValue( std::string const &arg ) -> ParserResult override {
7517 return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
7518 }
7519 };
7520
7521 template<typename L>
7522 struct BoundFlagLambda : BoundFlagRefBase {
7523 L m_lambda;
7524
7525 static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
7526 static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
7527
7528 explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
7529
7530 auto setFlag( bool flag ) -> ParserResult override {
7531 return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
7532 }
7533 };
7534
7535 enum class Optionality { Optional, Required };
7536
7537 struct Parser;
7538
7539 class ParserBase {
7540 public:
7541 virtual ~ParserBase() = default;
7542 virtual auto validate() const -> Result { return Result::ok(); }
7543 virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
7544 virtual auto cardinality() const -> size_t { return 1; }
7545
7546 auto parse( Args const &args ) const -> InternalParseResult {
7547 return parse( args.exeName(), TokenStream( args ) );
7548 }
7549 };
7550
7551 template<typename DerivedT>
7552 class ComposableParserImpl : public ParserBase {
7553 public:
7554 template<typename T>
7555 auto operator|( T const &other ) const -> Parser;
7556
7557 template<typename T>
7558 auto operator+( T const &other ) const -> Parser;
7559 };
7560
7561 // Common code and state for Args and Opts
7562 template<typename DerivedT>
7563 class ParserRefImpl : public ComposableParserImpl<DerivedT> {
7564 protected:
7565 Optionality m_optionality = Optionality::Optional;
7567 std::string m_hint;
7568 std::string m_description;
7569
7570 explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
7571
7572 public:
7573 template<typename T>
7574 ParserRefImpl( T &ref, std::string const &hint )
7575 : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
7576 m_hint( hint )
7577 {}
7578
7579 template<typename LambdaT>
7580 ParserRefImpl( LambdaT const &ref, std::string const &hint )
7581 : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
7582 m_hint(hint)
7583 {}
7584
7585 auto operator()( std::string const &description ) -> DerivedT & {
7586 m_description = description;
7587 return static_cast<DerivedT &>( *this );
7588 }
7589
7590 auto optional() -> DerivedT & {
7591 m_optionality = Optionality::Optional;
7592 return static_cast<DerivedT &>( *this );
7593 };
7594
7595 auto required() -> DerivedT & {
7596 m_optionality = Optionality::Required;
7597 return static_cast<DerivedT &>( *this );
7598 };
7599
7600 auto isOptional() const -> bool {
7601 return m_optionality == Optionality::Optional;
7602 }
7603
7604 auto cardinality() const -> size_t override {
7605 if( m_ref->isContainer() )
7606 return 0;
7607 else
7608 return 1;
7609 }
7610
7611 auto hint() const -> std::string { return m_hint; }
7612 };
7613
7614 class ExeName : public ComposableParserImpl<ExeName> {
7617
7618 template<typename LambdaT>
7619 static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
7620 return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
7621 }
7622
7623 public:
7624 ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
7625
7626 explicit ExeName( std::string &ref ) : ExeName() {
7628 }
7629
7630 template<typename LambdaT>
7631 explicit ExeName( LambdaT const& lambda ) : ExeName() {
7632 m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
7633 }
7634
7635 // The exe name is not parsed out of the normal tokens, but is handled specially
7636 auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
7637 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
7638 }
7639
7640 auto name() const -> std::string { return *m_name; }
7641 auto set( std::string const& newName ) -> ParserResult {
7642
7643 auto lastSlash = newName.find_last_of( "\\/" );
7644 auto filename = ( lastSlash == std::string::npos )
7645 ? newName
7646 : newName.substr( lastSlash+1 );
7647
7648 *m_name = filename;
7649 if( m_ref )
7650 return m_ref->setValue( filename );
7651 else
7652 return ParserResult::ok( ParseResultType::Matched );
7653 }
7654 };
7655
7656 class Arg : public ParserRefImpl<Arg> {
7657 public:
7658 using ParserRefImpl::ParserRefImpl;
7659
7660 auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
7661 auto validationResult = validate();
7662 if( !validationResult )
7663 return InternalParseResult( validationResult );
7664
7665 auto remainingTokens = tokens;
7666 auto const &token = *remainingTokens;
7667 if( token.type != TokenType::Argument )
7668 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
7669
7670 assert( !m_ref->isFlag() );
7671 auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
7672
7673 auto result = valueRef->setValue( remainingTokens->token );
7674 if( !result )
7675 return InternalParseResult( result );
7676 else
7677 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
7678 }
7679 };
7680
7681 inline auto normaliseOpt( std::string const &optName ) -> std::string {
7682#ifdef CATCH_PLATFORM_WINDOWS
7683 if( optName[0] == '/' )
7684 return "-" + optName.substr( 1 );
7685 else
7686#endif
7687 return optName;
7688 }
7689
7690 class Opt : public ParserRefImpl<Opt> {
7691 protected:
7692 std::vector<std::string> m_optNames;
7693
7694 public:
7695 template<typename LambdaT>
7696 explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
7697
7698 explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
7699
7700 template<typename LambdaT>
7701 Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
7702
7703 template<typename T>
7704 Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
7705
7706 auto operator[]( std::string const &optName ) -> Opt & {
7707 m_optNames.push_back( optName );
7708 return *this;
7709 }
7710
7711 auto getHelpColumns() const -> std::vector<HelpColumns> {
7713 bool first = true;
7714 for( auto const &opt : m_optNames ) {
7715 if (first)
7716 first = false;
7717 else
7718 oss << ", ";
7719 oss << opt;
7720 }
7721 if( !m_hint.empty() )
7722 oss << " <" << m_hint << ">";
7723 return { { oss.str(), m_description } };
7724 }
7725
7726 auto isMatch( std::string const &optToken ) const -> bool {
7727 auto normalisedToken = normaliseOpt( optToken );
7728 for( auto const &name : m_optNames ) {
7729 if( normaliseOpt( name ) == normalisedToken )
7730 return true;
7731 }
7732 return false;
7733 }
7734
7735 using ParserBase::parse;
7736
7737 auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
7738 auto validationResult = validate();
7739 if( !validationResult )
7740 return InternalParseResult( validationResult );
7741
7742 auto remainingTokens = tokens;
7743 if( remainingTokens && remainingTokens->type == TokenType::Option ) {
7744 auto const &token = *remainingTokens;
7745 if( isMatch(token.token ) ) {
7746 if( m_ref->isFlag() ) {
7747 auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
7748 auto result = flagRef->setFlag( true );
7749 if( !result )
7750 return InternalParseResult( result );
7751 if( result.value() == ParseResultType::ShortCircuitAll )
7752 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
7753 } else {
7754 auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
7755 ++remainingTokens;
7756 if( !remainingTokens )
7757 return InternalParseResult::runtimeError( "Expected argument following " + token.token );
7758 auto const &argToken = *remainingTokens;
7759 if( argToken.type != TokenType::Argument )
7760 return InternalParseResult::runtimeError( "Expected argument following " + token.token );
7761 auto result = valueRef->setValue( argToken.token );
7762 if( !result )
7763 return InternalParseResult( result );
7764 if( result.value() == ParseResultType::ShortCircuitAll )
7765 return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
7766 }
7767 return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
7768 }
7769 }
7770 return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
7771 }
7772
7773 auto validate() const -> Result override {
7774 if( m_optNames.empty() )
7775 return Result::logicError( "No options supplied to Opt" );
7776 for( auto const &name : m_optNames ) {
7777 if( name.empty() )
7778 return Result::logicError( "Option name cannot be empty" );
7779#ifdef CATCH_PLATFORM_WINDOWS
7780 if( name[0] != '-' && name[0] != '/' )
7781 return Result::logicError( "Option name must begin with '-' or '/'" );
7782#else
7783 if( name[0] != '-' )
7784 return Result::logicError( "Option name must begin with '-'" );
7785#endif
7786 }
7787 return ParserRefImpl::validate();
7788 }
7789 };
7790
7791 struct Help : Opt {
7792 Help( bool &showHelpFlag )
7793 : Opt([&]( bool flag ) {
7794 showHelpFlag = flag;
7795 return ParserResult::ok( ParseResultType::ShortCircuitAll );
7796 })
7797 {
7798 static_cast<Opt &>( *this )
7799 ("display usage information")
7800 ["-?"]["-h"]["--help"]
7801 .optional();
7802 }
7803 };
7804
7805 struct Parser : ParserBase {
7806
7807 mutable ExeName m_exeName;
7808 std::vector<Opt> m_options;
7809 std::vector<Arg> m_args;
7810
7811 auto operator|=( ExeName const &exeName ) -> Parser & {
7812 m_exeName = exeName;
7813 return *this;
7814 }
7815
7816 auto operator|=( Arg const &arg ) -> Parser & {
7817 m_args.push_back(arg);
7818 return *this;
7819 }
7820
7821 auto operator|=( Opt const &opt ) -> Parser & {
7822 m_options.push_back(opt);
7823 return *this;
7824 }
7825
7826 auto operator|=( Parser const &other ) -> Parser & {
7827 m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
7828 m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
7829 return *this;
7830 }
7831
7832 template<typename T>
7833 auto operator|( T const &other ) const -> Parser {
7834 return Parser( *this ) |= other;
7835 }
7836
7837 // Forward deprecated interface with '+' instead of '|'
7838 template<typename T>
7839 auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
7840 template<typename T>
7841 auto operator+( T const &other ) const -> Parser { return operator|( other ); }
7842
7843 auto getHelpColumns() const -> std::vector<HelpColumns> {
7845 for (auto const &o : m_options) {
7846 auto childCols = o.getHelpColumns();
7847 cols.insert( cols.end(), childCols.begin(), childCols.end() );
7848 }
7849 return cols;
7850 }
7851
7852 void writeToStream( std::ostream &os ) const {
7853 if (!m_exeName.name().empty()) {
7854 os << "usage:\n" << " " << m_exeName.name() << " ";
7855 bool required = true, first = true;
7856 for( auto const &arg : m_args ) {
7857 if (first)
7858 first = false;
7859 else
7860 os << " ";
7861 if( arg.isOptional() && required ) {
7862 os << "[";
7863 required = false;
7864 }
7865 os << "<" << arg.hint() << ">";
7866 if( arg.cardinality() == 0 )
7867 os << " ... ";
7868 }
7869 if( !required )
7870 os << "]";
7871 if( !m_options.empty() )
7872 os << " options";
7873 os << "\n\nwhere options are:" << std::endl;
7874 }
7875
7876 auto rows = getHelpColumns();
7877 size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
7878 size_t optWidth = 0;
7879 for( auto const &cols : rows )
7880 optWidth = (std::max)(optWidth, cols.left.size() + 2);
7881
7882 optWidth = (std::min)(optWidth, consoleWidth/2);
7883
7884 for( auto const &cols : rows ) {
7885 auto row =
7886 TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
7887 TextFlow::Spacer(4) +
7888 TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
7889 os << row << std::endl;
7890 }
7891 }
7892
7893 friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
7894 parser.writeToStream( os );
7895 return os;
7896 }
7897
7898 auto validate() const -> Result override {
7899 for( auto const &opt : m_options ) {
7900 auto result = opt.validate();
7901 if( !result )
7902 return result;
7903 }
7904 for( auto const &arg : m_args ) {
7905 auto result = arg.validate();
7906 if( !result )
7907 return result;
7908 }
7909 return Result::ok();
7910 }
7911
7912 using ParserBase::parse;
7913
7914 auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
7915
7916 struct ParserInfo {
7917 ParserBase const* parser = nullptr;
7918 size_t count = 0;
7919 };
7920 const size_t totalParsers = m_options.size() + m_args.size();
7921 assert( totalParsers < 512 );
7922 // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
7923 ParserInfo parseInfos[512];
7924
7925 {
7926 size_t i = 0;
7927 for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
7928 for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
7929 }
7930
7931 m_exeName.set( exeName );
7932
7933 auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
7934 while( result.value().remainingTokens() ) {
7935 bool tokenParsed = false;
7936
7937 for( size_t i = 0; i < totalParsers; ++i ) {
7938 auto& parseInfo = parseInfos[i];
7939 if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
7940 result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
7941 if (!result)
7942 return result;
7943 if (result.value().type() != ParseResultType::NoMatch) {
7944 tokenParsed = true;
7945 ++parseInfo.count;
7946 break;
7947 }
7948 }
7949 }
7950
7951 if( result.value().type() == ParseResultType::ShortCircuitAll )
7952 return result;
7953 if( !tokenParsed )
7954 return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
7955 }
7956 // !TBD Check missing required options
7957 return result;
7958 }
7959 };
7960
7961 template<typename DerivedT>
7962 template<typename T>
7963 auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
7964 return Parser() | static_cast<DerivedT const &>( *this ) | other;
7965 }
7966} // namespace detail
7967
7968// A Combined parser
7969using detail::Parser;
7970
7971// A parser for options
7972using detail::Opt;
7973
7974// A parser for arguments
7975using detail::Arg;
7976
7977// Wrapper for argc, argv from main()
7978using detail::Args;
7979
7980// Specifies the name of the executable
7981using detail::ExeName;
7982
7983// Convenience wrapper for option parser that specifies the help option
7984using detail::Help;
7985
7986// enum of result types from a parse
7987using detail::ParseResultType;
7988
7989// Result type for parser operation
7990using detail::ParserResult;
7991
7992}} // namespace Catch::clara
7993
7994// end clara.hpp
7995#ifdef __clang__
7996#pragma clang diagnostic pop
7997#endif
7998
7999// Restore Clara's value for console width, if present
8000#ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
8001#define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
8002#undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
8003#endif
8004
8005// end catch_clara.h
8006namespace Catch {
8007
8008 clara::Parser makeCommandLineParser( ConfigData& config );
8009
8010} // end namespace Catch
8011
8012// end catch_commandline.h
8013#include <fstream>
8014#include <ctime>
8015
8016namespace Catch {
8017
8018 clara::Parser makeCommandLineParser( ConfigData& config ) {
8019
8020 using namespace clara;
8021
8022 auto const setWarning = [&]( std::string const& warning ) {
8023 auto warningSet = [&]() {
8024 if( warning == "NoAssertions" )
8026
8027 if ( warning == "NoTests" )
8028 return WarnAbout::NoTests;
8029
8030 return WarnAbout::Nothing;
8031 }();
8032
8033 if (warningSet == WarnAbout::Nothing)
8034 return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
8035 config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
8036 return ParserResult::ok( ParseResultType::Matched );
8037 };
8038 auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
8039 std::ifstream f( filename.c_str() );
8040 if( !f.is_open() )
8041 return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
8042
8043 std::string line;
8044 while( std::getline( f, line ) ) {
8045 line = trim(line);
8046 if( !line.empty() && !startsWith( line, '#' ) ) {
8047 if( !startsWith( line, '"' ) )
8048 line = '"' + line + '"';
8049 config.testsOrTags.push_back( line + ',' );
8050 }
8051 }
8052 return ParserResult::ok( ParseResultType::Matched );
8053 };
8054 auto const setTestOrder = [&]( std::string const& order ) {
8055 if( startsWith( "declared", order ) )
8056 config.runOrder = RunTests::InDeclarationOrder;
8057 else if( startsWith( "lexical", order ) )
8058 config.runOrder = RunTests::InLexicographicalOrder;
8059 else if( startsWith( "random", order ) )
8060 config.runOrder = RunTests::InRandomOrder;
8061 else
8062 return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
8063 return ParserResult::ok( ParseResultType::Matched );
8064 };
8065 auto const setRngSeed = [&]( std::string const& seed ) {
8066 if( seed != "time" )
8067 return clara::detail::convertInto( seed, config.rngSeed );
8068 config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
8069 return ParserResult::ok( ParseResultType::Matched );
8070 };
8071 auto const setColourUsage = [&]( std::string const& useColour ) {
8072 auto mode = toLower( useColour );
8073
8074 if( mode == "yes" )
8075 config.useColour = UseColour::Yes;
8076 else if( mode == "no" )
8077 config.useColour = UseColour::No;
8078 else if( mode == "auto" )
8079 config.useColour = UseColour::Auto;
8080 else
8081 return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
8082 return ParserResult::ok( ParseResultType::Matched );
8083 };
8084 auto const setWaitForKeypress = [&]( std::string const& keypress ) {
8085 auto keypressLc = toLower( keypress );
8086 if( keypressLc == "start" )
8087 config.waitForKeypress = WaitForKeypress::BeforeStart;
8088 else if( keypressLc == "exit" )
8089 config.waitForKeypress = WaitForKeypress::BeforeExit;
8090 else if( keypressLc == "both" )
8091 config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
8092 else
8093 return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
8094 return ParserResult::ok( ParseResultType::Matched );
8095 };
8096 auto const setVerbosity = [&]( std::string const& verbosity ) {
8097 auto lcVerbosity = toLower( verbosity );
8098 if( lcVerbosity == "quiet" )
8099 config.verbosity = Verbosity::Quiet;
8100 else if( lcVerbosity == "normal" )
8101 config.verbosity = Verbosity::Normal;
8102 else if( lcVerbosity == "high" )
8103 config.verbosity = Verbosity::High;
8104 else
8105 return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
8106 return ParserResult::ok( ParseResultType::Matched );
8107 };
8108 auto const setReporter = [&]( std::string const& reporter ) {
8109 IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
8110
8111 auto lcReporter = toLower( reporter );
8112 auto result = factories.find( lcReporter );
8113
8114 if( factories.end() != result )
8115 config.reporterName = lcReporter;
8116 else
8117 return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
8118 return ParserResult::ok( ParseResultType::Matched );
8119 };
8120
8121 auto cli
8122 = ExeName( config.processName )
8123 | Help( config.showHelp )
8124 | Opt( config.listTests )
8125 ["-l"]["--list-tests"]
8126 ( "list all/matching test cases" )
8127 | Opt( config.listTags )
8128 ["-t"]["--list-tags"]
8129 ( "list all/matching tags" )
8130 | Opt( config.showSuccessfulTests )
8131 ["-s"]["--success"]
8132 ( "include successful tests in output" )
8133 | Opt( config.shouldDebugBreak )
8134 ["-b"]["--break"]
8135 ( "break into debugger on failure" )
8136 | Opt( config.noThrow )
8137 ["-e"]["--nothrow"]
8138 ( "skip exception tests" )
8139 | Opt( config.showInvisibles )
8140 ["-i"]["--invisibles"]
8141 ( "show invisibles (tabs, newlines)" )
8142 | Opt( config.outputFilename, "filename" )
8143 ["-o"]["--out"]
8144 ( "output filename" )
8145 | Opt( setReporter, "name" )
8146 ["-r"]["--reporter"]
8147 ( "reporter to use (defaults to console)" )
8148 | Opt( config.name, "name" )
8149 ["-n"]["--name"]
8150 ( "suite name" )
8151 | Opt( [&]( bool ){ config.abortAfter = 1; } )
8152 ["-a"]["--abort"]
8153 ( "abort at first failure" )
8154 | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
8155 ["-x"]["--abortx"]
8156 ( "abort after x failures" )
8157 | Opt( setWarning, "warning name" )
8158 ["-w"]["--warn"]
8159 ( "enable warnings" )
8160 | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
8161 ["-d"]["--durations"]
8162 ( "show test durations" )
8163 | Opt( loadTestNamesFromFile, "filename" )
8164 ["-f"]["--input-file"]
8165 ( "load test names to run from a file" )
8166 | Opt( config.filenamesAsTags )
8167 ["-#"]["--filenames-as-tags"]
8168 ( "adds a tag for the filename" )
8169 | Opt( config.sectionsToRun, "section name" )
8170 ["-c"]["--section"]
8171 ( "specify section to run" )
8172 | Opt( setVerbosity, "quiet|normal|high" )
8173 ["-v"]["--verbosity"]
8174 ( "set output verbosity" )
8175 | Opt( config.listTestNamesOnly )
8176 ["--list-test-names-only"]
8177 ( "list all/matching test cases names only" )
8178 | Opt( config.listReporters )
8179 ["--list-reporters"]
8180 ( "list all reporters" )
8181 | Opt( setTestOrder, "decl|lex|rand" )
8182 ["--order"]
8183 ( "test case order (defaults to decl)" )
8184 | Opt( setRngSeed, "'time'|number" )
8185 ["--rng-seed"]
8186 ( "set a specific seed for random numbers" )
8187 | Opt( setColourUsage, "yes|no" )
8188 ["--use-colour"]
8189 ( "should output be colourised" )
8190 | Opt( config.libIdentify )
8191 ["--libidentify"]
8192 ( "report name and version according to libidentify standard" )
8193 | Opt( setWaitForKeypress, "start|exit|both" )
8194 ["--wait-for-keypress"]
8195 ( "waits for a keypress before exiting" )
8196 | Opt( config.benchmarkResolutionMultiple, "multiplier" )
8197 ["--benchmark-resolution-multiple"]
8198 ( "multiple of clock resolution to run benchmarks" )
8199
8200 | Arg( config.testsOrTags, "test name|pattern|tags" )
8201 ( "which test or tests to use" );
8202
8203 return cli;
8204 }
8205
8206} // end namespace Catch
8207// end catch_commandline.cpp
8208// start catch_common.cpp
8209
8210#include <cstring>
8211#include <ostream>
8212
8213namespace Catch {
8214
8215 bool SourceLineInfo::empty() const noexcept {
8216 return file[0] == '\0';
8217 }
8218 bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
8219 return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
8220 }
8221 bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
8222 // We can assume that the same file will usually have the same pointer.
8223 // Thus, if the pointers are the same, there is no point in calling the strcmp
8224 return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
8225 }
8226
8227 std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
8228#ifndef __GNUG__
8229 os << info.file << '(' << info.line << ')';
8230#else
8231 os << info.file << ':' << info.line;
8232#endif
8233 return os;
8234 }
8235
8237 return std::string();
8238 }
8239
8240 NonCopyable::NonCopyable() = default;
8241 NonCopyable::~NonCopyable() = default;
8242
8243}
8244// end catch_common.cpp
8245// start catch_config.cpp
8246
8247namespace Catch {
8248
8249 Config::Config( ConfigData const& data )
8250 : m_data( data ),
8251 m_stream( openStream() )
8252 {
8253 TestSpecParser parser(ITagAliasRegistry::get());
8254 if (!data.testsOrTags.empty()) {
8255 m_hasTestFilters = true;
8256 for( auto const& testOrTags : data.testsOrTags )
8257 parser.parse( testOrTags );
8258 }
8259 m_testSpec = parser.testSpec();
8260 }
8261
8262 std::string const& Config::getFilename() const {
8263 return m_data.outputFilename ;
8264 }
8265
8266 bool Config::listTests() const { return m_data.listTests; }
8267 bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
8268 bool Config::listTags() const { return m_data.listTags; }
8269 bool Config::listReporters() const { return m_data.listReporters; }
8270
8271 std::string Config::getProcessName() const { return m_data.processName; }
8272 std::string const& Config::getReporterName() const { return m_data.reporterName; }
8273
8274 std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
8275 std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
8276
8277 TestSpec const& Config::testSpec() const { return m_testSpec; }
8278 bool Config::hasTestFilters() const { return m_hasTestFilters; }
8279
8280 bool Config::showHelp() const { return m_data.showHelp; }
8281
8282 // IConfig interface
8283 bool Config::allowThrows() const { return !m_data.noThrow; }
8284 std::ostream& Config::stream() const { return m_stream->stream(); }
8285 std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
8286 bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
8287 bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
8288 bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
8289 ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
8290 RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
8291 unsigned int Config::rngSeed() const { return m_data.rngSeed; }
8292 int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
8293 UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
8294 bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
8295 int Config::abortAfter() const { return m_data.abortAfter; }
8296 bool Config::showInvisibles() const { return m_data.showInvisibles; }
8297 Verbosity Config::verbosity() const { return m_data.verbosity; }
8298
8299 IStream const* Config::openStream() {
8300 return Catch::makeStream(m_data.outputFilename);
8301 }
8302
8303} // end namespace Catch
8304// end catch_config.cpp
8305// start catch_console_colour.cpp
8306
8307#if defined(__clang__)
8308# pragma clang diagnostic push
8309# pragma clang diagnostic ignored "-Wexit-time-destructors"
8310#endif
8311
8312// start catch_errno_guard.h
8313
8314namespace Catch {
8315
8316 class ErrnoGuard {
8317 public:
8318 ErrnoGuard();
8319 ~ErrnoGuard();
8320 private:
8321 int m_oldErrno;
8322 };
8323
8324}
8325
8326// end catch_errno_guard.h
8327#include <sstream>
8328
8329namespace Catch {
8330 namespace {
8331
8332 struct IColourImpl {
8333 virtual ~IColourImpl() = default;
8334 virtual void use( Colour::Code _colourCode ) = 0;
8335 };
8336
8337 struct NoColourImpl : IColourImpl {
8338 void use( Colour::Code ) {}
8339
8340 static IColourImpl* instance() {
8341 static NoColourImpl s_instance;
8342 return &s_instance;
8343 }
8344 };
8345
8346 } // anon namespace
8347} // namespace Catch
8348
8349#if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
8350# ifdef CATCH_PLATFORM_WINDOWS
8351# define CATCH_CONFIG_COLOUR_WINDOWS
8352# else
8353# define CATCH_CONFIG_COLOUR_ANSI
8354# endif
8355#endif
8356
8357#if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
8358
8359namespace Catch {
8360namespace {
8361
8362 class Win32ColourImpl : public IColourImpl {
8363 public:
8364 Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
8365 {
8366 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
8367 GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
8368 originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
8369 originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
8370 }
8371
8372 void use( Colour::Code _colourCode ) override {
8373 switch( _colourCode ) {
8374 case Colour::None: return setTextAttribute( originalForegroundAttributes );
8375 case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
8376 case Colour::Red: return setTextAttribute( FOREGROUND_RED );
8377 case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
8378 case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
8379 case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
8380 case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
8381 case Colour::Grey: return setTextAttribute( 0 );
8382
8383 case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
8384 case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
8385 case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
8386 case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
8387 case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
8388
8389 case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
8390
8391 default:
8392 CATCH_ERROR( "Unknown colour requested" );
8393 }
8394 }
8395
8396 private:
8397 void setTextAttribute( WORD _textAttribute ) {
8398 SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
8399 }
8400 HANDLE stdoutHandle;
8401 WORD originalForegroundAttributes;
8402 WORD originalBackgroundAttributes;
8403 };
8404
8405 IColourImpl* platformColourInstance() {
8406 static Win32ColourImpl s_instance;
8407
8409 UseColour::YesOrNo colourMode = config
8410 ? config->useColour()
8412 if( colourMode == UseColour::Auto )
8413 colourMode = UseColour::Yes;
8414 return colourMode == UseColour::Yes
8415 ? &s_instance
8416 : NoColourImpl::instance();
8417 }
8418
8419} // end anon namespace
8420} // end namespace Catch
8421
8422#elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
8423
8424#include <unistd.h>
8425
8426namespace Catch {
8427namespace {
8428
8429 // use POSIX/ ANSI console terminal codes
8430 // Thanks to Adam Strzelecki for original contribution
8431 // (http://github.com/nanoant)
8432 // https://github.com/philsquared/Catch/pull/131
8433 class PosixColourImpl : public IColourImpl {
8434 public:
8435 void use( Colour::Code _colourCode ) override {
8436 switch( _colourCode ) {
8437 case Colour::None:
8438 case Colour::White: return setColour( "[0m" );
8439 case Colour::Red: return setColour( "[0;31m" );
8440 case Colour::Green: return setColour( "[0;32m" );
8441 case Colour::Blue: return setColour( "[0;34m" );
8442 case Colour::Cyan: return setColour( "[0;36m" );
8443 case Colour::Yellow: return setColour( "[0;33m" );
8444 case Colour::Grey: return setColour( "[1;30m" );
8445
8446 case Colour::LightGrey: return setColour( "[0;37m" );
8447 case Colour::BrightRed: return setColour( "[1;31m" );
8448 case Colour::BrightGreen: return setColour( "[1;32m" );
8449 case Colour::BrightWhite: return setColour( "[1;37m" );
8450 case Colour::BrightYellow: return setColour( "[1;33m" );
8451
8452 case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
8453 default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
8454 }
8455 }
8456 static IColourImpl* instance() {
8457 static PosixColourImpl s_instance;
8458 return &s_instance;
8459 }
8460
8461 private:
8462 void setColour( const char* _escapeCode ) {
8463 getCurrentContext().getConfig()->stream()
8464 << '\033' << _escapeCode;
8465 }
8466 };
8467
8468 bool useColourOnPlatform() {
8469 return
8470#ifdef CATCH_PLATFORM_MAC
8471 !isDebuggerActive() &&
8472#endif
8473#if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
8474 isatty(STDOUT_FILENO)
8475#else
8476 false
8477#endif
8478 ;
8479 }
8480 IColourImpl* platformColourInstance() {
8481 ErrnoGuard guard;
8483 UseColour::YesOrNo colourMode = config
8484 ? config->useColour()
8486 if( colourMode == UseColour::Auto )
8487 colourMode = useColourOnPlatform()
8489 : UseColour::No;
8490 return colourMode == UseColour::Yes
8491 ? PosixColourImpl::instance()
8492 : NoColourImpl::instance();
8493 }
8494
8495} // end anon namespace
8496} // end namespace Catch
8497
8498#else // not Windows or ANSI ///////////////////////////////////////////////
8499
8500namespace Catch {
8501
8502 static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
8503
8504} // end namespace Catch
8505
8506#endif // Windows/ ANSI/ None
8507
8508namespace Catch {
8509
8510 Colour::Colour( Code _colourCode ) { use( _colourCode ); }
8511 Colour::Colour( Colour&& rhs ) noexcept {
8512 m_moved = rhs.m_moved;
8513 rhs.m_moved = true;
8514 }
8515 Colour& Colour::operator=( Colour&& rhs ) noexcept {
8516 m_moved = rhs.m_moved;
8517 rhs.m_moved = true;
8518 return *this;
8519 }
8520
8521 Colour::~Colour(){ if( !m_moved ) use( None ); }
8522
8523 void Colour::use( Code _colourCode ) {
8524 static IColourImpl* impl = platformColourInstance();
8525 impl->use( _colourCode );
8526 }
8527
8528 std::ostream& operator << ( std::ostream& os, Colour const& ) {
8529 return os;
8530 }
8531
8532} // end namespace Catch
8533
8534#if defined(__clang__)
8535# pragma clang diagnostic pop
8536#endif
8537
8538// end catch_console_colour.cpp
8539// start catch_context.cpp
8540
8541namespace Catch {
8542
8543 class Context : public IMutableContext, NonCopyable {
8544
8545 public: // IContext
8546 IResultCapture* getResultCapture() override {
8547 return m_resultCapture;
8548 }
8549 IRunner* getRunner() override {
8550 return m_runner;
8551 }
8552
8553 IConfigPtr const& getConfig() const override {
8554 return m_config;
8555 }
8556
8557 ~Context() override;
8558
8559 public: // IMutableContext
8560 void setResultCapture( IResultCapture* resultCapture ) override {
8561 m_resultCapture = resultCapture;
8562 }
8563 void setRunner( IRunner* runner ) override {
8564 m_runner = runner;
8565 }
8566 void setConfig( IConfigPtr const& config ) override {
8567 m_config = config;
8568 }
8569
8570 friend IMutableContext& getCurrentMutableContext();
8571
8572 private:
8573 IConfigPtr m_config;
8574 IRunner* m_runner = nullptr;
8575 IResultCapture* m_resultCapture = nullptr;
8576 };
8577
8578 IMutableContext *IMutableContext::currentContext = nullptr;
8579
8581 {
8582 currentContext = new Context();
8583 }
8584
8585 void cleanUpContext() {
8588 }
8589 IContext::~IContext() = default;
8591 Context::~Context() = default;
8592}
8593// end catch_context.cpp
8594// start catch_debug_console.cpp
8595
8596// start catch_debug_console.h
8597
8598#include <string>
8599
8600namespace Catch {
8601 void writeToDebugConsole( std::string const& text );
8602}
8603
8604// end catch_debug_console.h
8605#ifdef CATCH_PLATFORM_WINDOWS
8606
8607 namespace Catch {
8608 void writeToDebugConsole( std::string const& text ) {
8609 ::OutputDebugStringA( text.c_str() );
8610 }
8611 }
8612
8613#else
8614
8615 namespace Catch {
8616 void writeToDebugConsole( std::string const& text ) {
8617 // !TBD: Need a version for Mac/ XCode and other IDEs
8618 Catch::cout() << text;
8619 }
8620 }
8621
8622#endif // Platform
8623// end catch_debug_console.cpp
8624// start catch_debugger.cpp
8625
8626#ifdef CATCH_PLATFORM_MAC
8627
8628# include <assert.h>
8629# include <stdbool.h>
8630# include <sys/types.h>
8631# include <unistd.h>
8632# include <cstddef>
8633# include <ostream>
8634
8635#ifdef __apple_build_version__
8636 // These headers will only compile with AppleClang (XCode)
8637 // For other compilers (Clang, GCC, ... ) we need to exclude them
8638# include <sys/sysctl.h>
8639#endif
8640
8641 namespace Catch {
8642 #ifdef __apple_build_version__
8643 // The following function is taken directly from the following technical note:
8644 // https://developer.apple.com/library/archive/qa/qa1361/_index.html
8645
8646 // Returns true if the current process is being debugged (either
8647 // running under the debugger or has a debugger attached post facto).
8648 bool isDebuggerActive(){
8649 int mib[4];
8650 struct kinfo_proc info;
8652
8653 // Initialize the flags so that, if sysctl fails for some bizarre
8654 // reason, we get a predictable result.
8655
8656 info.kp_proc.p_flag = 0;
8657
8658 // Initialize mib, which tells sysctl the info we want, in this case
8659 // we're looking for information about a specific process ID.
8660
8661 mib[0] = CTL_KERN;
8662 mib[1] = KERN_PROC;
8663 mib[2] = KERN_PROC_PID;
8664 mib[3] = getpid();
8665
8666 // Call sysctl.
8667
8668 size = sizeof(info);
8669 if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
8670 Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
8671 return false;
8672 }
8673
8674 // We're being debugged if the P_TRACED flag is set.
8675
8676 return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
8677 }
8678 #else
8679 bool isDebuggerActive() {
8680 // We need to find another way to determine this for non-appleclang compilers on macOS
8681 return false;
8682 }
8683 #endif
8684 } // namespace Catch
8685
8686#elif defined(CATCH_PLATFORM_LINUX)
8687 #include <fstream>
8688 #include <string>
8689
8690 namespace Catch{
8691 // The standard POSIX way of detecting a debugger is to attempt to
8692 // ptrace() the process, but this needs to be done from a child and not
8693 // this process itself to still allow attaching to this process later
8694 // if wanted, so is rather heavy. Under Linux we have the PID of the
8695 // "debugger" (which doesn't need to be gdb, of course, it could also
8696 // be strace, for example) in /proc/$PID/status, so just get it from
8697 // there instead.
8698 bool isDebuggerActive(){
8699 // Libstdc++ has a bug, where std::ifstream sets errno to 0
8700 // This way our users can properly assert over errno values
8701 ErrnoGuard guard;
8702 std::ifstream in("/proc/self/status");
8703 for( std::string line; std::getline(in, line); ) {
8704 static const int PREFIX_LEN = 11;
8705 if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
8706 // We're traced if the PID is not 0 and no other PID starts
8707 // with 0 digit, so it's enough to check for just a single
8708 // character.
8709 return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
8710 }
8711 }
8712
8713 return false;
8714 }
8715 } // namespace Catch
8716#elif defined(_MSC_VER)
8717 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
8718 namespace Catch {
8719 bool isDebuggerActive() {
8720 return IsDebuggerPresent() != 0;
8721 }
8722 }
8723#elif defined(__MINGW32__)
8724 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
8725 namespace Catch {
8726 bool isDebuggerActive() {
8727 return IsDebuggerPresent() != 0;
8728 }
8729 }
8730#else
8731 namespace Catch {
8732 bool isDebuggerActive() { return false; }
8733 }
8734#endif // Platform
8735// end catch_debugger.cpp
8736// start catch_decomposer.cpp
8737
8738namespace Catch {
8739
8741
8742 void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
8743 if( lhs.size() + rhs.size() < 40 &&
8744 lhs.find('\n') == std::string::npos &&
8745 rhs.find('\n') == std::string::npos )
8746 os << lhs << " " << op << " " << rhs;
8747 else
8748 os << lhs << "\n" << op << "\n" << rhs;
8749 }
8750}
8751// end catch_decomposer.cpp
8752// start catch_enforce.cpp
8753
8754namespace Catch {
8755#if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
8756 [[noreturn]]
8757 void throw_exception(std::exception const& e) {
8758 Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
8759 << "The message was: " << e.what() << '\n';
8761 }
8762#endif
8763} // namespace Catch;
8764// end catch_enforce.cpp
8765// start catch_enum_values_registry.cpp
8766// start catch_enum_values_registry.h
8767
8768#include <vector>
8769#include <memory>
8770
8771namespace Catch {
8772
8773 namespace Detail {
8774
8775 std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values );
8776
8777 class EnumValuesRegistry : public IMutableEnumValuesRegistry {
8778
8780
8781 EnumInfo const& registerEnum( StringRef enumName, StringRef allEnums, std::vector<int> const& values) override;
8782 };
8783
8784 std::vector<std::string> parseEnums( StringRef enums );
8785
8786 } // Detail
8787
8788} // Catch
8789
8790// end catch_enum_values_registry.h
8791
8792#include <map>
8793#include <cassert>
8794
8795namespace Catch {
8796
8798
8799 namespace Detail {
8800
8801 std::vector<std::string> parseEnums( StringRef enums ) {
8802 auto enumValues = splitStringRef( enums, ',' );
8804 parsed.reserve( enumValues.size() );
8805 for( auto const& enumValue : enumValues ) {
8806 auto identifiers = splitStringRef( enumValue, ':' );
8807 parsed.push_back( Catch::trim( identifiers.back() ) );
8808 }
8809 return parsed;
8810 }
8811
8813
8814 StringRef EnumInfo::lookup( int value ) const {
8815 for( auto const& valueToName : m_values ) {
8816 if( valueToName.first == value )
8817 return valueToName.second;
8818 }
8819 return "{** unexpected enum value **}";
8820 }
8821
8822 std::unique_ptr<EnumInfo> makeEnumInfo( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
8823 std::unique_ptr<EnumInfo> enumInfo( new EnumInfo );
8824 enumInfo->m_name = enumName;
8825 enumInfo->m_values.reserve( values.size() );
8826
8827 const auto valueNames = Catch::Detail::parseEnums( allValueNames );
8828 assert( valueNames.size() == values.size() );
8829 std::size_t i = 0;
8830 for( auto value : values )
8831 enumInfo->m_values.push_back({ value, valueNames[i++] });
8832
8833 return enumInfo;
8834 }
8835
8836 EnumInfo const& EnumValuesRegistry::registerEnum( StringRef enumName, StringRef allValueNames, std::vector<int> const& values ) {
8837 auto enumInfo = makeEnumInfo( enumName, allValueNames, values );
8838 EnumInfo* raw = enumInfo.get();
8839 m_enumInfos.push_back( std::move( enumInfo ) );
8840 return *raw;
8841 }
8842
8843 } // Detail
8844} // Catch
8845
8846// end catch_enum_values_registry.cpp
8847// start catch_errno_guard.cpp
8848
8849#include <cerrno>
8850
8851namespace Catch {
8852 ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
8853 ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
8854}
8855// end catch_errno_guard.cpp
8856// start catch_exception_translator_registry.cpp
8857
8858// start catch_exception_translator_registry.h
8859
8860#include <vector>
8861#include <string>
8862#include <memory>
8863
8864namespace Catch {
8865
8866 class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
8867 public:
8868 ~ExceptionTranslatorRegistry();
8869 virtual void registerTranslator( const IExceptionTranslator* translator );
8870 std::string translateActiveException() const override;
8871 std::string tryTranslators() const;
8872
8873 private:
8875 };
8876}
8877
8878// end catch_exception_translator_registry.h
8879#ifdef __OBJC__
8880#import "Foundation/Foundation.h"
8881#endif
8882
8883namespace Catch {
8884
8885 ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
8886 }
8887
8888 void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
8889 m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
8890 }
8891
8892#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
8893 std::string ExceptionTranslatorRegistry::translateActiveException() const {
8894 try {
8895#ifdef __OBJC__
8896 // In Objective-C try objective-c exceptions first
8897 @try {
8898 return tryTranslators();
8899 }
8900 @catch (NSException *exception) {
8901 return Catch::Detail::stringify( [exception description] );
8902 }
8903#else
8904 // Compiling a mixed mode project with MSVC means that CLR
8905 // exceptions will be caught in (...) as well. However, these
8906 // do not fill-in std::current_exception and thus lead to crash
8907 // when attempting rethrow.
8908 // /EHa switch also causes structured exceptions to be caught
8909 // here, but they fill-in current_exception properly, so
8910 // at worst the output should be a little weird, instead of
8911 // causing a crash.
8912 if (std::current_exception() == nullptr) {
8913 return "Non C++ exception. Possibly a CLR exception.";
8914 }
8915 return tryTranslators();
8916#endif
8917 }
8918 catch( TestFailureException& ) {
8920 }
8921 catch( std::exception& ex ) {
8922 return ex.what();
8923 }
8924 catch( std::string& msg ) {
8925 return msg;
8926 }
8927 catch( const char* msg ) {
8928 return msg;
8929 }
8930 catch(...) {
8931 return "Unknown exception";
8932 }
8933 }
8934
8935 std::string ExceptionTranslatorRegistry::tryTranslators() const {
8936 if (m_translators.empty()) {
8938 } else {
8939 return m_translators[0]->translate(m_translators.begin() + 1, m_translators.end());
8940 }
8941 }
8942
8943#else // ^^ Exceptions are enabled // Exceptions are disabled vv
8944 std::string ExceptionTranslatorRegistry::translateActiveException() const {
8945 CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
8946 }
8947
8948 std::string ExceptionTranslatorRegistry::tryTranslators() const {
8949 CATCH_INTERNAL_ERROR("Attempted to use exception translators under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
8950 }
8951#endif
8952
8953}
8954// end catch_exception_translator_registry.cpp
8955// start catch_fatal_condition.cpp
8956
8957#if defined(__GNUC__)
8958# pragma GCC diagnostic push
8959# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
8960#endif
8961
8962#if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
8963
8964namespace {
8965 // Report the error condition
8966 void reportFatal( char const * const message ) {
8968 }
8969}
8970
8971#endif // signals/SEH handling
8972
8973#if defined( CATCH_CONFIG_WINDOWS_SEH )
8974
8975namespace Catch {
8976 struct SignalDefs { DWORD id; const char* name; };
8977
8978 // There is no 1-1 mapping between signals and windows exceptions.
8979 // Windows can easily distinguish between SO and SigSegV,
8980 // but SigInt, SigTerm, etc are handled differently.
8981 static SignalDefs signalDefs[] = {
8982 { static_cast<DWORD>(EXCEPTION_ILLEGAL_INSTRUCTION), "SIGILL - Illegal instruction signal" },
8983 { static_cast<DWORD>(EXCEPTION_STACK_OVERFLOW), "SIGSEGV - Stack overflow" },
8984 { static_cast<DWORD>(EXCEPTION_ACCESS_VIOLATION), "SIGSEGV - Segmentation violation signal" },
8985 { static_cast<DWORD>(EXCEPTION_INT_DIVIDE_BY_ZERO), "Divide by zero error" },
8986 };
8987
8988 LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
8989 for (auto const& def : signalDefs) {
8990 if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
8991 reportFatal(def.name);
8992 }
8993 }
8994 // If its not an exception we care about, pass it along.
8995 // This stops us from eating debugger breaks etc.
8996 return EXCEPTION_CONTINUE_SEARCH;
8997 }
8998
8999 FatalConditionHandler::FatalConditionHandler() {
9000 isSet = true;
9001 // 32k seems enough for Catch to handle stack overflow,
9002 // but the value was found experimentally, so there is no strong guarantee
9003 guaranteeSize = 32 * 1024;
9004 exceptionHandlerHandle = nullptr;
9005 // Register as first handler in current chain
9006 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
9007 // Pass in guarantee size to be filled
9008 SetThreadStackGuarantee(&guaranteeSize);
9009 }
9010
9011 void FatalConditionHandler::reset() {
9012 if (isSet) {
9013 RemoveVectoredExceptionHandler(exceptionHandlerHandle);
9014 SetThreadStackGuarantee(&guaranteeSize);
9015 exceptionHandlerHandle = nullptr;
9016 isSet = false;
9017 }
9018 }
9019
9020 FatalConditionHandler::~FatalConditionHandler() {
9021 reset();
9022 }
9023
9024bool FatalConditionHandler::isSet = false;
9025ULONG FatalConditionHandler::guaranteeSize = 0;
9026PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
9027
9028} // namespace Catch
9029
9030#elif defined( CATCH_CONFIG_POSIX_SIGNALS )
9031
9032namespace Catch {
9033
9034 struct SignalDefs {
9035 int id;
9036 const char* name;
9037 };
9038
9039 // 32kb for the alternate stack seems to be sufficient. However, this value
9040 // is experimentally determined, so that's not guaranteed.
9041 constexpr static std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
9042
9043 static SignalDefs signalDefs[] = {
9044 { SIGINT, "SIGINT - Terminal interrupt signal" },
9045 { SIGILL, "SIGILL - Illegal instruction signal" },
9046 { SIGFPE, "SIGFPE - Floating point error signal" },
9047 { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
9048 { SIGTERM, "SIGTERM - Termination request signal" },
9049 { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
9050 };
9051
9052 void FatalConditionHandler::handleSignal( int sig ) {
9053 char const * name = "<unknown signal>";
9054 for (auto const& def : signalDefs) {
9055 if (sig == def.id) {
9056 name = def.name;
9057 break;
9058 }
9059 }
9060 reset();
9061 reportFatal(name);
9062 raise( sig );
9063 }
9064
9065 FatalConditionHandler::FatalConditionHandler() {
9066 isSet = true;
9067 stack_t sigStack;
9068 sigStack.ss_sp = altStackMem;
9069 sigStack.ss_size = sigStackSize;
9070 sigStack.ss_flags = 0;
9071 sigaltstack(&sigStack, &oldSigStack);
9072 struct sigaction sa = { };
9073
9074 sa.sa_handler = handleSignal;
9075 sa.sa_flags = SA_ONSTACK;
9076 for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
9077 sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
9078 }
9079 }
9080
9081 FatalConditionHandler::~FatalConditionHandler() {
9082 reset();
9083 }
9084
9085 void FatalConditionHandler::reset() {
9086 if( isSet ) {
9087 // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
9088 for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
9089 sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
9090 }
9091 // Return the old stack
9092 sigaltstack(&oldSigStack, nullptr);
9093 isSet = false;
9094 }
9095 }
9096
9097 bool FatalConditionHandler::isSet = false;
9098 struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
9099 stack_t FatalConditionHandler::oldSigStack = {};
9100 char FatalConditionHandler::altStackMem[sigStackSize] = {};
9101
9102} // namespace Catch
9103
9104#else
9105
9106namespace Catch {
9107 void FatalConditionHandler::reset() {}
9108}
9109
9110#endif // signals/SEH handling
9111
9112#if defined(__GNUC__)
9113# pragma GCC diagnostic pop
9114#endif
9115// end catch_fatal_condition.cpp
9116// start catch_generators.cpp
9117
9118// start catch_random_number_generator.h
9119
9120#include <algorithm>
9121#include <random>
9122
9123namespace Catch {
9124
9125 struct IConfig;
9126
9127 std::mt19937& rng();
9128 void seedRng( IConfig const& config );
9129 unsigned int rngSeed();
9130
9131}
9132
9133// end catch_random_number_generator.h
9134#include <limits>
9135#include <set>
9136
9137namespace Catch {
9138
9140
9141const char* GeneratorException::what() const noexcept {
9142 return m_msg;
9143}
9144
9145namespace Generators {
9146
9148
9149 auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
9150 return getResultCapture().acquireGeneratorTracker( lineInfo );
9151 }
9152
9153} // namespace Generators
9154} // namespace Catch
9155// end catch_generators.cpp
9156// start catch_interfaces_capture.cpp
9157
9158namespace Catch {
9160}
9161// end catch_interfaces_capture.cpp
9162// start catch_interfaces_config.cpp
9163
9164namespace Catch {
9165 IConfig::~IConfig() = default;
9166}
9167// end catch_interfaces_config.cpp
9168// start catch_interfaces_exception.cpp
9169
9170namespace Catch {
9173}
9174// end catch_interfaces_exception.cpp
9175// start catch_interfaces_registry_hub.cpp
9176
9177namespace Catch {
9178 IRegistryHub::~IRegistryHub() = default;
9180}
9181// end catch_interfaces_registry_hub.cpp
9182// start catch_interfaces_reporter.cpp
9183
9184// start catch_reporter_listening.h
9185
9186namespace Catch {
9187
9188 class ListeningReporter : public IStreamingReporter {
9189 using Reporters = std::vector<IStreamingReporterPtr>;
9190 Reporters m_listeners;
9191 IStreamingReporterPtr m_reporter = nullptr;
9192 ReporterPreferences m_preferences;
9193
9194 public:
9195 ListeningReporter();
9196
9197 void addListener( IStreamingReporterPtr&& listener );
9198 void addReporter( IStreamingReporterPtr&& reporter );
9199
9200 public: // IStreamingReporter
9201
9202 ReporterPreferences getPreferences() const override;
9203
9204 void noMatchingTestCases( std::string const& spec ) override;
9205
9206 static std::set<Verbosity> getSupportedVerbosities();
9207
9208 void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
9209 void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override;
9210
9211 void testRunStarting( TestRunInfo const& testRunInfo ) override;
9212 void testGroupStarting( GroupInfo const& groupInfo ) override;
9213 void testCaseStarting( TestCaseInfo const& testInfo ) override;
9214 void sectionStarting( SectionInfo const& sectionInfo ) override;
9215 void assertionStarting( AssertionInfo const& assertionInfo ) override;
9216
9217 // The return value indicates if the messages buffer should be cleared:
9218 bool assertionEnded( AssertionStats const& assertionStats ) override;
9219 void sectionEnded( SectionStats const& sectionStats ) override;
9220 void testCaseEnded( TestCaseStats const& testCaseStats ) override;
9221 void testGroupEnded( TestGroupStats const& testGroupStats ) override;
9222 void testRunEnded( TestRunStats const& testRunStats ) override;
9223
9224 void skipTest( TestCaseInfo const& testInfo ) override;
9225 bool isMulti() const override;
9226
9227 };
9228
9229} // end namespace Catch
9230
9231// end catch_reporter_listening.h
9232namespace Catch {
9233
9234 ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
9235 : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
9236
9237 ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
9238 : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
9239
9240 std::ostream& ReporterConfig::stream() const { return *m_stream; }
9241 IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
9242
9243 TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
9244
9245 GroupInfo::GroupInfo( std::string const& _name,
9246 std::size_t _groupIndex,
9247 std::size_t _groupsCount )
9248 : name( _name ),
9249 groupIndex( _groupIndex ),
9250 groupsCounts( _groupsCount )
9251 {}
9252
9253 AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
9254 std::vector<MessageInfo> const& _infoMessages,
9255 Totals const& _totals )
9256 : assertionResult( _assertionResult ),
9257 infoMessages( _infoMessages ),
9258 totals( _totals )
9259 {
9260 assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
9261
9262 if( assertionResult.hasMessage() ) {
9263 // Copy message into messages list.
9264 // !TBD This should have been done earlier, somewhere
9265 MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
9266 builder << assertionResult.getMessage();
9267 builder.m_info.message = builder.m_stream.str();
9268
9269 infoMessages.push_back( builder.m_info );
9270 }
9271 }
9272
9273 AssertionStats::~AssertionStats() = default;
9274
9275 SectionStats::SectionStats( SectionInfo const& _sectionInfo,
9276 Counts const& _assertions,
9277 double _durationInSeconds,
9278 bool _missingAssertions )
9279 : sectionInfo( _sectionInfo ),
9280 assertions( _assertions ),
9281 durationInSeconds( _durationInSeconds ),
9282 missingAssertions( _missingAssertions )
9283 {}
9284
9285 SectionStats::~SectionStats() = default;
9286
9287 TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
9288 Totals const& _totals,
9289 std::string const& _stdOut,
9290 std::string const& _stdErr,
9291 bool _aborting )
9292 : testInfo( _testInfo ),
9293 totals( _totals ),
9294 stdOut( _stdOut ),
9295 stdErr( _stdErr ),
9296 aborting( _aborting )
9297 {}
9298
9299 TestCaseStats::~TestCaseStats() = default;
9300
9301 TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
9302 Totals const& _totals,
9303 bool _aborting )
9304 : groupInfo( _groupInfo ),
9305 totals( _totals ),
9306 aborting( _aborting )
9307 {}
9308
9309 TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
9310 : groupInfo( _groupInfo ),
9311 aborting( false )
9312 {}
9313
9314 TestGroupStats::~TestGroupStats() = default;
9315
9316 TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
9317 Totals const& _totals,
9318 bool _aborting )
9319 : runInfo( _runInfo ),
9320 totals( _totals ),
9321 aborting( _aborting )
9322 {}
9323
9324 TestRunStats::~TestRunStats() = default;
9325
9326 void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
9327 bool IStreamingReporter::isMulti() const { return false; }
9328
9329 IReporterFactory::~IReporterFactory() = default;
9330 IReporterRegistry::~IReporterRegistry() = default;
9331
9332} // end namespace Catch
9333// end catch_interfaces_reporter.cpp
9334// start catch_interfaces_runner.cpp
9335
9336namespace Catch {
9337 IRunner::~IRunner() = default;
9338}
9339// end catch_interfaces_runner.cpp
9340// start catch_interfaces_testcase.cpp
9341
9342namespace Catch {
9343 ITestInvoker::~ITestInvoker() = default;
9345}
9346// end catch_interfaces_testcase.cpp
9347// start catch_leak_detector.cpp
9348
9349#ifdef CATCH_CONFIG_WINDOWS_CRTDBG
9350#include <crtdbg.h>
9351
9352namespace Catch {
9353
9354 LeakDetector::LeakDetector() {
9355 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
9356 flag |= _CRTDBG_LEAK_CHECK_DF;
9357 flag |= _CRTDBG_ALLOC_MEM_DF;
9358 _CrtSetDbgFlag(flag);
9359 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
9360 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
9361 // Change this to leaking allocation's number to break there
9362 _CrtSetBreakAlloc(-1);
9363 }
9364}
9365
9366#else
9367
9368 Catch::LeakDetector::LeakDetector() {}
9369
9370#endif
9371
9372Catch::LeakDetector::~LeakDetector() {
9374}
9375// end catch_leak_detector.cpp
9376// start catch_list.cpp
9377
9378// start catch_list.h
9379
9380#include <set>
9381
9382namespace Catch {
9383
9384 std::size_t listTests( Config const& config );
9385
9386 std::size_t listTestsNamesOnly( Config const& config );
9387
9388 struct TagInfo {
9389 void add( std::string const& spelling );
9390 std::string all() const;
9391
9392 std::set<std::string> spellings;
9393 std::size_t count = 0;
9394 };
9395
9396 std::size_t listTags( Config const& config );
9397
9398 std::size_t listReporters();
9399
9400 Option<std::size_t> list( std::shared_ptr<Config> const& config );
9401
9402} // end namespace Catch
9403
9404// end catch_list.h
9405// start catch_text.h
9406
9407namespace Catch {
9408 using namespace clara::TextFlow;
9409}
9410
9411// end catch_text.h
9412#include <limits>
9413#include <algorithm>
9414#include <iomanip>
9415
9416namespace Catch {
9417
9418 std::size_t listTests( Config const& config ) {
9419 TestSpec testSpec = config.testSpec();
9420 if( config.hasTestFilters() )
9421 Catch::cout() << "Matching test cases:\n";
9422 else {
9423 Catch::cout() << "All available test cases:\n";
9424 }
9425
9426 auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
9427 for( auto const& testCaseInfo : matchedTestCases ) {
9428 Colour::Code colour = testCaseInfo.isHidden()
9429 ? Colour::SecondaryText
9430 : Colour::None;
9431 Colour colourGuard( colour );
9432
9433 Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
9434 if( config.verbosity() >= Verbosity::High ) {
9435 Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
9436 std::string description = testCaseInfo.description;
9437 if( description.empty() )
9438 description = "(NO DESCRIPTION)";
9439 Catch::cout() << Column( description ).indent(4) << std::endl;
9440 }
9441 if( !testCaseInfo.tags.empty() )
9442 Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
9443 }
9444
9445 if( !config.hasTestFilters() )
9446 Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
9447 else
9448 Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
9449 return matchedTestCases.size();
9450 }
9451
9452 std::size_t listTestsNamesOnly( Config const& config ) {
9453 TestSpec testSpec = config.testSpec();
9454 std::size_t matchedTests = 0;
9455 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
9456 for( auto const& testCaseInfo : matchedTestCases ) {
9457 matchedTests++;
9458 if( startsWith( testCaseInfo.name, '#' ) )
9459 Catch::cout() << '"' << testCaseInfo.name << '"';
9460 else
9461 Catch::cout() << testCaseInfo.name;
9462 if ( config.verbosity() >= Verbosity::High )
9463 Catch::cout() << "\t@" << testCaseInfo.lineInfo;
9465 }
9466 return matchedTests;
9467 }
9468
9469 void TagInfo::add( std::string const& spelling ) {
9470 ++count;
9471 spellings.insert( spelling );
9472 }
9473
9474 std::string TagInfo::all() const {
9475 std::string out;
9476 for( auto const& spelling : spellings )
9477 out += "[" + spelling + "]";
9478 return out;
9479 }
9480
9481 std::size_t listTags( Config const& config ) {
9482 TestSpec testSpec = config.testSpec();
9483 if( config.hasTestFilters() )
9484 Catch::cout() << "Tags for matching test cases:\n";
9485 else {
9486 Catch::cout() << "All available tags:\n";
9487 }
9488
9490
9491 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
9492 for( auto const& testCase : matchedTestCases ) {
9493 for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
9494 std::string lcaseTagName = toLower( tagName );
9495 auto countIt = tagCounts.find( lcaseTagName );
9496 if( countIt == tagCounts.end() )
9497 countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
9498 countIt->second.add( tagName );
9499 }
9500 }
9501
9502 for( auto const& tagCount : tagCounts ) {
9503 ReusableStringStream rss;
9504 rss << " " << std::setw(2) << tagCount.second.count << " ";
9505 auto str = rss.str();
9506 auto wrapper = Column( tagCount.second.all() )
9507 .initialIndent( 0 )
9508 .indent( str.size() )
9509 .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
9510 Catch::cout() << str << wrapper << '\n';
9511 }
9512 Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
9513 return tagCounts.size();
9514 }
9515
9516 std::size_t listReporters() {
9517 Catch::cout() << "Available reporters:\n";
9518 IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
9519 std::size_t maxNameLen = 0;
9520 for( auto const& factoryKvp : factories )
9521 maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
9522
9523 for( auto const& factoryKvp : factories ) {
9524 Catch::cout()
9525 << Column( factoryKvp.first + ":" )
9526 .indent(2)
9527 .width( 5+maxNameLen )
9528 + Column( factoryKvp.second->getDescription() )
9529 .initialIndent(0)
9530 .indent(2)
9531 .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
9532 << "\n";
9533 }
9535 return factories.size();
9536 }
9537
9538 Option<std::size_t> list( std::shared_ptr<Config> const& config ) {
9539 Option<std::size_t> listedCount;
9541 if( config->listTests() )
9542 listedCount = listedCount.valueOr(0) + listTests( *config );
9543 if( config->listTestNamesOnly() )
9544 listedCount = listedCount.valueOr(0) + listTestsNamesOnly( *config );
9545 if( config->listTags() )
9546 listedCount = listedCount.valueOr(0) + listTags( *config );
9547 if( config->listReporters() )
9548 listedCount = listedCount.valueOr(0) + listReporters();
9549 return listedCount;
9550 }
9551
9552} // end namespace Catch
9553// end catch_list.cpp
9554// start catch_matchers.cpp
9555
9556namespace Catch {
9557namespace Matchers {
9558 namespace Impl {
9559
9561 if( m_cachedToString.empty() )
9563 return m_cachedToString;
9564 }
9565
9567
9568 } // namespace Impl
9569} // namespace Matchers
9570
9571using namespace Matchers;
9572using Matchers::Impl::MatcherBase;
9573
9574} // namespace Catch
9575// end catch_matchers.cpp
9576// start catch_matchers_floating.cpp
9577
9578// start catch_polyfills.hpp
9579
9580namespace Catch {
9581 bool isnan(float f);
9582 bool isnan(double d);
9583}
9584
9585// end catch_polyfills.hpp
9586// start catch_to_string.hpp
9587
9588#include <string>
9589
9590namespace Catch {
9591 template <typename T>
9592 std::string to_string(T const& t) {
9593#if defined(CATCH_CONFIG_CPP11_TO_STRING)
9594 return std::to_string(t);
9595#else
9596 ReusableStringStream rss;
9597 rss << t;
9598 return rss.str();
9599#endif
9600 }
9601} // end namespace Catch
9602
9603// end catch_to_string.hpp
9604#include <cstdlib>
9605#include <cstdint>
9606#include <cstring>
9607
9608namespace Catch {
9609namespace Matchers {
9610namespace Floating {
9611enum class FloatingPointKind : uint8_t {
9612 Float,
9613 Double
9614};
9615}
9616}
9617}
9618
9619namespace {
9620
9621template <typename T>
9622struct Converter;
9623
9624template <>
9625struct Converter<float> {
9626 static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
9627 Converter(float f) {
9628 std::memcpy(&i, &f, sizeof(f));
9629 }
9630 int32_t i;
9631};
9632
9633template <>
9634struct Converter<double> {
9635 static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
9636 Converter(double d) {
9637 std::memcpy(&i, &d, sizeof(d));
9638 }
9639 int64_t i;
9640};
9641
9642template <typename T>
9643auto convert(T t) -> Converter<T> {
9644 return Converter<T>(t);
9645}
9646
9647template <typename FP>
9648bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
9649 // Comparison with NaN should always be false.
9650 // This way we can rule it out before getting into the ugly details
9651 if (Catch::isnan(lhs) || Catch::isnan(rhs)) {
9652 return false;
9653 }
9654
9655 auto lc = convert(lhs);
9656 auto rc = convert(rhs);
9657
9658 if ((lc.i < 0) != (rc.i < 0)) {
9659 // Potentially we can have +0 and -0
9660 return lhs == rhs;
9661 }
9662
9663 auto ulpDiff = std::abs(lc.i - rc.i);
9664 return ulpDiff <= maxUlpDiff;
9665}
9666
9667}
9668
9669namespace Catch {
9670namespace Matchers {
9671namespace Floating {
9672 WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
9673 :m_target{ target }, m_margin{ margin } {
9674 CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
9675 << " Margin has to be non-negative.");
9676 }
9677
9678 // Performs equivalent check of std::fabs(lhs - rhs) <= margin
9679 // But without the subtraction to allow for INFINITY in comparison
9680 bool WithinAbsMatcher::match(double const& matchee) const {
9681 return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
9682 }
9683
9684 std::string WithinAbsMatcher::describe() const {
9685 return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
9686 }
9687
9688 WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
9689 :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
9690 CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.'
9691 << " ULPs have to be non-negative.");
9692 }
9693
9694#if defined(__clang__)
9695#pragma clang diagnostic push
9696// Clang <3.5 reports on the default branch in the switch below
9697#pragma clang diagnostic ignored "-Wunreachable-code"
9698#endif
9699
9700 bool WithinUlpsMatcher::match(double const& matchee) const {
9701 switch (m_type) {
9702 case FloatingPointKind::Float:
9703 return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
9704 case FloatingPointKind::Double:
9705 return almostEqualUlps<double>(matchee, m_target, m_ulps);
9706 default:
9707 CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
9708 }
9709 }
9710
9711#if defined(__clang__)
9712#pragma clang diagnostic pop
9713#endif
9714
9715 std::string WithinUlpsMatcher::describe() const {
9716 return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
9717 }
9718
9719}// namespace Floating
9720
9721Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
9722 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
9723}
9724
9725Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
9726 return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
9727}
9728
9729Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
9730 return Floating::WithinAbsMatcher(target, margin);
9731}
9732
9733} // namespace Matchers
9734} // namespace Catch
9735
9736// end catch_matchers_floating.cpp
9737// start catch_matchers_generic.cpp
9738
9740 if (desc.empty()) {
9741 return "matches undescribed predicate";
9742 } else {
9743 return "matches predicate: \"" + desc + '"';
9744 }
9745}
9746// end catch_matchers_generic.cpp
9747// start catch_matchers_string.cpp
9748
9749#include <regex>
9750
9751namespace Catch {
9752namespace Matchers {
9753
9754 namespace StdString {
9755
9756 CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
9757 : m_caseSensitivity( caseSensitivity ),
9758 m_str( adjustString( str ) )
9759 {}
9760 std::string CasedString::adjustString( std::string const& str ) const {
9761 return m_caseSensitivity == CaseSensitive::No
9762 ? toLower( str )
9763 : str;
9764 }
9765 std::string CasedString::caseSensitivitySuffix() const {
9766 return m_caseSensitivity == CaseSensitive::No
9767 ? " (case insensitive)"
9768 : std::string();
9769 }
9770
9771 StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
9772 : m_comparator( comparator ),
9773 m_operation( operation ) {
9774 }
9775
9776 std::string StringMatcherBase::describe() const {
9777 std::string description;
9778 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
9779 m_comparator.caseSensitivitySuffix().size());
9780 description += m_operation;
9781 description += ": \"";
9782 description += m_comparator.m_str;
9783 description += "\"";
9784 description += m_comparator.caseSensitivitySuffix();
9785 return description;
9786 }
9787
9788 EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
9789
9790 bool EqualsMatcher::match( std::string const& source ) const {
9791 return m_comparator.adjustString( source ) == m_comparator.m_str;
9792 }
9793
9794 ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
9795
9796 bool ContainsMatcher::match( std::string const& source ) const {
9797 return contains( m_comparator.adjustString( source ), m_comparator.m_str );
9798 }
9799
9800 StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
9801
9802 bool StartsWithMatcher::match( std::string const& source ) const {
9803 return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
9804 }
9805
9806 EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
9807
9808 bool EndsWithMatcher::match( std::string const& source ) const {
9809 return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
9810 }
9811
9812 RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
9813
9814 bool RegexMatcher::match(std::string const& matchee) const {
9815 auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
9816 if (m_caseSensitivity == CaseSensitive::Choice::No) {
9817 flags |= std::regex::icase;
9818 }
9819 auto reg = std::regex(m_regex, flags);
9820 return std::regex_match(matchee, reg);
9821 }
9822
9823 std::string RegexMatcher::describe() const {
9824 return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
9825 }
9826
9827 } // namespace StdString
9828
9829 StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
9830 return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
9831 }
9832 StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
9833 return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
9834 }
9835 StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
9836 return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
9837 }
9838 StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
9839 return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
9840 }
9841
9842 StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
9843 return StdString::RegexMatcher(regex, caseSensitivity);
9844 }
9845
9846} // namespace Matchers
9847} // namespace Catch
9848// end catch_matchers_string.cpp
9849// start catch_message.cpp
9850
9851// start catch_uncaught_exceptions.h
9852
9853namespace Catch {
9854 bool uncaught_exceptions();
9855} // end namespace Catch
9856
9857// end catch_uncaught_exceptions.h
9858#include <cassert>
9859#include <stack>
9860
9861namespace Catch {
9862
9863 MessageInfo::MessageInfo( StringRef const& _macroName,
9864 SourceLineInfo const& _lineInfo,
9865 ResultWas::OfType _type )
9866 : macroName( _macroName ),
9867 lineInfo( _lineInfo ),
9868 type( _type ),
9869 sequence( ++globalCount )
9870 {}
9871
9872 bool MessageInfo::operator==( MessageInfo const& other ) const {
9873 return sequence == other.sequence;
9874 }
9875
9876 bool MessageInfo::operator<( MessageInfo const& other ) const {
9877 return sequence < other.sequence;
9878 }
9879
9880 // This may need protecting if threading support is added
9881 unsigned int MessageInfo::globalCount = 0;
9882
9883 ////////////////////////////////////////////////////////////////////////////
9884
9885 Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
9886 SourceLineInfo const& lineInfo,
9888 :m_info(macroName, lineInfo, type) {}
9889
9890 ////////////////////////////////////////////////////////////////////////////
9891
9892 ScopedMessage::ScopedMessage( MessageBuilder const& builder )
9893 : m_info( builder.m_info ), m_moved()
9894 {
9895 m_info.message = builder.m_stream.str();
9897 }
9898
9899 ScopedMessage::ScopedMessage( ScopedMessage&& old )
9900 : m_info( old.m_info ), m_moved()
9901 {
9902 old.m_moved = true;
9903 }
9904
9906 if ( !uncaught_exceptions() && !m_moved ){
9908 }
9909 }
9910
9911 Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
9912 auto trimmed = [&] (size_t start, size_t end) {
9913 while (names[start] == ',' || isspace(names[start])) {
9914 ++start;
9915 }
9916 while (names[end] == ',' || isspace(names[end])) {
9917 --end;
9918 }
9919 return names.substr(start, end - start + 1);
9920 };
9921 auto skipq = [&] (size_t start, char quote) {
9922 for (auto i = start + 1; i < names.size() ; ++i) {
9923 if (names[i] == quote)
9924 return i;
9925 if (names[i] == '\\')
9926 ++i;
9927 }
9928 CATCH_INTERNAL_ERROR("CAPTURE parsing encountered unmatched quote");
9929 };
9930
9931 size_t start = 0;
9932 std::stack<char> openings;
9933 for (size_t pos = 0; pos < names.size(); ++pos) {
9934 char c = names[pos];
9935 switch (c) {
9936 case '[':
9937 case '{':
9938 case '(':
9939 // It is basically impossible to disambiguate between
9940 // comparison and start of template args in this context
9941// case '<':
9942 openings.push(c);
9943 break;
9944 case ']':
9945 case '}':
9946 case ')':
9947// case '>':
9948 openings.pop();
9949 break;
9950 case '"':
9951 case '\'':
9952 pos = skipq(pos, c);
9953 break;
9954 case ',':
9955 if (start != pos && openings.size() == 0) {
9956 m_messages.emplace_back(macroName, lineInfo, resultType);
9957 m_messages.back().message = trimmed(start, pos);
9958 m_messages.back().message += " := ";
9959 start = pos;
9960 }
9961 }
9962 }
9963 assert(openings.size() == 0 && "Mismatched openings");
9964 m_messages.emplace_back(macroName, lineInfo, resultType);
9965 m_messages.back().message = trimmed(start, names.size() - 1);
9966 m_messages.back().message += " := ";
9967 }
9968 Capturer::~Capturer() {
9969 if ( !uncaught_exceptions() ){
9970 assert( m_captured == m_messages.size() );
9971 for( size_t i = 0; i < m_captured; ++i )
9972 m_resultCapture.popScopedMessage( m_messages[i] );
9973 }
9974 }
9975
9976 void Capturer::captureValue( size_t index, std::string const& value ) {
9977 assert( index < m_messages.size() );
9978 m_messages[index].message += value;
9979 m_resultCapture.pushScopedMessage( m_messages[index] );
9980 m_captured++;
9981 }
9982
9983} // end namespace Catch
9984// end catch_message.cpp
9985// start catch_output_redirect.cpp
9986
9987// start catch_output_redirect.h
9988#ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
9989#define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
9990
9991#include <cstdio>
9992#include <iosfwd>
9993#include <string>
9994
9995namespace Catch {
9996
9997 class RedirectedStream {
9998 std::ostream& m_originalStream;
9999 std::ostream& m_redirectionStream;
10000 std::streambuf* m_prevBuf;
10001
10002 public:
10003 RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
10004 ~RedirectedStream();
10005 };
10006
10007 class RedirectedStdOut {
10008 ReusableStringStream m_rss;
10009 RedirectedStream m_cout;
10010 public:
10011 RedirectedStdOut();
10012 auto str() const -> std::string;
10013 };
10014
10015 // StdErr has two constituent streams in C++, std::cerr and std::clog
10016 // This means that we need to redirect 2 streams into 1 to keep proper
10017 // order of writes
10018 class RedirectedStdErr {
10019 ReusableStringStream m_rss;
10020 RedirectedStream m_cerr;
10021 RedirectedStream m_clog;
10022 public:
10023 RedirectedStdErr();
10024 auto str() const -> std::string;
10025 };
10026
10027 class RedirectedStreams {
10028 public:
10029 RedirectedStreams(RedirectedStreams const&) = delete;
10030 RedirectedStreams& operator=(RedirectedStreams const&) = delete;
10031 RedirectedStreams(RedirectedStreams&&) = delete;
10032 RedirectedStreams& operator=(RedirectedStreams&&) = delete;
10033
10034 RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr);
10035 ~RedirectedStreams();
10036 private:
10037 std::string& m_redirectedCout;
10038 std::string& m_redirectedCerr;
10039 RedirectedStdOut m_redirectedStdOut;
10040 RedirectedStdErr m_redirectedStdErr;
10041 };
10042
10043#if defined(CATCH_CONFIG_NEW_CAPTURE)
10044
10045 // Windows's implementation of std::tmpfile is terrible (it tries
10046 // to create a file inside system folder, thus requiring elevated
10047 // privileges for the binary), so we have to use tmpnam(_s) and
10048 // create the file ourselves there.
10049 class TempFile {
10050 public:
10051 TempFile(TempFile const&) = delete;
10052 TempFile& operator=(TempFile const&) = delete;
10053 TempFile(TempFile&&) = delete;
10054 TempFile& operator=(TempFile&&) = delete;
10055
10056 TempFile();
10057 ~TempFile();
10058
10059 std::FILE* getFile();
10060 std::string getContents();
10061
10062 private:
10063 std::FILE* m_file = nullptr;
10064 #if defined(_MSC_VER)
10065 char m_buffer[L_tmpnam] = { 0 };
10066 #endif
10067 };
10068
10069 class OutputRedirect {
10070 public:
10071 OutputRedirect(OutputRedirect const&) = delete;
10072 OutputRedirect& operator=(OutputRedirect const&) = delete;
10073 OutputRedirect(OutputRedirect&&) = delete;
10074 OutputRedirect& operator=(OutputRedirect&&) = delete;
10075
10076 OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
10077 ~OutputRedirect();
10078
10079 private:
10080 int m_originalStdout = -1;
10081 int m_originalStderr = -1;
10082 TempFile m_stdoutFile;
10083 TempFile m_stderrFile;
10084 std::string& m_stdoutDest;
10085 std::string& m_stderrDest;
10086 };
10087
10088#endif
10089
10090} // end namespace Catch
10091
10092#endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
10093// end catch_output_redirect.h
10094#include <cstdio>
10095#include <cstring>
10096#include <fstream>
10097#include <sstream>
10098#include <stdexcept>
10099
10100#if defined(CATCH_CONFIG_NEW_CAPTURE)
10101 #if defined(_MSC_VER)
10102 #include <io.h> //_dup and _dup2
10103 #define dup _dup
10104 #define dup2 _dup2
10105 #define fileno _fileno
10106 #else
10107 #include <unistd.h> // dup and dup2
10108 #endif
10109#endif
10110
10111namespace Catch {
10112
10113 RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
10114 : m_originalStream( originalStream ),
10115 m_redirectionStream( redirectionStream ),
10116 m_prevBuf( m_originalStream.rdbuf() )
10117 {
10118 m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
10119 }
10120
10121 RedirectedStream::~RedirectedStream() {
10122 m_originalStream.rdbuf( m_prevBuf );
10123 }
10124
10125 RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
10126 auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
10127
10128 RedirectedStdErr::RedirectedStdErr()
10129 : m_cerr( Catch::cerr(), m_rss.get() ),
10130 m_clog( Catch::clog(), m_rss.get() )
10131 {}
10132 auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
10133
10134 RedirectedStreams::RedirectedStreams(std::string& redirectedCout, std::string& redirectedCerr)
10135 : m_redirectedCout(redirectedCout),
10136 m_redirectedCerr(redirectedCerr)
10137 {}
10138
10139 RedirectedStreams::~RedirectedStreams() {
10140 m_redirectedCout += m_redirectedStdOut.str();
10141 m_redirectedCerr += m_redirectedStdErr.str();
10142 }
10143
10144#if defined(CATCH_CONFIG_NEW_CAPTURE)
10145
10146#if defined(_MSC_VER)
10147 TempFile::TempFile() {
10148 if (tmpnam_s(m_buffer)) {
10149 CATCH_RUNTIME_ERROR("Could not get a temp filename");
10150 }
10151 if (fopen_s(&m_file, m_buffer, "w")) {
10152 char buffer[100];
10153 if (strerror_s(buffer, errno)) {
10154 CATCH_RUNTIME_ERROR("Could not translate errno to a string");
10155 }
10156 CATCH_RUNTIME_ERROR("Could not open the temp file: '" << m_buffer << "' because: " << buffer);
10157 }
10158 }
10159#else
10160 TempFile::TempFile() {
10161 m_file = std::tmpfile();
10162 if (!m_file) {
10163 CATCH_RUNTIME_ERROR("Could not create a temp file.");
10164 }
10165 }
10166
10167#endif
10168
10169 TempFile::~TempFile() {
10170 // TBD: What to do about errors here?
10171 std::fclose(m_file);
10172 // We manually create the file on Windows only, on Linux
10173 // it will be autodeleted
10174#if defined(_MSC_VER)
10175 std::remove(m_buffer);
10176#endif
10177 }
10178
10179 FILE* TempFile::getFile() {
10180 return m_file;
10181 }
10182
10183 std::string TempFile::getContents() {
10184 std::stringstream sstr;
10185 char buffer[100] = {};
10186 std::rewind(m_file);
10187 while (std::fgets(buffer, sizeof(buffer), m_file)) {
10188 sstr << buffer;
10189 }
10190 return sstr.str();
10191 }
10192
10193 OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
10194 m_originalStdout(dup(1)),
10195 m_originalStderr(dup(2)),
10196 m_stdoutDest(stdout_dest),
10197 m_stderrDest(stderr_dest) {
10198 dup2(fileno(m_stdoutFile.getFile()), 1);
10199 dup2(fileno(m_stderrFile.getFile()), 2);
10200 }
10201
10202 OutputRedirect::~OutputRedirect() {
10204 fflush(stdout);
10205 // Since we support overriding these streams, we flush cerr
10206 // even though std::cerr is unbuffered
10209 fflush(stderr);
10210
10211 dup2(m_originalStdout, 1);
10212 dup2(m_originalStderr, 2);
10213
10214 m_stdoutDest += m_stdoutFile.getContents();
10215 m_stderrDest += m_stderrFile.getContents();
10216 }
10217
10218#endif // CATCH_CONFIG_NEW_CAPTURE
10219
10220} // namespace Catch
10221
10222#if defined(CATCH_CONFIG_NEW_CAPTURE)
10223 #if defined(_MSC_VER)
10224 #undef dup
10225 #undef dup2
10226 #undef fileno
10227 #endif
10228#endif
10229// end catch_output_redirect.cpp
10230// start catch_polyfills.cpp
10231
10232#include <cmath>
10233
10234namespace Catch {
10235
10236#if !defined(CATCH_CONFIG_POLYFILL_ISNAN)
10237 bool isnan(float f) {
10238 return std::isnan(f);
10239 }
10240 bool isnan(double d) {
10241 return std::isnan(d);
10242 }
10243#else
10244 // For now we only use this for embarcadero
10245 bool isnan(float f) {
10246 return std::_isnan(f);
10247 }
10248 bool isnan(double d) {
10249 return std::_isnan(d);
10250 }
10251#endif
10252
10253} // end namespace Catch
10254// end catch_polyfills.cpp
10255// start catch_random_number_generator.cpp
10256
10257namespace Catch {
10258
10259 std::mt19937& rng() {
10260 static std::mt19937 s_rng;
10261 return s_rng;
10262 }
10263
10264 void seedRng( IConfig const& config ) {
10265 if( config.rngSeed() != 0 ) {
10266 std::srand( config.rngSeed() );
10267 rng().seed( config.rngSeed() );
10268 }
10269 }
10270
10271 unsigned int rngSeed() {
10272 return getCurrentContext().getConfig()->rngSeed();
10273 }
10274}
10275// end catch_random_number_generator.cpp
10276// start catch_registry_hub.cpp
10277
10278// start catch_test_case_registry_impl.h
10279
10280#include <vector>
10281#include <set>
10282#include <algorithm>
10283#include <ios>
10284
10285namespace Catch {
10286
10287 class TestCase;
10288 struct IConfig;
10289
10290 std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
10291 bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
10292
10293 void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
10294
10295 std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
10296 std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
10297
10298 class TestRegistry : public ITestCaseRegistry {
10299 public:
10300 virtual ~TestRegistry() = default;
10301
10302 virtual void registerTest( TestCase const& testCase );
10303
10304 std::vector<TestCase> const& getAllTests() const override;
10305 std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
10306
10307 private:
10308 std::vector<TestCase> m_functions;
10309 mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
10310 mutable std::vector<TestCase> m_sortedFunctions;
10311 std::size_t m_unnamedCount = 0;
10312 std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
10313 };
10314
10315 ///////////////////////////////////////////////////////////////////////////
10316
10317 class TestInvokerAsFunction : public ITestInvoker {
10318 void(*m_testAsFunction)();
10319 public:
10320 TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
10321
10322 void invoke() const override;
10323 };
10324
10325 std::string extractClassName( StringRef const& classOrQualifiedMethodName );
10326
10327 ///////////////////////////////////////////////////////////////////////////
10328
10329} // end namespace Catch
10330
10331// end catch_test_case_registry_impl.h
10332// start catch_reporter_registry.h
10333
10334#include <map>
10335
10336namespace Catch {
10337
10338 class ReporterRegistry : public IReporterRegistry {
10339
10340 public:
10341
10342 ~ReporterRegistry() override;
10343
10344 IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
10345
10346 void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
10347 void registerListener( IReporterFactoryPtr const& factory );
10348
10349 FactoryMap const& getFactories() const override;
10350 Listeners const& getListeners() const override;
10351
10352 private:
10353 FactoryMap m_factories;
10354 Listeners m_listeners;
10355 };
10356}
10357
10358// end catch_reporter_registry.h
10359// start catch_tag_alias_registry.h
10360
10361// start catch_tag_alias.h
10362
10363#include <string>
10364
10365namespace Catch {
10366
10367 struct TagAlias {
10368 TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
10369
10370 std::string tag;
10371 SourceLineInfo lineInfo;
10372 };
10373
10374} // end namespace Catch
10375
10376// end catch_tag_alias.h
10377#include <map>
10378
10379namespace Catch {
10380
10381 class TagAliasRegistry : public ITagAliasRegistry {
10382 public:
10383 ~TagAliasRegistry() override;
10384 TagAlias const* find( std::string const& alias ) const override;
10385 std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
10386 void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
10387
10388 private:
10390 };
10391
10392} // end namespace Catch
10393
10394// end catch_tag_alias_registry.h
10395// start catch_startup_exception_registry.h
10396
10397#include <vector>
10398#include <exception>
10399
10400namespace Catch {
10401
10402 class StartupExceptionRegistry {
10403 public:
10404 void add(std::exception_ptr const& exception) noexcept;
10405 std::vector<std::exception_ptr> const& getExceptions() const noexcept;
10406 private:
10407 std::vector<std::exception_ptr> m_exceptions;
10408 };
10409
10410} // end namespace Catch
10411
10412// end catch_startup_exception_registry.h
10413// start catch_singletons.hpp
10414
10415namespace Catch {
10416
10417 struct ISingleton {
10418 virtual ~ISingleton();
10419 };
10420
10421 void addSingleton( ISingleton* singleton );
10422 void cleanupSingletons();
10423
10424 template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
10425 class Singleton : SingletonImplT, public ISingleton {
10426
10427 static auto getInternal() -> Singleton* {
10428 static Singleton* s_instance = nullptr;
10429 if( !s_instance ) {
10430 s_instance = new Singleton;
10431 addSingleton( s_instance );
10432 }
10433 return s_instance;
10434 }
10435
10436 public:
10437 static auto get() -> InterfaceT const& {
10438 return *getInternal();
10439 }
10440 static auto getMutable() -> MutableInterfaceT& {
10441 return *getInternal();
10442 }
10443 };
10444
10445} // namespace Catch
10446
10447// end catch_singletons.hpp
10448namespace Catch {
10449
10450 namespace {
10451
10452 class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
10453 private NonCopyable {
10454
10455 public: // IRegistryHub
10456 RegistryHub() = default;
10457 IReporterRegistry const& getReporterRegistry() const override {
10458 return m_reporterRegistry;
10459 }
10460 ITestCaseRegistry const& getTestCaseRegistry() const override {
10461 return m_testCaseRegistry;
10462 }
10463 IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
10464 return m_exceptionTranslatorRegistry;
10465 }
10466 ITagAliasRegistry const& getTagAliasRegistry() const override {
10467 return m_tagAliasRegistry;
10468 }
10469 StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
10470 return m_exceptionRegistry;
10471 }
10472
10473 public: // IMutableRegistryHub
10474 void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
10475 m_reporterRegistry.registerReporter( name, factory );
10476 }
10477 void registerListener( IReporterFactoryPtr const& factory ) override {
10478 m_reporterRegistry.registerListener( factory );
10479 }
10480 void registerTest( TestCase const& testInfo ) override {
10481 m_testCaseRegistry.registerTest( testInfo );
10482 }
10483 void registerTranslator( const IExceptionTranslator* translator ) override {
10484 m_exceptionTranslatorRegistry.registerTranslator( translator );
10485 }
10486 void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
10487 m_tagAliasRegistry.add( alias, tag, lineInfo );
10488 }
10489 void registerStartupException() noexcept override {
10490 m_exceptionRegistry.add(std::current_exception());
10491 }
10492 IMutableEnumValuesRegistry& getMutableEnumValuesRegistry() override {
10493 return m_enumValuesRegistry;
10494 }
10495
10496 private:
10497 TestRegistry m_testCaseRegistry;
10498 ReporterRegistry m_reporterRegistry;
10499 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
10500 TagAliasRegistry m_tagAliasRegistry;
10501 StartupExceptionRegistry m_exceptionRegistry;
10502 Detail::EnumValuesRegistry m_enumValuesRegistry;
10503 };
10504 }
10505
10506 using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
10507
10508 IRegistryHub const& getRegistryHub() {
10509 return RegistryHubSingleton::get();
10510 }
10511 IMutableRegistryHub& getMutableRegistryHub() {
10512 return RegistryHubSingleton::getMutable();
10513 }
10514 void cleanUp() {
10515 cleanupSingletons();
10517 }
10520 }
10521
10522} // end namespace Catch
10523// end catch_registry_hub.cpp
10524// start catch_reporter_registry.cpp
10525
10526namespace Catch {
10527
10528 ReporterRegistry::~ReporterRegistry() = default;
10529
10530 IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
10531 auto it = m_factories.find( name );
10532 if( it == m_factories.end() )
10533 return nullptr;
10534 return it->second->create( ReporterConfig( config ) );
10535 }
10536
10537 void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
10538 m_factories.emplace(name, factory);
10539 }
10540 void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
10541 m_listeners.push_back( factory );
10542 }
10543
10544 IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
10545 return m_factories;
10546 }
10547 IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
10548 return m_listeners;
10549 }
10550
10551}
10552// end catch_reporter_registry.cpp
10553// start catch_result_type.cpp
10554
10555namespace Catch {
10556
10557 bool isOk( ResultWas::OfType resultType ) {
10558 return ( resultType & ResultWas::FailureBit ) == 0;
10559 }
10560 bool isJustInfo( int flags ) {
10561 return flags == ResultWas::Info;
10562 }
10563
10564 ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
10565 return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
10566 }
10567
10568 bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
10569 bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
10570
10571} // end namespace Catch
10572// end catch_result_type.cpp
10573// start catch_run_context.cpp
10574
10575#include <cassert>
10576#include <algorithm>
10577#include <sstream>
10578
10579namespace Catch {
10580
10581 namespace Generators {
10582 struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
10583 GeneratorBasePtr m_generator;
10584
10585 GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
10586 : TrackerBase( nameAndLocation, ctx, parent )
10587 {}
10588 ~GeneratorTracker();
10589
10590 static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
10592
10593 ITracker& currentTracker = ctx.currentTracker();
10594 if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
10595 assert( childTracker );
10596 assert( childTracker->isGeneratorTracker() );
10597 tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
10598 }
10599 else {
10600 tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
10601 currentTracker.addChild( tracker );
10602 }
10603
10604 if( !ctx.completedCycle() && !tracker->isComplete() ) {
10605 tracker->open();
10606 }
10607
10608 return *tracker;
10609 }
10610
10611 // TrackerBase interface
10612 bool isGeneratorTracker() const override { return true; }
10613 auto hasGenerator() const -> bool override {
10614 return !!m_generator;
10615 }
10616 void close() override {
10617 TrackerBase::close();
10618 // Generator interface only finds out if it has another item on atual move
10619 if (m_runState == CompletedSuccessfully && m_generator->next()) {
10620 m_children.clear();
10621 m_runState = Executing;
10622 }
10623 }
10624
10625 // IGeneratorTracker interface
10626 auto getGenerator() const -> GeneratorBasePtr const& override {
10627 return m_generator;
10628 }
10629 void setGenerator( GeneratorBasePtr&& generator ) override {
10630 m_generator = std::move( generator );
10631 }
10632 };
10633 GeneratorTracker::~GeneratorTracker() {}
10634 }
10635
10636 RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
10637 : m_runInfo(_config->name()),
10638 m_context(getCurrentMutableContext()),
10639 m_config(_config),
10640 m_reporter(std::move(reporter)),
10641 m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
10642 m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
10643 {
10644 m_context.setRunner(this);
10645 m_context.setConfig(m_config);
10646 m_context.setResultCapture(this);
10647 m_reporter->testRunStarting(m_runInfo);
10648 }
10649
10650 RunContext::~RunContext() {
10651 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
10652 }
10653
10654 void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
10655 m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
10656 }
10657
10658 void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
10659 m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
10660 }
10661
10662 Totals RunContext::runTest(TestCase const& testCase) {
10663 Totals prevTotals = m_totals;
10664
10665 std::string redirectedCout;
10666 std::string redirectedCerr;
10667
10668 auto const& testInfo = testCase.getTestCaseInfo();
10669
10670 m_reporter->testCaseStarting(testInfo);
10671
10672 m_activeTestCase = &testCase;
10673
10674 ITracker& rootTracker = m_trackerContext.startRun();
10675 assert(rootTracker.isSectionTracker());
10676 static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
10677 do {
10678 m_trackerContext.startCycle();
10679 m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
10680 runCurrentTest(redirectedCout, redirectedCerr);
10681 } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
10682
10683 Totals deltaTotals = m_totals.delta(prevTotals);
10684 if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
10685 deltaTotals.assertions.failed++;
10686 deltaTotals.testCases.passed--;
10687 deltaTotals.testCases.failed++;
10688 }
10689 m_totals.testCases += deltaTotals.testCases;
10690 m_reporter->testCaseEnded(TestCaseStats(testInfo,
10691 deltaTotals,
10692 redirectedCout,
10693 redirectedCerr,
10694 aborting()));
10695
10696 m_activeTestCase = nullptr;
10697 m_testCaseTracker = nullptr;
10698
10699 return deltaTotals;
10700 }
10701
10702 IConfigPtr RunContext::config() const {
10703 return m_config;
10704 }
10705
10706 IStreamingReporter& RunContext::reporter() const {
10707 return *m_reporter;
10708 }
10709
10710 void RunContext::assertionEnded(AssertionResult const & result) {
10711 if (result.getResultType() == ResultWas::Ok) {
10712 m_totals.assertions.passed++;
10713 m_lastAssertionPassed = true;
10714 } else if (!result.isOk()) {
10715 m_lastAssertionPassed = false;
10716 if( m_activeTestCase->getTestCaseInfo().okToFail() )
10717 m_totals.assertions.failedButOk++;
10718 else
10719 m_totals.assertions.failed++;
10720 }
10721 else {
10722 m_lastAssertionPassed = true;
10723 }
10724
10725 // We have no use for the return value (whether messages should be cleared), because messages were made scoped
10726 // and should be let to clear themselves out.
10727 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
10728
10729 if (result.getResultType() != ResultWas::Warning)
10730 m_messageScopes.clear();
10731
10732 // Reset working state
10733 resetAssertionInfo();
10734 m_lastResult = result;
10735 }
10736 void RunContext::resetAssertionInfo() {
10737 m_lastAssertionInfo.macroName = StringRef();
10738 m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
10739 }
10740
10741 bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
10742 ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
10743 if (!sectionTracker.isOpen())
10744 return false;
10745 m_activeSections.push_back(&sectionTracker);
10746
10747 m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
10748
10749 m_reporter->sectionStarting(sectionInfo);
10750
10751 assertions = m_totals.assertions;
10752
10753 return true;
10754 }
10755 auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
10756 using namespace Generators;
10757 GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) );
10758 assert( tracker.isOpen() );
10759 m_lastAssertionInfo.lineInfo = lineInfo;
10760 return tracker;
10761 }
10762
10763 bool RunContext::testForMissingAssertions(Counts& assertions) {
10764 if (assertions.total() != 0)
10765 return false;
10766 if (!m_config->warnAboutMissingAssertions())
10767 return false;
10768 if (m_trackerContext.currentTracker().hasChildren())
10769 return false;
10770 m_totals.assertions.failed++;
10771 assertions.failed++;
10772 return true;
10773 }
10774
10775 void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
10776 Counts assertions = m_totals.assertions - endInfo.prevAssertions;
10777 bool missingAssertions = testForMissingAssertions(assertions);
10778
10779 if (!m_activeSections.empty()) {
10780 m_activeSections.back()->close();
10781 m_activeSections.pop_back();
10782 }
10783
10784 m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
10785 m_messages.clear();
10786 m_messageScopes.clear();
10787 }
10788
10789 void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
10790 if (m_unfinishedSections.empty())
10791 m_activeSections.back()->fail();
10792 else
10793 m_activeSections.back()->close();
10794 m_activeSections.pop_back();
10795
10796 m_unfinishedSections.push_back(endInfo);
10797 }
10798 void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
10799 m_reporter->benchmarkStarting( info );
10800 }
10801 void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
10802 m_reporter->benchmarkEnded( stats );
10803 }
10804
10805 void RunContext::pushScopedMessage(MessageInfo const & message) {
10806 m_messages.push_back(message);
10807 }
10808
10809 void RunContext::popScopedMessage(MessageInfo const & message) {
10810 m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
10811 }
10812
10813 void RunContext::emplaceUnscopedMessage( MessageBuilder const& builder ) {
10814 m_messageScopes.emplace_back( builder );
10815 }
10816
10817 std::string RunContext::getCurrentTestName() const {
10818 return m_activeTestCase
10819 ? m_activeTestCase->getTestCaseInfo().name
10820 : std::string();
10821 }
10822
10823 const AssertionResult * RunContext::getLastResult() const {
10824 return &(*m_lastResult);
10825 }
10826
10827 void RunContext::exceptionEarlyReported() {
10828 m_shouldReportUnexpected = false;
10829 }
10830
10831 void RunContext::handleFatalErrorCondition( StringRef message ) {
10832 // First notify reporter that bad things happened
10833 m_reporter->fatalErrorEncountered(message);
10834
10835 // Don't rebuild the result -- the stringification itself can cause more fatal errors
10836 // Instead, fake a result data.
10837 AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
10838 tempResult.message = message;
10839 AssertionResult result(m_lastAssertionInfo, tempResult);
10840
10841 assertionEnded(result);
10842
10843 handleUnfinishedSections();
10844
10845 // Recreate section for test case (as we will lose the one that was in scope)
10846 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
10847 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
10848
10849 Counts assertions;
10850 assertions.failed = 1;
10851 SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
10852 m_reporter->sectionEnded(testCaseSectionStats);
10853
10854 auto const& testInfo = m_activeTestCase->getTestCaseInfo();
10855
10856 Totals deltaTotals;
10857 deltaTotals.testCases.failed = 1;
10858 deltaTotals.assertions.failed = 1;
10859 m_reporter->testCaseEnded(TestCaseStats(testInfo,
10860 deltaTotals,
10861 std::string(),
10862 std::string(),
10863 false));
10864 m_totals.testCases.failed++;
10865 testGroupEnded(std::string(), m_totals, 1, 1);
10866 m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
10867 }
10868
10869 bool RunContext::lastAssertionPassed() {
10870 return m_lastAssertionPassed;
10871 }
10872
10873 void RunContext::assertionPassed() {
10874 m_lastAssertionPassed = true;
10875 ++m_totals.assertions.passed;
10876 resetAssertionInfo();
10877 m_messageScopes.clear();
10878 }
10879
10880 bool RunContext::aborting() const {
10881 return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
10882 }
10883
10884 void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
10885 auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
10886 SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
10887 m_reporter->sectionStarting(testCaseSection);
10888 Counts prevAssertions = m_totals.assertions;
10889 double duration = 0;
10890 m_shouldReportUnexpected = true;
10891 m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
10892
10893 seedRng(*m_config);
10894
10895 Timer timer;
10896 CATCH_TRY {
10897 if (m_reporter->getPreferences().shouldRedirectStdOut) {
10898#if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
10899 RedirectedStreams redirectedStreams(redirectedCout, redirectedCerr);
10900
10901 timer.start();
10902 invokeActiveTestCase();
10903#else
10904 OutputRedirect r(redirectedCout, redirectedCerr);
10905 timer.start();
10906 invokeActiveTestCase();
10907#endif
10908 } else {
10909 timer.start();
10910 invokeActiveTestCase();
10911 }
10912 duration = timer.getElapsedSeconds();
10913 } CATCH_CATCH_ANON (TestFailureException&) {
10914 // This just means the test was aborted due to failure
10915 } CATCH_CATCH_ALL {
10916 // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
10917 // are reported without translation at the point of origin.
10918 if( m_shouldReportUnexpected ) {
10919 AssertionReaction dummyReaction;
10920 handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
10921 }
10922 }
10923 Counts assertions = m_totals.assertions - prevAssertions;
10924 bool missingAssertions = testForMissingAssertions(assertions);
10925
10926 m_testCaseTracker->close();
10927 handleUnfinishedSections();
10928 m_messages.clear();
10929 m_messageScopes.clear();
10930
10931 SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
10932 m_reporter->sectionEnded(testCaseSectionStats);
10933 }
10934
10935 void RunContext::invokeActiveTestCase() {
10936 FatalConditionHandler fatalConditionHandler; // Handle signals
10937 m_activeTestCase->invoke();
10938 fatalConditionHandler.reset();
10939 }
10940
10941 void RunContext::handleUnfinishedSections() {
10942 // If sections ended prematurely due to an exception we stored their
10943 // infos here so we can tear them down outside the unwind process.
10944 for (auto it = m_unfinishedSections.rbegin(),
10945 itEnd = m_unfinishedSections.rend();
10946 it != itEnd;
10947 ++it)
10948 sectionEnded(*it);
10949 m_unfinishedSections.clear();
10950 }
10951
10952 void RunContext::handleExpr(
10953 AssertionInfo const& info,
10954 ITransientExpression const& expr,
10955 AssertionReaction& reaction
10956 ) {
10957 m_reporter->assertionStarting( info );
10958
10959 bool negated = isFalseTest( info.resultDisposition );
10960 bool result = expr.getResult() != negated;
10961
10962 if( result ) {
10963 if (!m_includeSuccessfulResults) {
10964 assertionPassed();
10965 }
10966 else {
10967 reportExpr(info, ResultWas::Ok, &expr, negated);
10968 }
10969 }
10970 else {
10971 reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
10972 populateReaction( reaction );
10973 }
10974 }
10975 void RunContext::reportExpr(
10976 AssertionInfo const &info,
10977 ResultWas::OfType resultType,
10978 ITransientExpression const *expr,
10979 bool negated ) {
10980
10981 m_lastAssertionInfo = info;
10982 AssertionResultData data( resultType, LazyExpression( negated ) );
10983
10984 AssertionResult assertionResult{ info, data };
10985 assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
10986
10987 assertionEnded( assertionResult );
10988 }
10989
10990 void RunContext::handleMessage(
10991 AssertionInfo const& info,
10992 ResultWas::OfType resultType,
10993 StringRef const& message,
10994 AssertionReaction& reaction
10995 ) {
10996 m_reporter->assertionStarting( info );
10997
10998 m_lastAssertionInfo = info;
10999
11000 AssertionResultData data( resultType, LazyExpression( false ) );
11001 data.message = message;
11002 AssertionResult assertionResult{ m_lastAssertionInfo, data };
11003 assertionEnded( assertionResult );
11004 if( !assertionResult.isOk() )
11005 populateReaction( reaction );
11006 }
11007 void RunContext::handleUnexpectedExceptionNotThrown(
11008 AssertionInfo const& info,
11009 AssertionReaction& reaction
11010 ) {
11011 handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
11012 }
11013
11014 void RunContext::handleUnexpectedInflightException(
11015 AssertionInfo const& info,
11016 std::string const& message,
11017 AssertionReaction& reaction
11018 ) {
11019 m_lastAssertionInfo = info;
11020
11021 AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
11022 data.message = message;
11023 AssertionResult assertionResult{ info, data };
11024 assertionEnded( assertionResult );
11025 populateReaction( reaction );
11026 }
11027
11028 void RunContext::populateReaction( AssertionReaction& reaction ) {
11029 reaction.shouldDebugBreak = m_config->shouldDebugBreak();
11030 reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
11031 }
11032
11033 void RunContext::handleIncomplete(
11034 AssertionInfo const& info
11035 ) {
11036 m_lastAssertionInfo = info;
11037
11038 AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
11039 data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
11040 AssertionResult assertionResult{ info, data };
11041 assertionEnded( assertionResult );
11042 }
11043 void RunContext::handleNonExpr(
11044 AssertionInfo const &info,
11045 ResultWas::OfType resultType,
11046 AssertionReaction &reaction
11047 ) {
11048 m_lastAssertionInfo = info;
11049
11050 AssertionResultData data( resultType, LazyExpression( false ) );
11051 AssertionResult assertionResult{ info, data };
11052 assertionEnded( assertionResult );
11053
11054 if( !assertionResult.isOk() )
11055 populateReaction( reaction );
11056 }
11057
11058 IResultCapture& getResultCapture() {
11059 if (auto* capture = getCurrentContext().getResultCapture())
11060 return *capture;
11061 else
11062 CATCH_INTERNAL_ERROR("No result capture instance");
11063 }
11064}
11065// end catch_run_context.cpp
11066// start catch_section.cpp
11067
11068namespace Catch {
11069
11070 Section::Section( SectionInfo const& info )
11071 : m_info( info ),
11072 m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
11073 {
11074 m_timer.start();
11075 }
11076
11078 if( m_sectionIncluded ) {
11079 SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
11080 if( uncaught_exceptions() )
11082 else
11083 getResultCapture().sectionEnded( endInfo );
11084 }
11085 }
11086
11087 // This indicates whether the section should be executed or not
11088 Section::operator bool() const {
11089 return m_sectionIncluded;
11090 }
11091
11092} // end namespace Catch
11093// end catch_section.cpp
11094// start catch_section_info.cpp
11095
11096namespace Catch {
11097
11099 ( SourceLineInfo const& _lineInfo,
11100 std::string const& _name )
11101 : name( _name ),
11102 lineInfo( _lineInfo )
11103 {}
11104
11105} // end namespace Catch
11106// end catch_section_info.cpp
11107// start catch_session.cpp
11108
11109// start catch_session.h
11110
11111#include <memory>
11112
11113namespace Catch {
11114
11115 class Session : NonCopyable {
11116 public:
11117
11118 Session();
11119 ~Session() override;
11120
11121 void showHelp() const;
11122 void libIdentify();
11123
11124 int applyCommandLine( int argc, char const * const * argv );
11125 #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
11126 int applyCommandLine( int argc, wchar_t const * const * argv );
11127 #endif
11128
11129 void useConfigData( ConfigData const& configData );
11130
11131 template<typename CharT>
11132 int run(int argc, CharT const * const argv[]) {
11133 if (m_startupExceptions)
11134 return 1;
11135 int returnCode = applyCommandLine(argc, argv);
11136 if (returnCode == 0)
11137 returnCode = run();
11138 return returnCode;
11139 }
11140
11141 int run();
11142
11143 clara::Parser const& cli() const;
11144 void cli( clara::Parser const& newParser );
11145 ConfigData& configData();
11146 Config& config();
11147 private:
11148 int runInternal();
11149
11150 clara::Parser m_cli;
11151 ConfigData m_configData;
11152 std::shared_ptr<Config> m_config;
11153 bool m_startupExceptions = false;
11154 };
11155
11156} // end namespace Catch
11157
11158// end catch_session.h
11159// start catch_version.h
11160
11161#include <iosfwd>
11162
11163namespace Catch {
11164
11165 // Versioning information
11166 struct Version {
11167 Version( Version const& ) = delete;
11168 Version& operator=( Version const& ) = delete;
11169 Version( unsigned int _majorVersion,
11170 unsigned int _minorVersion,
11171 unsigned int _patchNumber,
11172 char const * const _branchName,
11173 unsigned int _buildNumber );
11174
11175 unsigned int const majorVersion;
11176 unsigned int const minorVersion;
11177 unsigned int const patchNumber;
11178
11179 // buildNumber is only used if branchName is not null
11180 char const * const branchName;
11181 unsigned int const buildNumber;
11182
11183 friend std::ostream& operator << ( std::ostream& os, Version const& version );
11184 };
11185
11186 Version const& libraryVersion();
11187}
11188
11189// end catch_version.h
11190#include <cstdlib>
11191#include <iomanip>
11192
11193namespace Catch {
11194
11195 namespace {
11196 const int MaxExitCode = 255;
11197
11198 IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
11199 auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
11200 CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
11201
11202 return reporter;
11203 }
11204
11205 IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
11206 if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
11207 return createReporter(config->getReporterName(), config);
11208 }
11209
11210 // On older platforms, returning std::unique_ptr<ListeningReporter>
11211 // when the return type is std::unique_ptr<IStreamingReporter>
11212 // doesn't compile without a std::move call. However, this causes
11213 // a warning on newer platforms. Thus, we have to work around
11214 // it a bit and downcast the pointer manually.
11215 auto ret = std::unique_ptr<IStreamingReporter>(new ListeningReporter);
11216 auto& multi = static_cast<ListeningReporter&>(*ret);
11217 auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
11218 for (auto const& listener : listeners) {
11219 multi.addListener(listener->create(Catch::ReporterConfig(config)));
11220 }
11221 multi.addReporter(createReporter(config->getReporterName(), config));
11222 return ret;
11223 }
11224
11225 Catch::Totals runTests(std::shared_ptr<Config> const& config) {
11226 auto reporter = makeReporter(config);
11227
11228 RunContext context(config, std::move(reporter));
11229
11230 Totals totals;
11231
11232 context.testGroupStarting(config->name(), 1, 1);
11233
11234 TestSpec testSpec = config->testSpec();
11235
11236 auto const& allTestCases = getAllTestCasesSorted(*config);
11237 for (auto const& testCase : allTestCases) {
11238 bool matching = (!testSpec.hasFilters() && !testCase.isHidden()) ||
11239 (testSpec.hasFilters() && matchTest(testCase, testSpec, *config));
11240
11241 if (!context.aborting() && matching)
11242 totals += context.runTest(testCase);
11243 else
11244 context.reporter().skipTest(testCase);
11245 }
11246
11247 if (config->warnAboutNoTests() && totals.testCases.total() == 0) {
11248 ReusableStringStream testConfig;
11249
11250 bool first = true;
11251 for (const auto& input : config->getTestsOrTags()) {
11252 if (!first) { testConfig << ' '; }
11253 first = false;
11254 testConfig << input;
11255 }
11256
11257 context.reporter().noMatchingTestCases(testConfig.str());
11258 totals.error = -1;
11259 }
11260
11261 context.testGroupEnded(config->name(), totals, 1, 1);
11262 return totals;
11263 }
11264
11265 void applyFilenamesAsTags(Catch::IConfig const& config) {
11266 auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
11267 for (auto& testCase : tests) {
11268 auto tags = testCase.tags;
11269
11270 std::string filename = testCase.lineInfo.file;
11271 auto lastSlash = filename.find_last_of("\\/");
11272 if (lastSlash != std::string::npos) {
11273 filename.erase(0, lastSlash);
11274 filename[0] = '#';
11275 }
11276
11277 auto lastDot = filename.find_last_of('.');
11278 if (lastDot != std::string::npos) {
11279 filename.erase(lastDot);
11280 }
11281
11282 tags.push_back(std::move(filename));
11283 setTags(testCase, tags);
11284 }
11285 }
11286
11287 } // anon namespace
11288
11289 Session::Session() {
11290 static bool alreadyInstantiated = false;
11291 if( alreadyInstantiated ) {
11292 CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
11294 }
11295
11296 // There cannot be exceptions at startup in no-exception mode.
11297#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
11298 const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
11299 if ( !exceptions.empty() ) {
11300 config();
11302
11303 m_startupExceptions = true;
11304 Colour colourGuard( Colour::Red );
11305 Catch::cerr() << "Errors occurred during startup!" << '\n';
11306 // iterate over all exceptions and notify user
11307 for ( const auto& ex_ptr : exceptions ) {
11308 try {
11309 std::rethrow_exception(ex_ptr);
11310 } catch ( std::exception const& ex ) {
11311 Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
11312 }
11313 }
11314 }
11315#endif
11316
11317 alreadyInstantiated = true;
11318 m_cli = makeCommandLineParser( m_configData );
11319 }
11320 Session::~Session() {
11322 }
11323
11324 void Session::showHelp() const {
11325 Catch::cout()
11326 << "\nCatch v" << libraryVersion() << "\n"
11327 << m_cli << std::endl
11328 << "For more detailed usage please see the project docs\n" << std::endl;
11329 }
11330 void Session::libIdentify() {
11331 Catch::cout()
11332 << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
11333 << std::left << std::setw(16) << "category: " << "testframework\n"
11334 << std::left << std::setw(16) << "framework: " << "Catch Test\n"
11335 << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
11336 }
11337
11338 int Session::applyCommandLine( int argc, char const * const * argv ) {
11339 if( m_startupExceptions )
11340 return 1;
11341
11342 auto result = m_cli.parse( clara::Args( argc, argv ) );
11343 if( !result ) {
11344 config();
11346 Catch::cerr()
11347 << Colour( Colour::Red )
11348 << "\nError(s) in input:\n"
11349 << Column( result.errorMessage() ).indent( 2 )
11350 << "\n\n";
11351 Catch::cerr() << "Run with -? for usage\n" << std::endl;
11352 return MaxExitCode;
11353 }
11354
11355 if( m_configData.showHelp )
11356 showHelp();
11357 if( m_configData.libIdentify )
11358 libIdentify();
11359 m_config.reset();
11360 return 0;
11361 }
11362
11363#if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
11364 int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
11365
11366 char **utf8Argv = new char *[ argc ];
11367
11368 for ( int i = 0; i < argc; ++i ) {
11369 int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
11370
11371 utf8Argv[ i ] = new char[ bufSize ];
11372
11373 WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
11374 }
11375
11376 int returnCode = applyCommandLine( argc, utf8Argv );
11377
11378 for ( int i = 0; i < argc; ++i )
11379 delete [] utf8Argv[ i ];
11380
11381 delete [] utf8Argv;
11382
11383 return returnCode;
11384 }
11385#endif
11386
11387 void Session::useConfigData( ConfigData const& configData ) {
11388 m_configData = configData;
11389 m_config.reset();
11390 }
11391
11392 int Session::run() {
11393 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
11394 Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
11395 static_cast<void>(std::getchar());
11396 }
11397 int exitCode = runInternal();
11398 if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
11399 Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
11400 static_cast<void>(std::getchar());
11401 }
11402 return exitCode;
11403 }
11404
11405 clara::Parser const& Session::cli() const {
11406 return m_cli;
11407 }
11408 void Session::cli( clara::Parser const& newParser ) {
11409 m_cli = newParser;
11410 }
11411 ConfigData& Session::configData() {
11412 return m_configData;
11413 }
11414 Config& Session::config() {
11415 if( !m_config )
11416 m_config = std::make_shared<Config>( m_configData );
11417 return *m_config;
11418 }
11419
11420 int Session::runInternal() {
11421 if( m_startupExceptions )
11422 return 1;
11423
11424 if (m_configData.showHelp || m_configData.libIdentify) {
11425 return 0;
11426 }
11427
11428 CATCH_TRY {
11429 config(); // Force config to be constructed
11430
11431 seedRng( *m_config );
11432
11433 if( m_configData.filenamesAsTags )
11434 applyFilenamesAsTags( *m_config );
11435
11436 // Handle list request
11437 if( Option<std::size_t> listed = list( m_config ) )
11438 return static_cast<int>( *listed );
11439
11440 auto totals = runTests( m_config );
11441 // Note that on unices only the lower 8 bits are usually used, clamping
11442 // the return value to 255 prevents false negative when some multiple
11443 // of 256 tests has failed
11444 return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
11445 }
11446#if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
11447 catch( std::exception& ex ) {
11448 Catch::cerr() << ex.what() << std::endl;
11449 return MaxExitCode;
11450 }
11451#endif
11452 }
11453
11454} // end namespace Catch
11455// end catch_session.cpp
11456// start catch_singletons.cpp
11457
11458#include <vector>
11459
11460namespace Catch {
11461
11462 namespace {
11463 static auto getSingletons() -> std::vector<ISingleton*>*& {
11464 static std::vector<ISingleton*>* g_singletons = nullptr;
11465 if( !g_singletons )
11466 g_singletons = new std::vector<ISingleton*>();
11467 return g_singletons;
11468 }
11469 }
11470
11471 ISingleton::~ISingleton() {}
11472
11473 void addSingleton(ISingleton* singleton ) {
11474 getSingletons()->push_back( singleton );
11475 }
11476 void cleanupSingletons() {
11477 auto& singletons = getSingletons();
11478 for( auto singleton : *singletons )
11479 delete singleton;
11480 delete singletons;
11481 singletons = nullptr;
11482 }
11483
11484} // namespace Catch
11485// end catch_singletons.cpp
11486// start catch_startup_exception_registry.cpp
11487
11488namespace Catch {
11489void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
11490 CATCH_TRY {
11491 m_exceptions.push_back(exception);
11492 } CATCH_CATCH_ALL {
11493 // If we run out of memory during start-up there's really not a lot more we can do about it
11495 }
11496 }
11497
11498 std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
11499 return m_exceptions;
11500 }
11501
11502} // end namespace Catch
11503// end catch_startup_exception_registry.cpp
11504// start catch_stream.cpp
11505
11506#include <cstdio>
11507#include <iostream>
11508#include <fstream>
11509#include <sstream>
11510#include <vector>
11511#include <memory>
11512
11513namespace Catch {
11514
11515 Catch::IStream::~IStream() = default;
11516
11517 namespace detail { namespace {
11518 template<typename WriterF, std::size_t bufferSize=256>
11519 class StreamBufImpl : public std::streambuf {
11520 char data[bufferSize];
11521 WriterF m_writer;
11522
11523 public:
11524 StreamBufImpl() {
11525 setp( data, data + sizeof(data) );
11526 }
11527
11528 ~StreamBufImpl() noexcept {
11529 StreamBufImpl::sync();
11530 }
11531
11532 private:
11533 int overflow( int c ) override {
11534 sync();
11535
11536 if( c != EOF ) {
11537 if( pbase() == epptr() )
11538 m_writer( std::string( 1, static_cast<char>( c ) ) );
11539 else
11540 sputc( static_cast<char>( c ) );
11541 }
11542 return 0;
11543 }
11544
11545 int sync() override {
11546 if( pbase() != pptr() ) {
11547 m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
11548 setp( pbase(), epptr() );
11549 }
11550 return 0;
11551 }
11552 };
11553
11554 ///////////////////////////////////////////////////////////////////////////
11555
11556 struct OutputDebugWriter {
11557
11558 void operator()( std::string const&str ) {
11559 writeToDebugConsole( str );
11560 }
11561 };
11562
11563 ///////////////////////////////////////////////////////////////////////////
11564
11565 class FileStream : public IStream {
11566 mutable std::ofstream m_ofs;
11567 public:
11568 FileStream( StringRef filename ) {
11569 m_ofs.open( filename.c_str() );
11570 CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
11571 }
11572 ~FileStream() override = default;
11573 public: // IStream
11574 std::ostream& stream() const override {
11575 return m_ofs;
11576 }
11577 };
11578
11579 ///////////////////////////////////////////////////////////////////////////
11580
11581 class CoutStream : public IStream {
11582 mutable std::ostream m_os;
11583 public:
11584 // Store the streambuf from cout up-front because
11585 // cout may get redirected when running tests
11586 CoutStream() : m_os( Catch::cout().rdbuf() ) {}
11587 ~CoutStream() override = default;
11588
11589 public: // IStream
11590 std::ostream& stream() const override { return m_os; }
11591 };
11592
11593 ///////////////////////////////////////////////////////////////////////////
11594
11595 class DebugOutStream : public IStream {
11597 mutable std::ostream m_os;
11598 public:
11599 DebugOutStream()
11600 : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
11601 m_os( m_streamBuf.get() )
11602 {}
11603
11604 ~DebugOutStream() override = default;
11605
11606 public: // IStream
11607 std::ostream& stream() const override { return m_os; }
11608 };
11609
11610 }} // namespace anon::detail
11611
11612 ///////////////////////////////////////////////////////////////////////////
11613
11614 auto makeStream( StringRef const &filename ) -> IStream const* {
11615 if( filename.empty() )
11616 return new detail::CoutStream();
11617 else if( filename[0] == '%' ) {
11618 if( filename == "%debug" )
11619 return new detail::DebugOutStream();
11620 else
11621 CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
11622 }
11623 else
11624 return new detail::FileStream( filename );
11625 }
11626
11627 // This class encapsulates the idea of a pool of ostringstreams that can be reused.
11628 struct StringStreams {
11630 std::vector<std::size_t> m_unused;
11631 std::ostringstream m_referenceStream; // Used for copy state/ flags from
11632
11633 auto add() -> std::size_t {
11634 if( m_unused.empty() ) {
11636 return m_streams.size()-1;
11637 }
11638 else {
11639 auto index = m_unused.back();
11640 m_unused.pop_back();
11641 return index;
11642 }
11643 }
11644
11645 void release( std::size_t index ) {
11646 m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
11647 m_unused.push_back(index);
11648 }
11649 };
11650
11652 : m_index( Singleton<StringStreams>::getMutable().add() ),
11653 m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
11654 {}
11655
11657 static_cast<std::ostringstream*>( m_oss )->str("");
11658 m_oss->clear();
11659 Singleton<StringStreams>::getMutable().release( m_index );
11660 }
11661
11662 auto ReusableStringStream::str() const -> std::string {
11663 return static_cast<std::ostringstream*>( m_oss )->str();
11664 }
11665
11666 ///////////////////////////////////////////////////////////////////////////
11667
11668#ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
11669 std::ostream& cout() { return std::cout; }
11670 std::ostream& cerr() { return std::cerr; }
11671 std::ostream& clog() { return std::clog; }
11672#endif
11673}
11674// end catch_stream.cpp
11675// start catch_string_manip.cpp
11676
11677#include <algorithm>
11678#include <ostream>
11679#include <cstring>
11680#include <cctype>
11681#include <vector>
11682
11683namespace Catch {
11684
11685 namespace {
11686 char toLowerCh(char c) {
11687 return static_cast<char>( std::tolower( c ) );
11688 }
11689 }
11690
11691 bool startsWith( std::string const& s, std::string const& prefix ) {
11692 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
11693 }
11694 bool startsWith( std::string const& s, char prefix ) {
11695 return !s.empty() && s[0] == prefix;
11696 }
11697 bool endsWith( std::string const& s, std::string const& suffix ) {
11698 return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
11699 }
11700 bool endsWith( std::string const& s, char suffix ) {
11701 return !s.empty() && s[s.size()-1] == suffix;
11702 }
11703 bool contains( std::string const& s, std::string const& infix ) {
11704 return s.find( infix ) != std::string::npos;
11705 }
11706 void toLowerInPlace( std::string& s ) {
11707 std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
11708 }
11709 std::string toLower( std::string const& s ) {
11710 std::string lc = s;
11711 toLowerInPlace( lc );
11712 return lc;
11713 }
11714 std::string trim( std::string const& str ) {
11715 static char const* whitespaceChars = "\n\r\t ";
11716 std::string::size_type start = str.find_first_not_of( whitespaceChars );
11717 std::string::size_type end = str.find_last_not_of( whitespaceChars );
11718
11719 return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
11720 }
11721
11722 bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
11723 bool replaced = false;
11724 std::size_t i = str.find( replaceThis );
11725 while( i != std::string::npos ) {
11726 replaced = true;
11727 str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
11728 if( i < str.size()-withThis.size() )
11729 i = str.find( replaceThis, i+withThis.size() );
11730 else
11731 i = std::string::npos;
11732 }
11733 return replaced;
11734 }
11735
11736 std::vector<StringRef> splitStringRef( StringRef str, char delimiter ) {
11737 std::vector<StringRef> subStrings;
11738 std::size_t start = 0;
11739 for(std::size_t pos = 0; pos < str.size(); ++pos ) {
11740 if( str[pos] == delimiter ) {
11741 if( pos - start > 1 )
11742 subStrings.push_back( str.substr( start, pos-start ) );
11743 start = pos+1;
11744 }
11745 }
11746 if( start < str.size() )
11747 subStrings.push_back( str.substr( start, str.size()-start ) );
11748 return subStrings;
11749 }
11750
11751 pluralise::pluralise( std::size_t count, std::string const& label )
11752 : m_count( count ),
11753 m_label( label )
11754 {}
11755
11756 std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
11757 os << pluraliser.m_count << ' ' << pluraliser.m_label;
11758 if( pluraliser.m_count != 1 )
11759 os << 's';
11760 return os;
11761 }
11762
11763}
11764// end catch_string_manip.cpp
11765// start catch_stringref.cpp
11766
11767#if defined(__clang__)
11768# pragma clang diagnostic push
11769# pragma clang diagnostic ignored "-Wexit-time-destructors"
11770#endif
11771
11772#include <ostream>
11773#include <cstring>
11774#include <cstdint>
11775
11776namespace {
11777 const uint32_t byte_2_lead = 0xC0;
11778 const uint32_t byte_3_lead = 0xE0;
11779 const uint32_t byte_4_lead = 0xF0;
11780}
11781
11782namespace Catch {
11783 StringRef::StringRef( char const* rawChars ) noexcept
11784 : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
11785 {}
11786
11787 StringRef::operator std::string() const {
11788 return std::string( m_start, m_size );
11789 }
11790
11791 void StringRef::swap( StringRef& other ) noexcept {
11792 std::swap( m_start, other.m_start );
11793 std::swap( m_size, other.m_size );
11794 std::swap( m_data, other.m_data );
11795 }
11796
11797 auto StringRef::c_str() const -> char const* {
11798 if( !isSubstring() )
11799 return m_start;
11800
11801 const_cast<StringRef *>( this )->takeOwnership();
11802 return m_data;
11803 }
11804 auto StringRef::currentData() const noexcept -> char const* {
11805 return m_start;
11806 }
11807
11808 auto StringRef::isOwned() const noexcept -> bool {
11809 return m_data != nullptr;
11810 }
11811 auto StringRef::isSubstring() const noexcept -> bool {
11812 return m_start[m_size] != '\0';
11813 }
11814
11816 if( !isOwned() ) {
11817 m_data = new char[m_size+1];
11819 m_data[m_size] = '\0';
11820 }
11821 }
11822 auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
11823 if( start < m_size )
11824 return StringRef( m_start+start, size );
11825 else
11826 return StringRef();
11827 }
11828 auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
11829 return
11830 size() == other.size() &&
11831 (std::strncmp( m_start, other.m_start, size() ) == 0);
11832 }
11833 auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
11834 return !operator==( other );
11835 }
11836
11837 auto StringRef::operator[](size_type index) const noexcept -> char {
11838 return m_start[index];
11839 }
11840
11841 auto StringRef::numberOfCharacters() const noexcept -> size_type {
11842 size_type noChars = m_size;
11843 // Make adjustments for uft encodings
11844 for( size_type i=0; i < m_size; ++i ) {
11845 char c = m_start[i];
11846 if( ( c & byte_2_lead ) == byte_2_lead ) {
11847 noChars--;
11848 if (( c & byte_3_lead ) == byte_3_lead )
11849 noChars--;
11850 if( ( c & byte_4_lead ) == byte_4_lead )
11851 noChars--;
11852 }
11853 }
11854 return noChars;
11855 }
11856
11857 auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
11858 std::string str;
11859 str.reserve( lhs.size() + rhs.size() );
11860 str += lhs;
11861 str += rhs;
11862 return str;
11863 }
11864 auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
11865 return std::string( lhs ) + std::string( rhs );
11866 }
11867 auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
11868 return std::string( lhs ) + std::string( rhs );
11869 }
11870
11871 auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
11872 return os.write(str.currentData(), str.size());
11873 }
11874
11875 auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
11876 lhs.append(rhs.currentData(), rhs.size());
11877 return lhs;
11878 }
11879
11880} // namespace Catch
11881
11882#if defined(__clang__)
11883# pragma clang diagnostic pop
11884#endif
11885// end catch_stringref.cpp
11886// start catch_tag_alias.cpp
11887
11888namespace Catch {
11889 TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
11890}
11891// end catch_tag_alias.cpp
11892// start catch_tag_alias_autoregistrar.cpp
11893
11894namespace Catch {
11895
11896 RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
11897 CATCH_TRY {
11898 getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
11899 } CATCH_CATCH_ALL {
11900 // Do not throw when constructing global objects, instead register the exception to be processed later
11902 }
11903 }
11904
11905}
11906// end catch_tag_alias_autoregistrar.cpp
11907// start catch_tag_alias_registry.cpp
11908
11909#include <sstream>
11910
11911namespace Catch {
11912
11913 TagAliasRegistry::~TagAliasRegistry() {}
11914
11915 TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
11916 auto it = m_registry.find( alias );
11917 if( it != m_registry.end() )
11918 return &(it->second);
11919 else
11920 return nullptr;
11921 }
11922
11923 std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
11924 std::string expandedTestSpec = unexpandedTestSpec;
11925 for( auto const& registryKvp : m_registry ) {
11926 std::size_t pos = expandedTestSpec.find( registryKvp.first );
11927 if( pos != std::string::npos ) {
11928 expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
11929 registryKvp.second.tag +
11930 expandedTestSpec.substr( pos + registryKvp.first.size() );
11931 }
11932 }
11933 return expandedTestSpec;
11934 }
11935
11936 void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
11937 CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
11938 "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
11939
11940 CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
11941 "error: tag alias, '" << alias << "' already registered.\n"
11942 << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
11943 << "\tRedefined at: " << lineInfo );
11944 }
11945
11946 ITagAliasRegistry::~ITagAliasRegistry() {}
11947
11948 ITagAliasRegistry const& ITagAliasRegistry::get() {
11950 }
11951
11952} // end namespace Catch
11953// end catch_tag_alias_registry.cpp
11954// start catch_test_case_info.cpp
11955
11956#include <cctype>
11957#include <exception>
11958#include <algorithm>
11959#include <sstream>
11960
11961namespace Catch {
11962
11963 namespace {
11964 TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
11965 if( startsWith( tag, '.' ) ||
11966 tag == "!hide" )
11968 else if( tag == "!throws" )
11969 return TestCaseInfo::Throws;
11970 else if( tag == "!shouldfail" )
11972 else if( tag == "!mayfail" )
11973 return TestCaseInfo::MayFail;
11974 else if( tag == "!nonportable" )
11976 else if( tag == "!benchmark" )
11978 else
11979 return TestCaseInfo::None;
11980 }
11981 bool isReservedTag( std::string const& tag ) {
11982 return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
11983 }
11984 void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
11985 CATCH_ENFORCE( !isReservedTag(tag),
11986 "Tag name: [" << tag << "] is not allowed.\n"
11987 << "Tag names starting with non alphanumeric characters are reserved\n"
11988 << _lineInfo );
11989 }
11990 }
11991
11992 TestCase makeTestCase( ITestInvoker* _testCase,
11993 std::string const& _className,
11994 NameAndTags const& nameAndTags,
11995 SourceLineInfo const& _lineInfo )
11996 {
11997 bool isHidden = false;
11998
11999 // Parse out tags
12001 std::string desc, tag;
12002 bool inTag = false;
12003 std::string _descOrTags = nameAndTags.tags;
12004 for (char c : _descOrTags) {
12005 if( !inTag ) {
12006 if( c == '[' )
12007 inTag = true;
12008 else
12009 desc += c;
12010 }
12011 else {
12012 if( c == ']' ) {
12013 TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
12014 if( ( prop & TestCaseInfo::IsHidden ) != 0 )
12015 isHidden = true;
12016 else if( prop == TestCaseInfo::None )
12017 enforceNotReservedTag( tag, _lineInfo );
12018
12019 // Merged hide tags like `[.approvals]` should be added as
12020 // `[.][approvals]`. The `[.]` is added at later point, so
12021 // we only strip the prefix
12022 if (startsWith(tag, '.') && tag.size() > 1) {
12023 tag.erase(0, 1);
12024 }
12025 tags.push_back( tag );
12026 tag.clear();
12027 inTag = false;
12028 }
12029 else
12030 tag += c;
12031 }
12032 }
12033 if( isHidden ) {
12034 tags.push_back( "." );
12035 }
12036
12037 TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
12038 return TestCase( _testCase, std::move(info) );
12039 }
12040
12041 void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
12042 std::sort(begin(tags), end(tags));
12043 tags.erase(std::unique(begin(tags), end(tags)), end(tags));
12044 testCaseInfo.lcaseTags.clear();
12045
12046 for( auto const& tag : tags ) {
12047 std::string lcaseTag = toLower( tag );
12048 testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
12049 testCaseInfo.lcaseTags.push_back( lcaseTag );
12050 }
12051 testCaseInfo.tags = std::move(tags);
12052 }
12053
12055 std::string const& _className,
12056 std::string const& _description,
12057 std::vector<std::string> const& _tags,
12058 SourceLineInfo const& _lineInfo )
12059 : name( _name ),
12060 className( _className ),
12061 description( _description ),
12062 lineInfo( _lineInfo ),
12063 properties( None )
12064 {
12065 setTags( *this, _tags );
12066 }
12067
12068 bool TestCaseInfo::isHidden() const {
12069 return ( properties & IsHidden ) != 0;
12070 }
12071 bool TestCaseInfo::throws() const {
12072 return ( properties & Throws ) != 0;
12073 }
12074 bool TestCaseInfo::okToFail() const {
12075 return ( properties & (ShouldFail | MayFail ) ) != 0;
12076 }
12077 bool TestCaseInfo::expectedToFail() const {
12078 return ( properties & (ShouldFail ) ) != 0;
12079 }
12080
12082 std::string ret;
12083 // '[' and ']' per tag
12084 std::size_t full_size = 2 * tags.size();
12085 for (const auto& tag : tags) {
12086 full_size += tag.size();
12087 }
12088 ret.reserve(full_size);
12089 for (const auto& tag : tags) {
12090 ret.push_back('[');
12091 ret.append(tag);
12092 ret.push_back(']');
12093 }
12094
12095 return ret;
12096 }
12097
12098 TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
12099
12100 TestCase TestCase::withName( std::string const& _newName ) const {
12101 TestCase other( *this );
12102 other.name = _newName;
12103 return other;
12104 }
12105
12106 void TestCase::invoke() const {
12107 test->invoke();
12108 }
12109
12110 bool TestCase::operator == ( TestCase const& other ) const {
12111 return test.get() == other.test.get() &&
12112 name == other.name &&
12113 className == other.className;
12114 }
12115
12116 bool TestCase::operator < ( TestCase const& other ) const {
12117 return name < other.name;
12118 }
12119
12120 TestCaseInfo const& TestCase::getTestCaseInfo() const
12121 {
12122 return *this;
12123 }
12124
12125} // end namespace Catch
12126// end catch_test_case_info.cpp
12127// start catch_test_case_registry_impl.cpp
12128
12129#include <sstream>
12130
12131namespace Catch {
12132
12133 std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
12134
12135 std::vector<TestCase> sorted = unsortedTestCases;
12136
12137 switch( config.runOrder() ) {
12139 std::sort( sorted.begin(), sorted.end() );
12140 break;
12142 seedRng( config );
12143 std::shuffle( sorted.begin(), sorted.end(), rng() );
12144 break;
12146 // already in declaration order
12147 break;
12148 }
12149 return sorted;
12150 }
12151 bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
12152 return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
12153 }
12154
12155 void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
12156 std::set<TestCase> seenFunctions;
12157 for( auto const& function : functions ) {
12158 auto prev = seenFunctions.insert( function );
12159 CATCH_ENFORCE( prev.second,
12160 "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
12161 << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
12162 << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
12163 }
12164 }
12165
12166 std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
12167 std::vector<TestCase> filtered;
12168 filtered.reserve( testCases.size() );
12169 for (auto const& testCase : testCases) {
12170 if ((!testSpec.hasFilters() && !testCase.isHidden()) ||
12171 (testSpec.hasFilters() && matchTest(testCase, testSpec, config))) {
12172 filtered.push_back(testCase);
12173 }
12174 }
12175 return filtered;
12176 }
12177 std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
12179 }
12180
12181 void TestRegistry::registerTest( TestCase const& testCase ) {
12182 std::string name = testCase.getTestCaseInfo().name;
12183 if( name.empty() ) {
12184 ReusableStringStream rss;
12185 rss << "Anonymous test case " << ++m_unnamedCount;
12186 return registerTest( testCase.withName( rss.str() ) );
12187 }
12188 m_functions.push_back( testCase );
12189 }
12190
12191 std::vector<TestCase> const& TestRegistry::getAllTests() const {
12192 return m_functions;
12193 }
12194 std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
12195 if( m_sortedFunctions.empty() )
12196 enforceNoDuplicateTestCases( m_functions );
12197
12198 if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
12199 m_sortedFunctions = sortTests( config, m_functions );
12200 m_currentSortOrder = config.runOrder();
12201 }
12202 return m_sortedFunctions;
12203 }
12204
12205 ///////////////////////////////////////////////////////////////////////////
12206 TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
12207
12208 void TestInvokerAsFunction::invoke() const {
12209 m_testAsFunction();
12210 }
12211
12212 std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
12213 std::string className = classOrQualifiedMethodName;
12214 if( startsWith( className, '&' ) )
12215 {
12216 std::size_t lastColons = className.rfind( "::" );
12217 std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
12218 if( penultimateColons == std::string::npos )
12219 penultimateColons = 1;
12220 className = className.substr( penultimateColons, lastColons-penultimateColons );
12221 }
12222 return className;
12223 }
12224
12225} // end namespace Catch
12226// end catch_test_case_registry_impl.cpp
12227// start catch_test_case_tracker.cpp
12228
12229#include <algorithm>
12230#include <cassert>
12231#include <stdexcept>
12232#include <memory>
12233#include <sstream>
12234
12235#if defined(__clang__)
12236# pragma clang diagnostic push
12237# pragma clang diagnostic ignored "-Wexit-time-destructors"
12238#endif
12239
12240namespace Catch {
12241namespace TestCaseTracking {
12242
12243 NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
12244 : name( _name ),
12245 location( _location )
12246 {}
12247
12248 ITracker::~ITracker() = default;
12249
12250 ITracker& TrackerContext::startRun() {
12251 m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
12252 m_currentTracker = nullptr;
12253 m_runState = Executing;
12254 return *m_rootTracker;
12255 }
12256
12257 void TrackerContext::endRun() {
12258 m_rootTracker.reset();
12259 m_currentTracker = nullptr;
12260 m_runState = NotStarted;
12261 }
12262
12263 void TrackerContext::startCycle() {
12264 m_currentTracker = m_rootTracker.get();
12265 m_runState = Executing;
12266 }
12267 void TrackerContext::completeCycle() {
12268 m_runState = CompletedCycle;
12269 }
12270
12271 bool TrackerContext::completedCycle() const {
12272 return m_runState == CompletedCycle;
12273 }
12274 ITracker& TrackerContext::currentTracker() {
12275 return *m_currentTracker;
12276 }
12277 void TrackerContext::setCurrentTracker( ITracker* tracker ) {
12278 m_currentTracker = tracker;
12279 }
12280
12281 TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
12282 : m_nameAndLocation( nameAndLocation ),
12283 m_ctx( ctx ),
12284 m_parent( parent )
12285 {}
12286
12287 NameAndLocation const& TrackerBase::nameAndLocation() const {
12288 return m_nameAndLocation;
12289 }
12290 bool TrackerBase::isComplete() const {
12291 return m_runState == CompletedSuccessfully || m_runState == Failed;
12292 }
12293 bool TrackerBase::isSuccessfullyCompleted() const {
12294 return m_runState == CompletedSuccessfully;
12295 }
12296 bool TrackerBase::isOpen() const {
12297 return m_runState != NotStarted && !isComplete();
12298 }
12299 bool TrackerBase::hasChildren() const {
12300 return !m_children.empty();
12301 }
12302
12303 void TrackerBase::addChild( ITrackerPtr const& child ) {
12304 m_children.push_back( child );
12305 }
12306
12307 ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
12308 auto it = std::find_if( m_children.begin(), m_children.end(),
12309 [&nameAndLocation]( ITrackerPtr const& tracker ){
12310 return
12311 tracker->nameAndLocation().location == nameAndLocation.location &&
12312 tracker->nameAndLocation().name == nameAndLocation.name;
12313 } );
12314 return( it != m_children.end() )
12315 ? *it
12316 : nullptr;
12317 }
12318 ITracker& TrackerBase::parent() {
12319 assert( m_parent ); // Should always be non-null except for root
12320 return *m_parent;
12321 }
12322
12323 void TrackerBase::openChild() {
12324 if( m_runState != ExecutingChildren ) {
12325 m_runState = ExecutingChildren;
12326 if( m_parent )
12327 m_parent->openChild();
12328 }
12329 }
12330
12331 bool TrackerBase::isSectionTracker() const { return false; }
12332 bool TrackerBase::isGeneratorTracker() const { return false; }
12333
12334 void TrackerBase::open() {
12335 m_runState = Executing;
12336 moveToThis();
12337 if( m_parent )
12338 m_parent->openChild();
12339 }
12340
12341 void TrackerBase::close() {
12342
12343 // Close any still open children (e.g. generators)
12344 while( &m_ctx.currentTracker() != this )
12345 m_ctx.currentTracker().close();
12346
12347 switch( m_runState ) {
12348 case NeedsAnotherRun:
12349 break;
12350
12351 case Executing:
12352 m_runState = CompletedSuccessfully;
12353 break;
12354 case ExecutingChildren:
12355 if( m_children.empty() || m_children.back()->isComplete() )
12356 m_runState = CompletedSuccessfully;
12357 break;
12358
12359 case NotStarted:
12360 case CompletedSuccessfully:
12361 case Failed:
12362 CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
12363
12364 default:
12365 CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
12366 }
12367 moveToParent();
12368 m_ctx.completeCycle();
12369 }
12370 void TrackerBase::fail() {
12371 m_runState = Failed;
12372 if( m_parent )
12373 m_parent->markAsNeedingAnotherRun();
12374 moveToParent();
12375 m_ctx.completeCycle();
12376 }
12377 void TrackerBase::markAsNeedingAnotherRun() {
12378 m_runState = NeedsAnotherRun;
12379 }
12380
12381 void TrackerBase::moveToParent() {
12382 assert( m_parent );
12383 m_ctx.setCurrentTracker( m_parent );
12384 }
12385 void TrackerBase::moveToThis() {
12386 m_ctx.setCurrentTracker( this );
12387 }
12388
12389 SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
12390 : TrackerBase( nameAndLocation, ctx, parent )
12391 {
12392 if( parent ) {
12393 while( !parent->isSectionTracker() )
12394 parent = &parent->parent();
12395
12396 SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
12397 addNextFilters( parentSection.m_filters );
12398 }
12399 }
12400
12401 bool SectionTracker::isComplete() const {
12402 bool complete = true;
12403
12404 if ((m_filters.empty() || m_filters[0] == "") ||
12405 std::find(m_filters.begin(), m_filters.end(),
12406 m_nameAndLocation.name) != m_filters.end())
12407 complete = TrackerBase::isComplete();
12408 return complete;
12409
12410 }
12411
12412 bool SectionTracker::isSectionTracker() const { return true; }
12413
12414 SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
12416
12417 ITracker& currentTracker = ctx.currentTracker();
12418 if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
12419 assert( childTracker );
12420 assert( childTracker->isSectionTracker() );
12421 section = std::static_pointer_cast<SectionTracker>( childTracker );
12422 }
12423 else {
12424 section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
12425 currentTracker.addChild( section );
12426 }
12427 if( !ctx.completedCycle() )
12428 section->tryOpen();
12429 return *section;
12430 }
12431
12432 void SectionTracker::tryOpen() {
12433 if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
12434 open();
12435 }
12436
12437 void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
12438 if( !filters.empty() ) {
12439 m_filters.push_back(""); // Root - should never be consulted
12440 m_filters.push_back(""); // Test Case - not a section filter
12441 m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
12442 }
12443 }
12444 void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
12445 if( filters.size() > 1 )
12446 m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
12447 }
12448
12449} // namespace TestCaseTracking
12450
12451using TestCaseTracking::ITracker;
12452using TestCaseTracking::TrackerContext;
12453using TestCaseTracking::SectionTracker;
12454
12455} // namespace Catch
12456
12457#if defined(__clang__)
12458# pragma clang diagnostic pop
12459#endif
12460// end catch_test_case_tracker.cpp
12461// start catch_test_registry.cpp
12462
12463namespace Catch {
12464
12465 auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
12466 return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
12467 }
12468
12469 NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
12470
12471 AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
12472 CATCH_TRY {
12474 .registerTest(
12476 invoker,
12477 extractClassName( classOrMethod ),
12478 nameAndTags,
12479 lineInfo));
12480 } CATCH_CATCH_ALL {
12481 // Do not throw when constructing global objects, instead register the exception to be processed later
12483 }
12484 }
12485
12486 AutoReg::~AutoReg() = default;
12487}
12488// end catch_test_registry.cpp
12489// start catch_test_spec.cpp
12490
12491#include <algorithm>
12492#include <string>
12493#include <vector>
12494#include <memory>
12495
12496namespace Catch {
12497
12498 TestSpec::Pattern::~Pattern() = default;
12499 TestSpec::NamePattern::~NamePattern() = default;
12500 TestSpec::TagPattern::~TagPattern() = default;
12501 TestSpec::ExcludedPattern::~ExcludedPattern() = default;
12502
12503 TestSpec::NamePattern::NamePattern( std::string const& name )
12504 : m_wildcardPattern( toLower( name ), CaseSensitive::No )
12505 {}
12506 bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
12507 return m_wildcardPattern.matches( toLower( testCase.name ) );
12508 }
12509
12510 TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
12511 bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
12512 return std::find(begin(testCase.lcaseTags),
12513 end(testCase.lcaseTags),
12514 m_tag) != end(testCase.lcaseTags);
12515 }
12516
12517 TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
12518 bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
12519
12520 bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
12521 // All patterns in a filter must match for the filter to be a match
12522 for( auto const& pattern : m_patterns ) {
12523 if( !pattern->matches( testCase ) )
12524 return false;
12525 }
12526 return true;
12527 }
12528
12529 bool TestSpec::hasFilters() const {
12530 return !m_filters.empty();
12531 }
12532 bool TestSpec::matches( TestCaseInfo const& testCase ) const {
12533 // A TestSpec matches if any filter matches
12534 for( auto const& filter : m_filters )
12535 if( filter.matches( testCase ) )
12536 return true;
12537 return false;
12538 }
12539}
12540// end catch_test_spec.cpp
12541// start catch_test_spec_parser.cpp
12542
12543namespace Catch {
12544
12545 TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
12546
12547 TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
12548 m_mode = None;
12549 m_exclusion = false;
12550 m_start = std::string::npos;
12551 m_arg = m_tagAliases->expandAliases( arg );
12552 m_escapeChars.clear();
12553 for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
12554 visitChar( m_arg[m_pos] );
12555 if( m_mode == Name )
12556 addPattern<TestSpec::NamePattern>();
12557 return *this;
12558 }
12559 TestSpec TestSpecParser::testSpec() {
12560 addFilter();
12561 return m_testSpec;
12562 }
12563
12564 void TestSpecParser::visitChar( char c ) {
12565 if( m_mode == None ) {
12566 switch( c ) {
12567 case ' ': return;
12568 case '~': m_exclusion = true; return;
12569 case '[': return startNewMode( Tag, ++m_pos );
12570 case '"': return startNewMode( QuotedName, ++m_pos );
12571 case '\\': return escape();
12572 default: startNewMode( Name, m_pos ); break;
12573 }
12574 }
12575 if( m_mode == Name ) {
12576 if( c == ',' ) {
12577 addPattern<TestSpec::NamePattern>();
12578 addFilter();
12579 }
12580 else if( c == '[' ) {
12581 if( subString() == "exclude:" )
12582 m_exclusion = true;
12583 else
12584 addPattern<TestSpec::NamePattern>();
12585 startNewMode( Tag, ++m_pos );
12586 }
12587 else if( c == '\\' )
12588 escape();
12589 }
12590 else if( m_mode == EscapedName )
12591 m_mode = Name;
12592 else if( m_mode == QuotedName && c == '"' )
12593 addPattern<TestSpec::NamePattern>();
12594 else if( m_mode == Tag && c == ']' )
12595 addPattern<TestSpec::TagPattern>();
12596 }
12597 void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
12598 m_mode = mode;
12599 m_start = start;
12600 }
12601 void TestSpecParser::escape() {
12602 if( m_mode == None )
12603 m_start = m_pos;
12604 m_mode = EscapedName;
12605 m_escapeChars.push_back( m_pos );
12606 }
12607 std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
12608
12609 void TestSpecParser::addFilter() {
12610 if( !m_currentFilter.m_patterns.empty() ) {
12611 m_testSpec.m_filters.push_back( m_currentFilter );
12612 m_currentFilter = TestSpec::Filter();
12613 }
12614 }
12615
12616 TestSpec parseTestSpec( std::string const& arg ) {
12617 return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
12618 }
12619
12620} // namespace Catch
12621// end catch_test_spec_parser.cpp
12622// start catch_timer.cpp
12623
12624#include <chrono>
12625
12626static const uint64_t nanosecondsInSecond = 1000000000;
12627
12628namespace Catch {
12629
12630 auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
12631 return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
12632 }
12633
12634 namespace {
12635 auto estimateClockResolution() -> uint64_t {
12636 uint64_t sum = 0;
12637 static const uint64_t iterations = 1000000;
12638
12639 auto startTime = getCurrentNanosecondsSinceEpoch();
12640
12641 for( std::size_t i = 0; i < iterations; ++i ) {
12642
12643 uint64_t ticks;
12644 uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
12645 do {
12647 } while( ticks == baseTicks );
12648
12649 auto delta = ticks - baseTicks;
12650 sum += delta;
12651
12652 // If we have been calibrating for over 3 seconds -- the clock
12653 // is terrible and we should move on.
12654 // TBD: How to signal that the measured resolution is probably wrong?
12655 if (ticks > startTime + 3 * nanosecondsInSecond) {
12656 return sum / ( i + 1u );
12657 }
12658 }
12659
12660 // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
12661 // - and potentially do more iterations if there's a high variance.
12662 return sum/iterations;
12663 }
12664 }
12665 auto getEstimatedClockResolution() -> uint64_t {
12666 static auto s_resolution = estimateClockResolution();
12667 return s_resolution;
12668 }
12669
12670 void Timer::start() {
12671 m_nanoseconds = getCurrentNanosecondsSinceEpoch();
12672 }
12673 auto Timer::getElapsedNanoseconds() const -> uint64_t {
12674 return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
12675 }
12676 auto Timer::getElapsedMicroseconds() const -> uint64_t {
12677 return getElapsedNanoseconds()/1000;
12678 }
12679 auto Timer::getElapsedMilliseconds() const -> unsigned int {
12680 return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
12681 }
12682 auto Timer::getElapsedSeconds() const -> double {
12683 return getElapsedMicroseconds()/1000000.0;
12684 }
12685
12686} // namespace Catch
12687// end catch_timer.cpp
12688// start catch_tostring.cpp
12689
12690#if defined(__clang__)
12691# pragma clang diagnostic push
12692# pragma clang diagnostic ignored "-Wexit-time-destructors"
12693# pragma clang diagnostic ignored "-Wglobal-constructors"
12694#endif
12695
12696// Enable specific decls locally
12697#if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
12698#define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
12699#endif
12700
12701#include <cmath>
12702#include <iomanip>
12703
12704namespace Catch {
12705
12706namespace Detail {
12707
12708 const std::string unprintableString = "{?}";
12709
12710 namespace {
12711 const int hexThreshold = 255;
12712
12713 struct Endianness {
12714 enum Arch { Big, Little };
12715
12716 static Arch which() {
12717 union _{
12718 int asInt;
12719 char asChar[sizeof (int)];
12720 } u;
12721
12722 u.asInt = 1;
12723 return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
12724 }
12725 };
12726 }
12727
12728 std::string rawMemoryToString( const void *object, std::size_t size ) {
12729 // Reverse order for little endian architectures
12730 int i = 0, end = static_cast<int>( size ), inc = 1;
12731 if( Endianness::which() == Endianness::Little ) {
12732 i = end-1;
12733 end = inc = -1;
12734 }
12735
12736 unsigned char const *bytes = static_cast<unsigned char const *>(object);
12737 ReusableStringStream rss;
12738 rss << "0x" << std::setfill('0') << std::hex;
12739 for( ; i != end; i += inc )
12740 rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
12741 return rss.str();
12742 }
12743}
12744
12745template<typename T>
12746std::string fpToString( T value, int precision ) {
12747 if (Catch::isnan(value)) {
12748 return "nan";
12749 }
12750
12751 ReusableStringStream rss;
12752 rss << std::setprecision( precision )
12753 << std::fixed
12754 << value;
12755 std::string d = rss.str();
12756 std::size_t i = d.find_last_not_of( '0' );
12757 if( i != std::string::npos && i != d.size()-1 ) {
12758 if( d[i] == '.' )
12759 i++;
12760 d = d.substr( 0, i+1 );
12761 }
12762 return d;
12763}
12764
12765//// ======================================================= ////
12766//
12767// Out-of-line defs for full specialization of StringMaker
12768//
12769//// ======================================================= ////
12770
12772 if (!getCurrentContext().getConfig()->showInvisibles()) {
12773 return '"' + str + '"';
12774 }
12775
12776 std::string s("\"");
12777 for (char c : str) {
12778 switch (c) {
12779 case '\n':
12780 s.append("\\n");
12781 break;
12782 case '\t':
12783 s.append("\\t");
12784 break;
12785 default:
12786 s.push_back(c);
12787 break;
12788 }
12789 }
12790 s.append("\"");
12791 return s;
12792}
12793
12794#ifdef CATCH_CONFIG_CPP17_STRING_VIEW
12796 return ::Catch::Detail::stringify(std::string{ str });
12797}
12798#endif
12799
12801 if (str) {
12802 return ::Catch::Detail::stringify(std::string{ str });
12803 } else {
12804 return{ "{null string}" };
12805 }
12806}
12808 if (str) {
12809 return ::Catch::Detail::stringify(std::string{ str });
12810 } else {
12811 return{ "{null string}" };
12812 }
12813}
12814
12815#ifdef CATCH_CONFIG_WCHAR
12817 std::string s;
12818 s.reserve(wstr.size());
12819 for (auto c : wstr) {
12820 s += (c <= 0xff) ? static_cast<char>(c) : '?';
12821 }
12822 return ::Catch::Detail::stringify(s);
12823}
12824
12825# ifdef CATCH_CONFIG_CPP17_STRING_VIEW
12828}
12829# endif
12830
12832 if (str) {
12833 return ::Catch::Detail::stringify(std::wstring{ str });
12834 } else {
12835 return{ "{null string}" };
12836 }
12837}
12839 if (str) {
12840 return ::Catch::Detail::stringify(std::wstring{ str });
12841 } else {
12842 return{ "{null string}" };
12843 }
12844}
12845#endif
12846
12848 return ::Catch::Detail::stringify(static_cast<long long>(value));
12849}
12851 return ::Catch::Detail::stringify(static_cast<long long>(value));
12852}
12854 ReusableStringStream rss;
12855 rss << value;
12856 if (value > Detail::hexThreshold) {
12857 rss << " (0x" << std::hex << value << ')';
12858 }
12859 return rss.str();
12860}
12861
12863 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
12864}
12866 return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
12867}
12869 ReusableStringStream rss;
12870 rss << value;
12871 if (value > Detail::hexThreshold) {
12872 rss << " (0x" << std::hex << value << ')';
12873 }
12874 return rss.str();
12875}
12876
12878 return b ? "true" : "false";
12879}
12880
12882 if (value == '\r') {
12883 return "'\\r'";
12884 } else if (value == '\f') {
12885 return "'\\f'";
12886 } else if (value == '\n') {
12887 return "'\\n'";
12888 } else if (value == '\t') {
12889 return "'\\t'";
12890 } else if ('\0' <= value && value < ' ') {
12891 return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
12892 } else {
12893 char chstr[] = "' '";
12894 chstr[1] = value;
12895 return chstr;
12896 }
12897}
12899 return ::Catch::Detail::stringify(static_cast<signed char>(c));
12900}
12902 return ::Catch::Detail::stringify(static_cast<char>(c));
12903}
12904
12906 return "nullptr";
12907}
12908
12909int StringMaker<float>::precision = 5;
12910
12912 return fpToString(value, precision) + 'f';
12913}
12914
12915int StringMaker<double>::precision = 10;
12916
12918 return fpToString(value, precision);
12919}
12920
12921std::string ratio_string<std::atto>::symbol() { return "a"; }
12922std::string ratio_string<std::femto>::symbol() { return "f"; }
12923std::string ratio_string<std::pico>::symbol() { return "p"; }
12924std::string ratio_string<std::nano>::symbol() { return "n"; }
12925std::string ratio_string<std::micro>::symbol() { return "u"; }
12926std::string ratio_string<std::milli>::symbol() { return "m"; }
12927
12928} // end namespace Catch
12929
12930#if defined(__clang__)
12931# pragma clang diagnostic pop
12932#endif
12933
12934// end catch_tostring.cpp
12935// start catch_totals.cpp
12936
12937namespace Catch {
12938
12939 Counts Counts::operator - ( Counts const& other ) const {
12940 Counts diff;
12941 diff.passed = passed - other.passed;
12942 diff.failed = failed - other.failed;
12943 diff.failedButOk = failedButOk - other.failedButOk;
12944 return diff;
12945 }
12946
12947 Counts& Counts::operator += ( Counts const& other ) {
12948 passed += other.passed;
12949 failed += other.failed;
12950 failedButOk += other.failedButOk;
12951 return *this;
12952 }
12953
12954 std::size_t Counts::total() const {
12955 return passed + failed + failedButOk;
12956 }
12957 bool Counts::allPassed() const {
12958 return failed == 0 && failedButOk == 0;
12959 }
12960 bool Counts::allOk() const {
12961 return failed == 0;
12962 }
12963
12964 Totals Totals::operator - ( Totals const& other ) const {
12965 Totals diff;
12966 diff.assertions = assertions - other.assertions;
12967 diff.testCases = testCases - other.testCases;
12968 return diff;
12969 }
12970
12971 Totals& Totals::operator += ( Totals const& other ) {
12972 assertions += other.assertions;
12973 testCases += other.testCases;
12974 return *this;
12975 }
12976
12977 Totals Totals::delta( Totals const& prevTotals ) const {
12978 Totals diff = *this - prevTotals;
12979 if( diff.assertions.failed > 0 )
12980 ++diff.testCases.failed;
12981 else if( diff.assertions.failedButOk > 0 )
12982 ++diff.testCases.failedButOk;
12983 else
12984 ++diff.testCases.passed;
12985 return diff;
12986 }
12987
12988}
12989// end catch_totals.cpp
12990// start catch_uncaught_exceptions.cpp
12991
12992#include <exception>
12993
12994namespace Catch {
12995 bool uncaught_exceptions() {
12996#if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
12997 return std::uncaught_exceptions() > 0;
12998#else
12999 return std::uncaught_exception();
13000#endif
13001 }
13002} // end namespace Catch
13003// end catch_uncaught_exceptions.cpp
13004// start catch_version.cpp
13005
13006#include <ostream>
13007
13008namespace Catch {
13009
13010 Version::Version
13011 ( unsigned int _majorVersion,
13012 unsigned int _minorVersion,
13013 unsigned int _patchNumber,
13014 char const * const _branchName,
13015 unsigned int _buildNumber )
13016 : majorVersion( _majorVersion ),
13017 minorVersion( _minorVersion ),
13018 patchNumber( _patchNumber ),
13019 branchName( _branchName ),
13020 buildNumber( _buildNumber )
13021 {}
13022
13023 std::ostream& operator << ( std::ostream& os, Version const& version ) {
13024 os << version.majorVersion << '.'
13025 << version.minorVersion << '.'
13026 << version.patchNumber;
13027 // branchName is never null -> 0th char is \0 if it is empty
13028 if (version.branchName[0]) {
13029 os << '-' << version.branchName
13030 << '.' << version.buildNumber;
13031 }
13032 return os;
13033 }
13034
13035 Version const& libraryVersion() {
13036 static Version version( 2, 8, 0, "", 0 );
13037 return version;
13038 }
13039
13040}
13041// end catch_version.cpp
13042// start catch_wildcard_pattern.cpp
13043
13044#include <sstream>
13045
13046namespace Catch {
13047
13048 WildcardPattern::WildcardPattern( std::string const& pattern,
13049 CaseSensitive::Choice caseSensitivity )
13050 : m_caseSensitivity( caseSensitivity ),
13051 m_pattern( adjustCase( pattern ) )
13052 {
13053 if( startsWith( m_pattern, '*' ) ) {
13054 m_pattern = m_pattern.substr( 1 );
13055 m_wildcard = WildcardAtStart;
13056 }
13057 if( endsWith( m_pattern, '*' ) ) {
13058 m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
13059 m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
13060 }
13061 }
13062
13063 bool WildcardPattern::matches( std::string const& str ) const {
13064 switch( m_wildcard ) {
13065 case NoWildcard:
13066 return m_pattern == adjustCase( str );
13067 case WildcardAtStart:
13068 return endsWith( adjustCase( str ), m_pattern );
13069 case WildcardAtEnd:
13070 return startsWith( adjustCase( str ), m_pattern );
13071 case WildcardAtBothEnds:
13072 return contains( adjustCase( str ), m_pattern );
13073 default:
13074 CATCH_INTERNAL_ERROR( "Unknown enum" );
13075 }
13076 }
13077
13078 std::string WildcardPattern::adjustCase( std::string const& str ) const {
13079 return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
13080 }
13081}
13082// end catch_wildcard_pattern.cpp
13083// start catch_xmlwriter.cpp
13084
13085#include <iomanip>
13086
13087using uchar = unsigned char;
13088
13089namespace Catch {
13090
13091namespace {
13092
13093 size_t trailingBytes(unsigned char c) {
13094 if ((c & 0xE0) == 0xC0) {
13095 return 2;
13096 }
13097 if ((c & 0xF0) == 0xE0) {
13098 return 3;
13099 }
13100 if ((c & 0xF8) == 0xF0) {
13101 return 4;
13102 }
13103 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
13104 }
13105
13106 uint32_t headerValue(unsigned char c) {
13107 if ((c & 0xE0) == 0xC0) {
13108 return c & 0x1F;
13109 }
13110 if ((c & 0xF0) == 0xE0) {
13111 return c & 0x0F;
13112 }
13113 if ((c & 0xF8) == 0xF0) {
13114 return c & 0x07;
13115 }
13116 CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
13117 }
13118
13119 void hexEscapeChar(std::ostream& os, unsigned char c) {
13120 std::ios_base::fmtflags f(os.flags());
13121 os << "\\x"
13122 << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
13123 << static_cast<int>(c);
13124 os.flags(f);
13125 }
13126
13127} // anonymous namespace
13128
13129 XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
13130 : m_str( str ),
13131 m_forWhat( forWhat )
13132 {}
13133
13134 void XmlEncode::encodeTo( std::ostream& os ) const {
13135 // Apostrophe escaping not necessary if we always use " to write attributes
13136 // (see: http://www.w3.org/TR/xml/#syntax)
13137
13138 for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
13139 uchar c = m_str[idx];
13140 switch (c) {
13141 case '<': os << "&lt;"; break;
13142 case '&': os << "&amp;"; break;
13143
13144 case '>':
13145 // See: http://www.w3.org/TR/xml/#syntax
13146 if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
13147 os << "&gt;";
13148 else
13149 os << c;
13150 break;
13151
13152 case '\"':
13153 if (m_forWhat == ForAttributes)
13154 os << "&quot;";
13155 else
13156 os << c;
13157 break;
13158
13159 default:
13160 // Check for control characters and invalid utf-8
13161
13162 // Escape control characters in standard ascii
13163 // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
13164 if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
13165 hexEscapeChar(os, c);
13166 break;
13167 }
13168
13169 // Plain ASCII: Write it to stream
13170 if (c < 0x7F) {
13171 os << c;
13172 break;
13173 }
13174
13175 // UTF-8 territory
13176 // Check if the encoding is valid and if it is not, hex escape bytes.
13177 // Important: We do not check the exact decoded values for validity, only the encoding format
13178 // First check that this bytes is a valid lead byte:
13179 // This means that it is not encoded as 1111 1XXX
13180 // Or as 10XX XXXX
13181 if (c < 0xC0 ||
13182 c >= 0xF8) {
13183 hexEscapeChar(os, c);
13184 break;
13185 }
13186
13187 auto encBytes = trailingBytes(c);
13188 // Are there enough bytes left to avoid accessing out-of-bounds memory?
13189 if (idx + encBytes - 1 >= m_str.size()) {
13190 hexEscapeChar(os, c);
13191 break;
13192 }
13193 // The header is valid, check data
13194 // The next encBytes bytes must together be a valid utf-8
13195 // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
13196 bool valid = true;
13197 uint32_t value = headerValue(c);
13198 for (std::size_t n = 1; n < encBytes; ++n) {
13199 uchar nc = m_str[idx + n];
13200 valid &= ((nc & 0xC0) == 0x80);
13201 value = (value << 6) | (nc & 0x3F);
13202 }
13203
13204 if (
13205 // Wrong bit pattern of following bytes
13206 (!valid) ||
13207 // Overlong encodings
13208 (value < 0x80) ||
13209 (0x80 <= value && value < 0x800 && encBytes > 2) ||
13210 (0x800 < value && value < 0x10000 && encBytes > 3) ||
13211 // Encoded value out of range
13212 (value >= 0x110000)
13213 ) {
13214 hexEscapeChar(os, c);
13215 break;
13216 }
13217
13218 // If we got here, this is in fact a valid(ish) utf-8 sequence
13219 for (std::size_t n = 0; n < encBytes; ++n) {
13220 os << m_str[idx + n];
13221 }
13222 idx += encBytes - 1;
13223 break;
13224 }
13225 }
13226 }
13227
13228 std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
13229 xmlEncode.encodeTo( os );
13230 return os;
13231 }
13232
13233 XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
13234 : m_writer( writer )
13235 {}
13236
13237 XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
13238 : m_writer( other.m_writer ){
13239 other.m_writer = nullptr;
13240 }
13241 XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
13242 if ( m_writer ) {
13243 m_writer->endElement();
13244 }
13245 m_writer = other.m_writer;
13246 other.m_writer = nullptr;
13247 return *this;
13248 }
13249
13250 XmlWriter::ScopedElement::~ScopedElement() {
13251 if( m_writer )
13252 m_writer->endElement();
13253 }
13254
13255 XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
13256 m_writer->writeText( text, indent );
13257 return *this;
13258 }
13259
13260 XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
13261 {
13262 writeDeclaration();
13263 }
13264
13265 XmlWriter::~XmlWriter() {
13266 while( !m_tags.empty() )
13267 endElement();
13268 }
13269
13270 XmlWriter& XmlWriter::startElement( std::string const& name ) {
13271 ensureTagClosed();
13272 newlineIfNecessary();
13273 m_os << m_indent << '<' << name;
13274 m_tags.push_back( name );
13275 m_indent += " ";
13276 m_tagIsOpen = true;
13277 return *this;
13278 }
13279
13280 XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
13281 ScopedElement scoped( this );
13282 startElement( name );
13283 return scoped;
13284 }
13285
13286 XmlWriter& XmlWriter::endElement() {
13287 newlineIfNecessary();
13288 m_indent = m_indent.substr( 0, m_indent.size()-2 );
13289 if( m_tagIsOpen ) {
13290 m_os << "/>";
13291 m_tagIsOpen = false;
13292 }
13293 else {
13294 m_os << m_indent << "</" << m_tags.back() << ">";
13295 }
13296 m_os << std::endl;
13297 m_tags.pop_back();
13298 return *this;
13299 }
13300
13301 XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
13302 if( !name.empty() && !attribute.empty() )
13303 m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
13304 return *this;
13305 }
13306
13307 XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
13308 m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
13309 return *this;
13310 }
13311
13312 XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
13313 if( !text.empty() ){
13314 bool tagWasOpen = m_tagIsOpen;
13315 ensureTagClosed();
13316 if( tagWasOpen && indent )
13317 m_os << m_indent;
13318 m_os << XmlEncode( text );
13319 m_needsNewline = true;
13320 }
13321 return *this;
13322 }
13323
13324 XmlWriter& XmlWriter::writeComment( std::string const& text ) {
13325 ensureTagClosed();
13326 m_os << m_indent << "<!--" << text << "-->";
13327 m_needsNewline = true;
13328 return *this;
13329 }
13330
13331 void XmlWriter::writeStylesheetRef( std::string const& url ) {
13332 m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
13333 }
13334
13335 XmlWriter& XmlWriter::writeBlankLine() {
13336 ensureTagClosed();
13337 m_os << '\n';
13338 return *this;
13339 }
13340
13341 void XmlWriter::ensureTagClosed() {
13342 if( m_tagIsOpen ) {
13343 m_os << ">" << std::endl;
13344 m_tagIsOpen = false;
13345 }
13346 }
13347
13348 void XmlWriter::writeDeclaration() {
13349 m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
13350 }
13351
13352 void XmlWriter::newlineIfNecessary() {
13353 if( m_needsNewline ) {
13354 m_os << std::endl;
13355 m_needsNewline = false;
13356 }
13357 }
13358}
13359// end catch_xmlwriter.cpp
13360// start catch_reporter_bases.cpp
13361
13362#include <cstring>
13363#include <cfloat>
13364#include <cstdio>
13365#include <cassert>
13366#include <memory>
13367
13368namespace Catch {
13369 void prepareExpandedExpression(AssertionResult& result) {
13370 result.getExpandedExpression();
13371 }
13372
13373 // Because formatting using c++ streams is stateful, drop down to C is required
13374 // Alternatively we could use stringstream, but its performance is... not good.
13375 std::string getFormattedDuration( double duration ) {
13376 // Max exponent + 1 is required to represent the whole part
13377 // + 1 for decimal point
13378 // + 3 for the 3 decimal places
13379 // + 1 for null terminator
13380 const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
13381 char buffer[maxDoubleSize];
13382
13383 // Save previous errno, to prevent sprintf from overwriting it
13384 ErrnoGuard guard;
13385#ifdef _MSC_VER
13386 sprintf_s(buffer, "%.3f", duration);
13387#else
13388 std::sprintf(buffer, "%.3f", duration);
13389#endif
13390 return std::string(buffer);
13391 }
13392
13393 std::string serializeFilters( std::vector<std::string> const& container ) {
13394 ReusableStringStream oss;
13395 bool first = true;
13396 for (auto&& filter : container)
13397 {
13398 if (!first)
13399 oss << ' ';
13400 else
13401 first = false;
13402
13403 oss << filter;
13404 }
13405 return oss.str();
13406 }
13407
13408 TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
13409 :StreamingReporterBase(_config) {}
13410
13411 std::set<Verbosity> TestEventListenerBase::getSupportedVerbosities() {
13413 }
13414
13415 void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
13416
13417 bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
13418 return false;
13419 }
13420
13421} // end namespace Catch
13422// end catch_reporter_bases.cpp
13423// start catch_reporter_compact.cpp
13424
13425namespace {
13426
13427#ifdef CATCH_PLATFORM_MAC
13428 const char* failedString() { return "FAILED"; }
13429 const char* passedString() { return "PASSED"; }
13430#else
13431 const char* failedString() { return "failed"; }
13432 const char* passedString() { return "passed"; }
13433#endif
13434
13435 // Colour::LightGrey
13436 Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
13437
13438 std::string bothOrAll( std::size_t count ) {
13439 return count == 1 ? std::string() :
13440 count == 2 ? "both " : "all " ;
13441 }
13442
13443} // anon namespace
13444
13445namespace Catch {
13446namespace {
13447// Colour, message variants:
13448// - white: No tests ran.
13449// - red: Failed [both/all] N test cases, failed [both/all] M assertions.
13450// - white: Passed [both/all] N test cases (no assertions).
13451// - red: Failed N tests cases, failed M assertions.
13452// - green: Passed [both/all] N tests cases with M assertions.
13453void printTotals(std::ostream& out, const Totals& totals) {
13454 if (totals.testCases.total() == 0) {
13455 out << "No tests ran.";
13456 } else if (totals.testCases.failed == totals.testCases.total()) {
13457 Colour colour(Colour::ResultError);
13458 const std::string qualify_assertions_failed =
13459 totals.assertions.failed == totals.assertions.total() ?
13460 bothOrAll(totals.assertions.failed) : std::string();
13461 out <<
13462 "Failed " << bothOrAll(totals.testCases.failed)
13463 << pluralise(totals.testCases.failed, "test case") << ", "
13464 "failed " << qualify_assertions_failed <<
13465 pluralise(totals.assertions.failed, "assertion") << '.';
13466 } else if (totals.assertions.total() == 0) {
13467 out <<
13468 "Passed " << bothOrAll(totals.testCases.total())
13469 << pluralise(totals.testCases.total(), "test case")
13470 << " (no assertions).";
13471 } else if (totals.assertions.failed) {
13472 Colour colour(Colour::ResultError);
13473 out <<
13474 "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
13475 "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
13476 } else {
13477 Colour colour(Colour::ResultSuccess);
13478 out <<
13479 "Passed " << bothOrAll(totals.testCases.passed)
13480 << pluralise(totals.testCases.passed, "test case") <<
13481 " with " << pluralise(totals.assertions.passed, "assertion") << '.';
13482 }
13483}
13484
13485// Implementation of CompactReporter formatting
13486class AssertionPrinter {
13487public:
13488 AssertionPrinter& operator= (AssertionPrinter const&) = delete;
13489 AssertionPrinter(AssertionPrinter const&) = delete;
13490 AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
13491 : stream(_stream)
13492 , result(_stats.assertionResult)
13493 , messages(_stats.infoMessages)
13494 , itMessage(_stats.infoMessages.begin())
13495 , printInfoMessages(_printInfoMessages) {}
13496
13497 void print() {
13498 printSourceInfo();
13499
13500 itMessage = messages.begin();
13501
13502 switch (result.getResultType()) {
13503 case ResultWas::Ok:
13504 printResultType(Colour::ResultSuccess, passedString());
13505 printOriginalExpression();
13506 printReconstructedExpression();
13507 if (!result.hasExpression())
13508 printRemainingMessages(Colour::None);
13509 else
13510 printRemainingMessages();
13511 break;
13512 case ResultWas::ExpressionFailed:
13513 if (result.isOk())
13514 printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
13515 else
13516 printResultType(Colour::Error, failedString());
13517 printOriginalExpression();
13518 printReconstructedExpression();
13519 printRemainingMessages();
13520 break;
13521 case ResultWas::ThrewException:
13522 printResultType(Colour::Error, failedString());
13523 printIssue("unexpected exception with message:");
13524 printMessage();
13525 printExpressionWas();
13526 printRemainingMessages();
13527 break;
13528 case ResultWas::FatalErrorCondition:
13529 printResultType(Colour::Error, failedString());
13530 printIssue("fatal error condition with message:");
13531 printMessage();
13532 printExpressionWas();
13533 printRemainingMessages();
13534 break;
13535 case ResultWas::DidntThrowException:
13536 printResultType(Colour::Error, failedString());
13537 printIssue("expected exception, got none");
13538 printExpressionWas();
13539 printRemainingMessages();
13540 break;
13541 case ResultWas::Info:
13542 printResultType(Colour::None, "info");
13543 printMessage();
13544 printRemainingMessages();
13545 break;
13546 case ResultWas::Warning:
13547 printResultType(Colour::None, "warning");
13548 printMessage();
13549 printRemainingMessages();
13550 break;
13551 case ResultWas::ExplicitFailure:
13552 printResultType(Colour::Error, failedString());
13553 printIssue("explicitly");
13554 printRemainingMessages(Colour::None);
13555 break;
13556 // These cases are here to prevent compiler warnings
13557 case ResultWas::Unknown:
13558 case ResultWas::FailureBit:
13559 case ResultWas::Exception:
13560 printResultType(Colour::Error, "** internal error **");
13561 break;
13562 }
13563 }
13564
13565private:
13566 void printSourceInfo() const {
13567 Colour colourGuard(Colour::FileName);
13568 stream << result.getSourceInfo() << ':';
13569 }
13570
13571 void printResultType(Colour::Code colour, std::string const& passOrFail) const {
13572 if (!passOrFail.empty()) {
13573 {
13574 Colour colourGuard(colour);
13575 stream << ' ' << passOrFail;
13576 }
13577 stream << ':';
13578 }
13579 }
13580
13581 void printIssue(std::string const& issue) const {
13582 stream << ' ' << issue;
13583 }
13584
13585 void printExpressionWas() {
13586 if (result.hasExpression()) {
13587 stream << ';';
13588 {
13589 Colour colour(dimColour());
13590 stream << " expression was:";
13591 }
13592 printOriginalExpression();
13593 }
13594 }
13595
13596 void printOriginalExpression() const {
13597 if (result.hasExpression()) {
13598 stream << ' ' << result.getExpression();
13599 }
13600 }
13601
13602 void printReconstructedExpression() const {
13603 if (result.hasExpandedExpression()) {
13604 {
13605 Colour colour(dimColour());
13606 stream << " for: ";
13607 }
13608 stream << result.getExpandedExpression();
13609 }
13610 }
13611
13612 void printMessage() {
13613 if (itMessage != messages.end()) {
13614 stream << " '" << itMessage->message << '\'';
13615 ++itMessage;
13616 }
13617 }
13618
13619 void printRemainingMessages(Colour::Code colour = dimColour()) {
13620 if (itMessage == messages.end())
13621 return;
13622
13623 // using messages.end() directly yields (or auto) compilation error:
13625 const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
13626
13627 {
13628 Colour colourGuard(colour);
13629 stream << " with " << pluralise(N, "message") << ':';
13630 }
13631
13632 for (; itMessage != itEnd; ) {
13633 // If this assertion is a warning ignore any INFO messages
13634 if (printInfoMessages || itMessage->type != ResultWas::Info) {
13635 stream << " '" << itMessage->message << '\'';
13636 if (++itMessage != itEnd) {
13637 Colour colourGuard(dimColour());
13638 stream << " and";
13639 }
13640 }
13641 }
13642 }
13643
13644private:
13645 std::ostream& stream;
13646 AssertionResult const& result;
13647 std::vector<MessageInfo> messages;
13649 bool printInfoMessages;
13650};
13651
13652} // anon namespace
13653
13654 std::string CompactReporter::getDescription() {
13655 return "Reports test results on a single line, suitable for IDEs";
13656 }
13657
13658 ReporterPreferences CompactReporter::getPreferences() const {
13659 return m_reporterPrefs;
13660 }
13661
13662 void CompactReporter::noMatchingTestCases( std::string const& spec ) {
13663 stream << "No test cases matched '" << spec << '\'' << std::endl;
13664 }
13665
13666 void CompactReporter::assertionStarting( AssertionInfo const& ) {}
13667
13668 bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
13669 AssertionResult const& result = _assertionStats.assertionResult;
13670
13671 bool printInfoMessages = true;
13672
13673 // Drop out if result was successful and we're not printing those
13674 if( !m_config->includeSuccessfulResults() && result.isOk() ) {
13675 if( result.getResultType() != ResultWas::Warning )
13676 return false;
13677 printInfoMessages = false;
13678 }
13679
13680 AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
13681 printer.print();
13682
13683 stream << std::endl;
13684 return true;
13685 }
13686
13687 void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
13688 if (m_config->showDurations() == ShowDurations::Always) {
13689 stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
13690 }
13691 }
13692
13693 void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
13694 printTotals( stream, _testRunStats.totals );
13695 stream << '\n' << std::endl;
13696 StreamingReporterBase::testRunEnded( _testRunStats );
13697 }
13698
13699 CompactReporter::~CompactReporter() {}
13700
13701 CATCH_REGISTER_REPORTER( "compact", CompactReporter )
13702
13703} // end namespace Catch
13704// end catch_reporter_compact.cpp
13705// start catch_reporter_console.cpp
13706
13707#include <cfloat>
13708#include <cstdio>
13709
13710#if defined(_MSC_VER)
13711#pragma warning(push)
13712#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
13713 // Note that 4062 (not all labels are handled
13714 // and default is missing) is enabled
13715#endif
13716
13717namespace Catch {
13718
13719namespace {
13720
13721// Formatter impl for ConsoleReporter
13722class ConsoleAssertionPrinter {
13723public:
13724 ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
13725 ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
13726 ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
13727 : stream(_stream),
13728 stats(_stats),
13729 result(_stats.assertionResult),
13730 colour(Colour::None),
13731 message(result.getMessage()),
13732 messages(_stats.infoMessages),
13733 printInfoMessages(_printInfoMessages) {
13734 switch (result.getResultType()) {
13735 case ResultWas::Ok:
13736 colour = Colour::Success;
13737 passOrFail = "PASSED";
13738 //if( result.hasMessage() )
13739 if (_stats.infoMessages.size() == 1)
13740 messageLabel = "with message";
13741 if (_stats.infoMessages.size() > 1)
13742 messageLabel = "with messages";
13743 break;
13744 case ResultWas::ExpressionFailed:
13745 if (result.isOk()) {
13746 colour = Colour::Success;
13747 passOrFail = "FAILED - but was ok";
13748 } else {
13749 colour = Colour::Error;
13750 passOrFail = "FAILED";
13751 }
13752 if (_stats.infoMessages.size() == 1)
13753 messageLabel = "with message";
13754 if (_stats.infoMessages.size() > 1)
13755 messageLabel = "with messages";
13756 break;
13757 case ResultWas::ThrewException:
13758 colour = Colour::Error;
13759 passOrFail = "FAILED";
13760 messageLabel = "due to unexpected exception with ";
13761 if (_stats.infoMessages.size() == 1)
13762 messageLabel += "message";
13763 if (_stats.infoMessages.size() > 1)
13764 messageLabel += "messages";
13765 break;
13766 case ResultWas::FatalErrorCondition:
13767 colour = Colour::Error;
13768 passOrFail = "FAILED";
13769 messageLabel = "due to a fatal error condition";
13770 break;
13771 case ResultWas::DidntThrowException:
13772 colour = Colour::Error;
13773 passOrFail = "FAILED";
13774 messageLabel = "because no exception was thrown where one was expected";
13775 break;
13776 case ResultWas::Info:
13777 messageLabel = "info";
13778 break;
13779 case ResultWas::Warning:
13780 messageLabel = "warning";
13781 break;
13782 case ResultWas::ExplicitFailure:
13783 passOrFail = "FAILED";
13784 colour = Colour::Error;
13785 if (_stats.infoMessages.size() == 1)
13786 messageLabel = "explicitly with message";
13787 if (_stats.infoMessages.size() > 1)
13788 messageLabel = "explicitly with messages";
13789 break;
13790 // These cases are here to prevent compiler warnings
13791 case ResultWas::Unknown:
13792 case ResultWas::FailureBit:
13793 case ResultWas::Exception:
13794 passOrFail = "** internal error **";
13795 colour = Colour::Error;
13796 break;
13797 }
13798 }
13799
13800 void print() const {
13801 printSourceInfo();
13802 if (stats.totals.assertions.total() > 0) {
13803 printResultType();
13804 printOriginalExpression();
13805 printReconstructedExpression();
13806 } else {
13807 stream << '\n';
13808 }
13809 printMessage();
13810 }
13811
13812private:
13813 void printResultType() const {
13814 if (!passOrFail.empty()) {
13815 Colour colourGuard(colour);
13816 stream << passOrFail << ":\n";
13817 }
13818 }
13819 void printOriginalExpression() const {
13820 if (result.hasExpression()) {
13821 Colour colourGuard(Colour::OriginalExpression);
13822 stream << " ";
13823 stream << result.getExpressionInMacro();
13824 stream << '\n';
13825 }
13826 }
13827 void printReconstructedExpression() const {
13828 if (result.hasExpandedExpression()) {
13829 stream << "with expansion:\n";
13830 Colour colourGuard(Colour::ReconstructedExpression);
13831 stream << Column(result.getExpandedExpression()).indent(2) << '\n';
13832 }
13833 }
13834 void printMessage() const {
13835 if (!messageLabel.empty())
13836 stream << messageLabel << ':' << '\n';
13837 for (auto const& msg : messages) {
13838 // If this assertion is a warning ignore any INFO messages
13839 if (printInfoMessages || msg.type != ResultWas::Info)
13840 stream << Column(msg.message).indent(2) << '\n';
13841 }
13842 }
13843 void printSourceInfo() const {
13844 Colour colourGuard(Colour::FileName);
13845 stream << result.getSourceInfo() << ": ";
13846 }
13847
13848 std::ostream& stream;
13849 AssertionStats const& stats;
13850 AssertionResult const& result;
13851 Colour::Code colour;
13852 std::string passOrFail;
13853 std::string messageLabel;
13854 std::string message;
13855 std::vector<MessageInfo> messages;
13856 bool printInfoMessages;
13857};
13858
13859std::size_t makeRatio(std::size_t number, std::size_t total) {
13860 std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
13861 return (ratio == 0 && number > 0) ? 1 : ratio;
13862}
13863
13864std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
13865 if (i > j && i > k)
13866 return i;
13867 else if (j > k)
13868 return j;
13869 else
13870 return k;
13871}
13872
13873struct ColumnInfo {
13874 enum Justification { Left, Right };
13876 int width;
13877 Justification justification;
13878};
13879struct ColumnBreak {};
13880struct RowBreak {};
13881
13882class Duration {
13883 enum class Unit {
13884 Auto,
13885 Nanoseconds,
13886 Microseconds,
13887 Milliseconds,
13888 Seconds,
13889 Minutes
13890 };
13891 static const uint64_t s_nanosecondsInAMicrosecond = 1000;
13892 static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
13893 static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
13894 static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
13895
13896 uint64_t m_inNanoseconds;
13897 Unit m_units;
13898
13899public:
13900 explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
13901 : m_inNanoseconds(inNanoseconds),
13902 m_units(units) {
13903 if (m_units == Unit::Auto) {
13904 if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
13905 m_units = Unit::Nanoseconds;
13906 else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
13907 m_units = Unit::Microseconds;
13908 else if (m_inNanoseconds < s_nanosecondsInASecond)
13909 m_units = Unit::Milliseconds;
13910 else if (m_inNanoseconds < s_nanosecondsInAMinute)
13911 m_units = Unit::Seconds;
13912 else
13913 m_units = Unit::Minutes;
13914 }
13915
13916 }
13917
13918 auto value() const -> double {
13919 switch (m_units) {
13920 case Unit::Microseconds:
13921 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
13922 case Unit::Milliseconds:
13923 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
13924 case Unit::Seconds:
13925 return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
13926 case Unit::Minutes:
13927 return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
13928 default:
13929 return static_cast<double>(m_inNanoseconds);
13930 }
13931 }
13932 auto unitsAsString() const -> std::string {
13933 switch (m_units) {
13934 case Unit::Nanoseconds:
13935 return "ns";
13936 case Unit::Microseconds:
13937 return "us";
13938 case Unit::Milliseconds:
13939 return "ms";
13940 case Unit::Seconds:
13941 return "s";
13942 case Unit::Minutes:
13943 return "m";
13944 default:
13945 return "** internal error **";
13946 }
13947
13948 }
13949 friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
13950 return os << duration.value() << " " << duration.unitsAsString();
13951 }
13952};
13953} // end anon namespace
13954
13955class TablePrinter {
13956 std::ostream& m_os;
13957 std::vector<ColumnInfo> m_columnInfos;
13958 std::ostringstream m_oss;
13959 int m_currentColumn = -1;
13960 bool m_isOpen = false;
13961
13962public:
13963 TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
13964 : m_os( os ),
13965 m_columnInfos( std::move( columnInfos ) ) {}
13966
13967 auto columnInfos() const -> std::vector<ColumnInfo> const& {
13968 return m_columnInfos;
13969 }
13970
13971 void open() {
13972 if (!m_isOpen) {
13973 m_isOpen = true;
13974 *this << RowBreak();
13975 for (auto const& info : m_columnInfos)
13976 *this << info.name << ColumnBreak();
13977 *this << RowBreak();
13978 m_os << Catch::getLineOfChars<'-'>() << "\n";
13979 }
13980 }
13981 void close() {
13982 if (m_isOpen) {
13983 *this << RowBreak();
13984 m_os << std::endl;
13985 m_isOpen = false;
13986 }
13987 }
13988
13989 template<typename T>
13990 friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
13991 tp.m_oss << value;
13992 return tp;
13993 }
13994
13995 friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
13996 auto colStr = tp.m_oss.str();
13997 // This takes account of utf8 encodings
13998 auto strSize = Catch::StringRef(colStr).numberOfCharacters();
13999 tp.m_oss.str("");
14000 tp.open();
14001 if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
14002 tp.m_currentColumn = -1;
14003 tp.m_os << "\n";
14004 }
14005 tp.m_currentColumn++;
14006
14007 auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
14008 auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
14009 ? std::string(colInfo.width - (strSize + 2), ' ')
14010 : std::string();
14011 if (colInfo.justification == ColumnInfo::Left)
14012 tp.m_os << colStr << padding << " ";
14013 else
14014 tp.m_os << padding << colStr << " ";
14015 return tp;
14016 }
14017
14018 friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
14019 if (tp.m_currentColumn > 0) {
14020 tp.m_os << "\n";
14021 tp.m_currentColumn = -1;
14022 }
14023 return tp;
14024 }
14025};
14026
14027ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
14028 : StreamingReporterBase(config),
14029 m_tablePrinter(new TablePrinter(config.stream(),
14030 {
14031 { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
14032 { "iters", 8, ColumnInfo::Right },
14033 { "elapsed ns", 14, ColumnInfo::Right },
14034 { "average", 14, ColumnInfo::Right }
14035 })) {}
14036ConsoleReporter::~ConsoleReporter() = default;
14037
14038std::string ConsoleReporter::getDescription() {
14039 return "Reports test results as plain lines of text";
14040}
14041
14042void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
14043 stream << "No test cases matched '" << spec << '\'' << std::endl;
14044}
14045
14046void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
14047
14048bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
14049 AssertionResult const& result = _assertionStats.assertionResult;
14050
14051 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
14052
14053 // Drop out if result was successful but we're not printing them.
14054 if (!includeResults && result.getResultType() != ResultWas::Warning)
14055 return false;
14056
14057 lazyPrint();
14058
14059 ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
14060 printer.print();
14061 stream << std::endl;
14062 return true;
14063}
14064
14065void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
14066 m_headerPrinted = false;
14067 StreamingReporterBase::sectionStarting(_sectionInfo);
14068}
14069void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
14070 m_tablePrinter->close();
14071 if (_sectionStats.missingAssertions) {
14072 lazyPrint();
14073 Colour colour(Colour::ResultError);
14074 if (m_sectionStack.size() > 1)
14075 stream << "\nNo assertions in section";
14076 else
14077 stream << "\nNo assertions in test case";
14078 stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
14079 }
14080 if (m_config->showDurations() == ShowDurations::Always) {
14081 stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
14082 }
14083 if (m_headerPrinted) {
14084 m_headerPrinted = false;
14085 }
14086 StreamingReporterBase::sectionEnded(_sectionStats);
14087}
14088
14089void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
14090 lazyPrintWithoutClosingBenchmarkTable();
14091
14092 auto nameCol = Column( info.name ).width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) );
14093
14094 bool firstLine = true;
14095 for (auto line : nameCol) {
14096 if (!firstLine)
14097 (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
14098 else
14099 firstLine = false;
14100
14101 (*m_tablePrinter) << line << ColumnBreak();
14102 }
14103}
14104void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) {
14105 Duration average(stats.elapsedTimeInNanoseconds / stats.iterations);
14106 (*m_tablePrinter)
14107 << stats.iterations << ColumnBreak()
14108 << stats.elapsedTimeInNanoseconds << ColumnBreak()
14109 << average << ColumnBreak();
14110}
14111
14112void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
14113 m_tablePrinter->close();
14114 StreamingReporterBase::testCaseEnded(_testCaseStats);
14115 m_headerPrinted = false;
14116}
14117void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
14118 if (currentGroupInfo.used) {
14119 printSummaryDivider();
14120 stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
14121 printTotals(_testGroupStats.totals);
14122 stream << '\n' << std::endl;
14123 }
14124 StreamingReporterBase::testGroupEnded(_testGroupStats);
14125}
14126void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
14127 printTotalsDivider(_testRunStats.totals);
14128 printTotals(_testRunStats.totals);
14129 stream << std::endl;
14130 StreamingReporterBase::testRunEnded(_testRunStats);
14131}
14132void ConsoleReporter::testRunStarting(TestRunInfo const& _testInfo) {
14133 StreamingReporterBase::testRunStarting(_testInfo);
14134 printTestFilters();
14135}
14136
14137void ConsoleReporter::lazyPrint() {
14138
14139 m_tablePrinter->close();
14140 lazyPrintWithoutClosingBenchmarkTable();
14141}
14142
14143void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
14144
14145 if (!currentTestRunInfo.used)
14146 lazyPrintRunInfo();
14147 if (!currentGroupInfo.used)
14148 lazyPrintGroupInfo();
14149
14150 if (!m_headerPrinted) {
14151 printTestCaseAndSectionHeader();
14152 m_headerPrinted = true;
14153 }
14154}
14155void ConsoleReporter::lazyPrintRunInfo() {
14156 stream << '\n' << getLineOfChars<'~'>() << '\n';
14157 Colour colour(Colour::SecondaryText);
14158 stream << currentTestRunInfo->name
14159 << " is a Catch v" << libraryVersion() << " host application.\n"
14160 << "Run with -? for options\n\n";
14161
14162 if (m_config->rngSeed() != 0)
14163 stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
14164
14165 currentTestRunInfo.used = true;
14166}
14167void ConsoleReporter::lazyPrintGroupInfo() {
14168 if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
14169 printClosedHeader("Group: " + currentGroupInfo->name);
14170 currentGroupInfo.used = true;
14171 }
14172}
14173void ConsoleReporter::printTestCaseAndSectionHeader() {
14174 assert(!m_sectionStack.empty());
14175 printOpenHeader(currentTestCaseInfo->name);
14176
14177 if (m_sectionStack.size() > 1) {
14178 Colour colourGuard(Colour::Headers);
14179
14180 auto
14181 it = m_sectionStack.begin() + 1, // Skip first section (test case)
14182 itEnd = m_sectionStack.end();
14183 for (; it != itEnd; ++it)
14184 printHeaderString(it->name, 2);
14185 }
14186
14187 SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
14188
14189 if (!lineInfo.empty()) {
14190 stream << getLineOfChars<'-'>() << '\n';
14191 Colour colourGuard(Colour::FileName);
14192 stream << lineInfo << '\n';
14193 }
14194 stream << getLineOfChars<'.'>() << '\n' << std::endl;
14195}
14196
14197void ConsoleReporter::printClosedHeader(std::string const& _name) {
14198 printOpenHeader(_name);
14199 stream << getLineOfChars<'.'>() << '\n';
14200}
14201void ConsoleReporter::printOpenHeader(std::string const& _name) {
14202 stream << getLineOfChars<'-'>() << '\n';
14203 {
14204 Colour colourGuard(Colour::Headers);
14205 printHeaderString(_name);
14206 }
14207}
14208
14209// if string has a : in first line will set indent to follow it on
14210// subsequent lines
14211void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
14212 std::size_t i = _string.find(": ");
14213 if (i != std::string::npos)
14214 i += 2;
14215 else
14216 i = 0;
14217 stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
14218}
14219
14220struct SummaryColumn {
14221
14222 SummaryColumn( std::string _label, Colour::Code _colour )
14223 : label( std::move( _label ) ),
14224 colour( _colour ) {}
14225 SummaryColumn addRow( std::size_t count ) {
14226 ReusableStringStream rss;
14227 rss << count;
14228 std::string row = rss.str();
14229 for (auto& oldRow : rows) {
14230 while (oldRow.size() < row.size())
14231 oldRow = ' ' + oldRow;
14232 while (oldRow.size() > row.size())
14233 row = ' ' + row;
14234 }
14235 rows.push_back(row);
14236 return *this;
14237 }
14238
14239 std::string label;
14240 Colour::Code colour;
14242
14243};
14244
14245void ConsoleReporter::printTotals( Totals const& totals ) {
14246 if (totals.testCases.total() == 0) {
14247 stream << Colour(Colour::Warning) << "No tests ran\n";
14248 } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
14249 stream << Colour(Colour::ResultSuccess) << "All tests passed";
14250 stream << " ("
14251 << pluralise(totals.assertions.passed, "assertion") << " in "
14252 << pluralise(totals.testCases.passed, "test case") << ')'
14253 << '\n';
14254 } else {
14255
14257 columns.push_back(SummaryColumn("", Colour::None)
14258 .addRow(totals.testCases.total())
14259 .addRow(totals.assertions.total()));
14260 columns.push_back(SummaryColumn("passed", Colour::Success)
14261 .addRow(totals.testCases.passed)
14262 .addRow(totals.assertions.passed));
14263 columns.push_back(SummaryColumn("failed", Colour::ResultError)
14264 .addRow(totals.testCases.failed)
14265 .addRow(totals.assertions.failed));
14266 columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
14267 .addRow(totals.testCases.failedButOk)
14268 .addRow(totals.assertions.failedButOk));
14269
14270 printSummaryRow("test cases", columns, 0);
14271 printSummaryRow("assertions", columns, 1);
14272 }
14273}
14274void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
14275 for (auto col : cols) {
14276 std::string value = col.rows[row];
14277 if (col.label.empty()) {
14278 stream << label << ": ";
14279 if (value != "0")
14280 stream << value;
14281 else
14282 stream << Colour(Colour::Warning) << "- none -";
14283 } else if (value != "0") {
14284 stream << Colour(Colour::LightGrey) << " | ";
14285 stream << Colour(col.colour)
14286 << value << ' ' << col.label;
14287 }
14288 }
14289 stream << '\n';
14290}
14291
14292void ConsoleReporter::printTotalsDivider(Totals const& totals) {
14293 if (totals.testCases.total() > 0) {
14294 std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
14295 std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
14296 std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
14297 while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
14298 findMax(failedRatio, failedButOkRatio, passedRatio)++;
14299 while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
14300 findMax(failedRatio, failedButOkRatio, passedRatio)--;
14301
14302 stream << Colour(Colour::Error) << std::string(failedRatio, '=');
14303 stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
14304 if (totals.testCases.allPassed())
14305 stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
14306 else
14307 stream << Colour(Colour::Success) << std::string(passedRatio, '=');
14308 } else {
14309 stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
14310 }
14311 stream << '\n';
14312}
14313void ConsoleReporter::printSummaryDivider() {
14314 stream << getLineOfChars<'-'>() << '\n';
14315}
14316
14317void ConsoleReporter::printTestFilters() {
14318 if (m_config->testSpec().hasFilters())
14319 stream << Colour(Colour::BrightYellow) << "Filters: " << serializeFilters( m_config->getTestsOrTags() ) << '\n';
14320}
14321
14322CATCH_REGISTER_REPORTER("console", ConsoleReporter)
14323
14324} // end namespace Catch
14325
14326#if defined(_MSC_VER)
14327#pragma warning(pop)
14328#endif
14329// end catch_reporter_console.cpp
14330// start catch_reporter_junit.cpp
14331
14332#include <cassert>
14333#include <sstream>
14334#include <ctime>
14335#include <algorithm>
14336
14337namespace Catch {
14338
14339 namespace {
14340 std::string getCurrentTimestamp() {
14341 // Beware, this is not reentrant because of backward compatibility issues
14342 // Also, UTC only, again because of backward compatibility (%z is C++11)
14343 time_t rawtime;
14344 std::time(&rawtime);
14345 auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
14346
14347#ifdef _MSC_VER
14348 std::tm timeInfo = {};
14349 gmtime_s(&timeInfo, &rawtime);
14350#else
14351 std::tm* timeInfo;
14352 timeInfo = std::gmtime(&rawtime);
14353#endif
14354
14355 char timeStamp[timeStampSize];
14356 const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
14357
14358#ifdef _MSC_VER
14359 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
14360#else
14361 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
14362#endif
14363 return std::string(timeStamp);
14364 }
14365
14366 std::string fileNameTag(const std::vector<std::string> &tags) {
14367 auto it = std::find_if(begin(tags),
14368 end(tags),
14369 [] (std::string const& tag) {return tag.front() == '#'; });
14370 if (it != tags.end())
14371 return it->substr(1);
14372 return std::string();
14373 }
14374 } // anonymous namespace
14375
14376 JunitReporter::JunitReporter( ReporterConfig const& _config )
14377 : CumulativeReporterBase( _config ),
14378 xml( _config.stream() )
14379 {
14380 m_reporterPrefs.shouldRedirectStdOut = true;
14381 m_reporterPrefs.shouldReportAllAssertions = true;
14382 }
14383
14384 JunitReporter::~JunitReporter() {}
14385
14386 std::string JunitReporter::getDescription() {
14387 return "Reports test results in an XML format that looks like Ant's junitreport target";
14388 }
14389
14390 void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
14391
14392 void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
14393 CumulativeReporterBase::testRunStarting( runInfo );
14394 xml.startElement( "testsuites" );
14395 }
14396
14397 void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
14398 suiteTimer.start();
14399 stdOutForSuite.clear();
14400 stdErrForSuite.clear();
14401 unexpectedExceptions = 0;
14402 CumulativeReporterBase::testGroupStarting( groupInfo );
14403 }
14404
14405 void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
14406 m_okToFail = testCaseInfo.okToFail();
14407 }
14408
14409 bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
14410 if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
14411 unexpectedExceptions++;
14412 return CumulativeReporterBase::assertionEnded( assertionStats );
14413 }
14414
14415 void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
14416 stdOutForSuite += testCaseStats.stdOut;
14417 stdErrForSuite += testCaseStats.stdErr;
14418 CumulativeReporterBase::testCaseEnded( testCaseStats );
14419 }
14420
14421 void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
14422 double suiteTime = suiteTimer.getElapsedSeconds();
14423 CumulativeReporterBase::testGroupEnded( testGroupStats );
14424 writeGroup( *m_testGroups.back(), suiteTime );
14425 }
14426
14427 void JunitReporter::testRunEndedCumulative() {
14428 xml.endElement();
14429 }
14430
14431 void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
14432 XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
14433
14434 TestGroupStats const& stats = groupNode.value;
14435 xml.writeAttribute( "name", stats.groupInfo.name );
14436 xml.writeAttribute( "errors", unexpectedExceptions );
14437 xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
14438 xml.writeAttribute( "tests", stats.totals.assertions.total() );
14439 xml.writeAttribute( "hostname", "tbd" ); // !TBD
14440 if( m_config->showDurations() == ShowDurations::Never )
14441 xml.writeAttribute( "time", "" );
14442 else
14443 xml.writeAttribute( "time", suiteTime );
14444 xml.writeAttribute( "timestamp", getCurrentTimestamp() );
14445
14446 // Write properties if there are any
14447 if (m_config->hasTestFilters() || m_config->rngSeed() != 0) {
14448 auto properties = xml.scopedElement("properties");
14449 if (m_config->hasTestFilters()) {
14450 xml.scopedElement("property")
14451 .writeAttribute("name", "filters")
14452 .writeAttribute("value", serializeFilters(m_config->getTestsOrTags()));
14453 }
14454 if (m_config->rngSeed() != 0) {
14455 xml.scopedElement("property")
14456 .writeAttribute("name", "random-seed")
14457 .writeAttribute("value", m_config->rngSeed());
14458 }
14459 }
14460
14461 // Write test cases
14462 for( auto const& child : groupNode.children )
14463 writeTestCase( *child );
14464
14465 xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
14466 xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
14467 }
14468
14469 void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
14470 TestCaseStats const& stats = testCaseNode.value;
14471
14472 // All test cases have exactly one section - which represents the
14473 // test case itself. That section may have 0-n nested sections
14474 assert( testCaseNode.children.size() == 1 );
14475 SectionNode const& rootSection = *testCaseNode.children.front();
14476
14477 std::string className = stats.testInfo.className;
14478
14479 if( className.empty() ) {
14480 className = fileNameTag(stats.testInfo.tags);
14481 if ( className.empty() )
14482 className = "global";
14483 }
14484
14485 if ( !m_config->name().empty() )
14486 className = m_config->name() + "." + className;
14487
14488 writeSection( className, "", rootSection );
14489 }
14490
14491 void JunitReporter::writeSection( std::string const& className,
14492 std::string const& rootName,
14493 SectionNode const& sectionNode ) {
14494 std::string name = trim( sectionNode.stats.sectionInfo.name );
14495 if( !rootName.empty() )
14496 name = rootName + '/' + name;
14497
14498 if( !sectionNode.assertions.empty() ||
14499 !sectionNode.stdOut.empty() ||
14500 !sectionNode.stdErr.empty() ) {
14501 XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
14502 if( className.empty() ) {
14503 xml.writeAttribute( "classname", name );
14504 xml.writeAttribute( "name", "root" );
14505 }
14506 else {
14507 xml.writeAttribute( "classname", className );
14508 xml.writeAttribute( "name", name );
14509 }
14510 xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
14511
14512 writeAssertions( sectionNode );
14513
14514 if( !sectionNode.stdOut.empty() )
14515 xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
14516 if( !sectionNode.stdErr.empty() )
14517 xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
14518 }
14519 for( auto const& childNode : sectionNode.childSections )
14520 if( className.empty() )
14521 writeSection( name, "", *childNode );
14522 else
14523 writeSection( className, name, *childNode );
14524 }
14525
14526 void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
14527 for( auto const& assertion : sectionNode.assertions )
14528 writeAssertion( assertion );
14529 }
14530
14531 void JunitReporter::writeAssertion( AssertionStats const& stats ) {
14532 AssertionResult const& result = stats.assertionResult;
14533 if( !result.isOk() ) {
14534 std::string elementName;
14535 switch( result.getResultType() ) {
14538 elementName = "error";
14539 break;
14541 elementName = "failure";
14542 break;
14544 elementName = "failure";
14545 break;
14547 elementName = "failure";
14548 break;
14549
14550 // We should never see these here:
14551 case ResultWas::Info:
14552 case ResultWas::Warning:
14553 case ResultWas::Ok:
14554 case ResultWas::Unknown:
14557 elementName = "internalError";
14558 break;
14559 }
14560
14561 XmlWriter::ScopedElement e = xml.scopedElement( elementName );
14562
14563 xml.writeAttribute( "message", result.getExpandedExpression() );
14564 xml.writeAttribute( "type", result.getTestMacroName() );
14565
14566 ReusableStringStream rss;
14567 if( !result.getMessage().empty() )
14568 rss << result.getMessage() << '\n';
14569 for( auto const& msg : stats.infoMessages )
14570 if( msg.type == ResultWas::Info )
14571 rss << msg.message << '\n';
14572
14573 rss << "at " << result.getSourceInfo();
14574 xml.writeText( rss.str(), false );
14575 }
14576 }
14577
14578 CATCH_REGISTER_REPORTER( "junit", JunitReporter )
14579
14580} // end namespace Catch
14581// end catch_reporter_junit.cpp
14582// start catch_reporter_listening.cpp
14583
14584#include <cassert>
14585
14586namespace Catch {
14587
14588 ListeningReporter::ListeningReporter() {
14589 // We will assume that listeners will always want all assertions
14590 m_preferences.shouldReportAllAssertions = true;
14591 }
14592
14593 void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
14594 m_listeners.push_back( std::move( listener ) );
14595 }
14596
14597 void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
14598 assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
14599 m_reporter = std::move( reporter );
14600 m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
14601 }
14602
14603 ReporterPreferences ListeningReporter::getPreferences() const {
14604 return m_preferences;
14605 }
14606
14607 std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
14608 return std::set<Verbosity>{ };
14609 }
14610
14611 void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
14612 for ( auto const& listener : m_listeners ) {
14613 listener->noMatchingTestCases( spec );
14614 }
14615 m_reporter->noMatchingTestCases( spec );
14616 }
14617
14618 void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
14619 for ( auto const& listener : m_listeners ) {
14620 listener->benchmarkStarting( benchmarkInfo );
14621 }
14622 m_reporter->benchmarkStarting( benchmarkInfo );
14623 }
14624 void ListeningReporter::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
14625 for ( auto const& listener : m_listeners ) {
14626 listener->benchmarkEnded( benchmarkStats );
14627 }
14628 m_reporter->benchmarkEnded( benchmarkStats );
14629 }
14630
14631 void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
14632 for ( auto const& listener : m_listeners ) {
14633 listener->testRunStarting( testRunInfo );
14634 }
14635 m_reporter->testRunStarting( testRunInfo );
14636 }
14637
14638 void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
14639 for ( auto const& listener : m_listeners ) {
14640 listener->testGroupStarting( groupInfo );
14641 }
14642 m_reporter->testGroupStarting( groupInfo );
14643 }
14644
14645 void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
14646 for ( auto const& listener : m_listeners ) {
14647 listener->testCaseStarting( testInfo );
14648 }
14649 m_reporter->testCaseStarting( testInfo );
14650 }
14651
14652 void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
14653 for ( auto const& listener : m_listeners ) {
14654 listener->sectionStarting( sectionInfo );
14655 }
14656 m_reporter->sectionStarting( sectionInfo );
14657 }
14658
14659 void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
14660 for ( auto const& listener : m_listeners ) {
14661 listener->assertionStarting( assertionInfo );
14662 }
14663 m_reporter->assertionStarting( assertionInfo );
14664 }
14665
14666 // The return value indicates if the messages buffer should be cleared:
14667 bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
14668 for( auto const& listener : m_listeners ) {
14669 static_cast<void>( listener->assertionEnded( assertionStats ) );
14670 }
14671 return m_reporter->assertionEnded( assertionStats );
14672 }
14673
14674 void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
14675 for ( auto const& listener : m_listeners ) {
14676 listener->sectionEnded( sectionStats );
14677 }
14678 m_reporter->sectionEnded( sectionStats );
14679 }
14680
14681 void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
14682 for ( auto const& listener : m_listeners ) {
14683 listener->testCaseEnded( testCaseStats );
14684 }
14685 m_reporter->testCaseEnded( testCaseStats );
14686 }
14687
14688 void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
14689 for ( auto const& listener : m_listeners ) {
14690 listener->testGroupEnded( testGroupStats );
14691 }
14692 m_reporter->testGroupEnded( testGroupStats );
14693 }
14694
14695 void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
14696 for ( auto const& listener : m_listeners ) {
14697 listener->testRunEnded( testRunStats );
14698 }
14699 m_reporter->testRunEnded( testRunStats );
14700 }
14701
14702 void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
14703 for ( auto const& listener : m_listeners ) {
14704 listener->skipTest( testInfo );
14705 }
14706 m_reporter->skipTest( testInfo );
14707 }
14708
14709 bool ListeningReporter::isMulti() const {
14710 return true;
14711 }
14712
14713} // end namespace Catch
14714// end catch_reporter_listening.cpp
14715// start catch_reporter_xml.cpp
14716
14717#if defined(_MSC_VER)
14718#pragma warning(push)
14719#pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
14720 // Note that 4062 (not all labels are handled
14721 // and default is missing) is enabled
14722#endif
14723
14724namespace Catch {
14725 XmlReporter::XmlReporter( ReporterConfig const& _config )
14726 : StreamingReporterBase( _config ),
14727 m_xml(_config.stream())
14728 {
14729 m_reporterPrefs.shouldRedirectStdOut = true;
14730 m_reporterPrefs.shouldReportAllAssertions = true;
14731 }
14732
14733 XmlReporter::~XmlReporter() = default;
14734
14735 std::string XmlReporter::getDescription() {
14736 return "Reports test results as an XML document";
14737 }
14738
14739 std::string XmlReporter::getStylesheetRef() const {
14740 return std::string();
14741 }
14742
14743 void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
14744 m_xml
14745 .writeAttribute( "filename", sourceInfo.file )
14746 .writeAttribute( "line", sourceInfo.line );
14747 }
14748
14749 void XmlReporter::noMatchingTestCases( std::string const& s ) {
14750 StreamingReporterBase::noMatchingTestCases( s );
14751 }
14752
14753 void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
14754 StreamingReporterBase::testRunStarting( testInfo );
14755 std::string stylesheetRef = getStylesheetRef();
14756 if( !stylesheetRef.empty() )
14757 m_xml.writeStylesheetRef( stylesheetRef );
14758 m_xml.startElement( "Catch" );
14759 if( !m_config->name().empty() )
14760 m_xml.writeAttribute( "name", m_config->name() );
14761 if (m_config->testSpec().hasFilters())
14762 m_xml.writeAttribute( "filters", serializeFilters( m_config->getTestsOrTags() ) );
14763 if( m_config->rngSeed() != 0 )
14764 m_xml.scopedElement( "Randomness" )
14765 .writeAttribute( "seed", m_config->rngSeed() );
14766 }
14767
14768 void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
14769 StreamingReporterBase::testGroupStarting( groupInfo );
14770 m_xml.startElement( "Group" )
14771 .writeAttribute( "name", groupInfo.name );
14772 }
14773
14774 void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
14775 StreamingReporterBase::testCaseStarting(testInfo);
14776 m_xml.startElement( "TestCase" )
14777 .writeAttribute( "name", trim( testInfo.name ) )
14778 .writeAttribute( "description", testInfo.description )
14779 .writeAttribute( "tags", testInfo.tagsAsString() );
14780
14781 writeSourceInfo( testInfo.lineInfo );
14782
14783 if ( m_config->showDurations() == ShowDurations::Always )
14784 m_testCaseTimer.start();
14785 m_xml.ensureTagClosed();
14786 }
14787
14788 void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
14789 StreamingReporterBase::sectionStarting( sectionInfo );
14790 if( m_sectionDepth++ > 0 ) {
14791 m_xml.startElement( "Section" )
14792 .writeAttribute( "name", trim( sectionInfo.name ) );
14793 writeSourceInfo( sectionInfo.lineInfo );
14794 m_xml.ensureTagClosed();
14795 }
14796 }
14797
14798 void XmlReporter::assertionStarting( AssertionInfo const& ) { }
14799
14800 bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
14801
14802 AssertionResult const& result = assertionStats.assertionResult;
14803
14804 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
14805
14806 if( includeResults || result.getResultType() == ResultWas::Warning ) {
14807 // Print any info messages in <Info> tags.
14808 for( auto const& msg : assertionStats.infoMessages ) {
14809 if( msg.type == ResultWas::Info && includeResults ) {
14810 m_xml.scopedElement( "Info" )
14811 .writeText( msg.message );
14812 } else if ( msg.type == ResultWas::Warning ) {
14813 m_xml.scopedElement( "Warning" )
14814 .writeText( msg.message );
14815 }
14816 }
14817 }
14818
14819 // Drop out if result was successful but we're not printing them.
14820 if( !includeResults && result.getResultType() != ResultWas::Warning )
14821 return true;
14822
14823 // Print the expression if there is one.
14824 if( result.hasExpression() ) {
14825 m_xml.startElement( "Expression" )
14826 .writeAttribute( "success", result.succeeded() )
14827 .writeAttribute( "type", result.getTestMacroName() );
14828
14829 writeSourceInfo( result.getSourceInfo() );
14830
14831 m_xml.scopedElement( "Original" )
14832 .writeText( result.getExpression() );
14833 m_xml.scopedElement( "Expanded" )
14834 .writeText( result.getExpandedExpression() );
14835 }
14836
14837 // And... Print a result applicable to each result type.
14838 switch( result.getResultType() ) {
14840 m_xml.startElement( "Exception" );
14841 writeSourceInfo( result.getSourceInfo() );
14842 m_xml.writeText( result.getMessage() );
14843 m_xml.endElement();
14844 break;
14846 m_xml.startElement( "FatalErrorCondition" );
14847 writeSourceInfo( result.getSourceInfo() );
14848 m_xml.writeText( result.getMessage() );
14849 m_xml.endElement();
14850 break;
14851 case ResultWas::Info:
14852 m_xml.scopedElement( "Info" )
14853 .writeText( result.getMessage() );
14854 break;
14855 case ResultWas::Warning:
14856 // Warning will already have been written
14857 break;
14859 m_xml.startElement( "Failure" );
14860 writeSourceInfo( result.getSourceInfo() );
14861 m_xml.writeText( result.getMessage() );
14862 m_xml.endElement();
14863 break;
14864 default:
14865 break;
14866 }
14867
14868 if( result.hasExpression() )
14869 m_xml.endElement();
14870
14871 return true;
14872 }
14873
14874 void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
14875 StreamingReporterBase::sectionEnded( sectionStats );
14876 if( --m_sectionDepth > 0 ) {
14877 XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
14878 e.writeAttribute( "successes", sectionStats.assertions.passed );
14879 e.writeAttribute( "failures", sectionStats.assertions.failed );
14880 e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
14881
14882 if ( m_config->showDurations() == ShowDurations::Always )
14883 e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
14884
14885 m_xml.endElement();
14886 }
14887 }
14888
14889 void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
14890 StreamingReporterBase::testCaseEnded( testCaseStats );
14891 XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
14892 e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
14893
14894 if ( m_config->showDurations() == ShowDurations::Always )
14895 e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
14896
14897 if( !testCaseStats.stdOut.empty() )
14898 m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
14899 if( !testCaseStats.stdErr.empty() )
14900 m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
14901
14902 m_xml.endElement();
14903 }
14904
14905 void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
14906 StreamingReporterBase::testGroupEnded( testGroupStats );
14907 // TODO: Check testGroupStats.aborting and act accordingly.
14908 m_xml.scopedElement( "OverallResults" )
14909 .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
14910 .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
14911 .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
14912 m_xml.endElement();
14913 }
14914
14915 void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
14916 StreamingReporterBase::testRunEnded( testRunStats );
14917 m_xml.scopedElement( "OverallResults" )
14918 .writeAttribute( "successes", testRunStats.totals.assertions.passed )
14919 .writeAttribute( "failures", testRunStats.totals.assertions.failed )
14920 .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
14921 m_xml.endElement();
14922 }
14923
14924 CATCH_REGISTER_REPORTER( "xml", XmlReporter )
14925
14926} // end namespace Catch
14927
14928#if defined(_MSC_VER)
14929#pragma warning(pop)
14930#endif
14931// end catch_reporter_xml.cpp
14932
14933namespace Catch {
14934 LeakDetector leakDetector;
14935}
14936
14937#ifdef __clang__
14938#pragma clang diagnostic pop
14939#endif
14940
14941// end catch_impl.hpp
14942#endif
14943
14944#ifdef CATCH_CONFIG_MAIN
14945// start catch_default_main.hpp
14946
14947#ifndef __OBJC__
14948
14949#if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
14950// Standard C/C++ Win32 Unicode wmain entry point
14951extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
14952#else
14953// Standard C/C++ main entry point
14954int main (int argc, char * argv[]) {
14955#endif
14956
14957 return Catch::Session().run( argc, argv );
14958}
14959
14960#else // __OBJC__
14961
14962// Objective-C entry point
14963int main (int argc, char * const argv[]) {
14964#if !CATCH_ARC_ENABLED
14965 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
14966#endif
14967
14968 Catch::registerTestMethods();
14969 int result = Catch::Session().run( argc, (char**)argv );
14970
14971#if !CATCH_ARC_ENABLED
14972 [pool drain];
14973#endif
14974
14975 return result;
14976}
14977
14978#endif // __OBJC__
14979
14980// end catch_default_main.hpp
14981#endif
14982
14983#if !defined(CATCH_CONFIG_IMPL_ONLY)
14984
14985#ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
14986# undef CLARA_CONFIG_MAIN
14987#endif
14988
14989#if !defined(CATCH_CONFIG_DISABLE)
14990//////
14991// If this config identifier is defined then all CATCH macros are prefixed with CATCH_
14992#ifdef CATCH_CONFIG_PREFIX_ALL
14993
14994#define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
14995#define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
14996
14997#define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
14998#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
14999#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
15000#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
15001#define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
15002#endif// CATCH_CONFIG_DISABLE_MATCHERS
15003#define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
15004
15005#define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
15006#define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
15007#define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
15008#define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
15009#define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
15010
15011#define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
15012#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
15013#define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
15014#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
15015#define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
15016#endif // CATCH_CONFIG_DISABLE_MATCHERS
15017#define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
15018
15019#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
15020#define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
15021
15022#define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
15023#endif // CATCH_CONFIG_DISABLE_MATCHERS
15024
15025#define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
15026#define CATCH_UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "CATCH_UNSCOPED_INFO", msg )
15027#define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
15028#define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
15029
15030#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
15031#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
15032#define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
15033#define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
15034#define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
15035#define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
15036#define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
15037#define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
15038#define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
15039
15040#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
15041
15042#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
15043#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
15044#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
15045#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
15046#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
15047#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
15048#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
15049#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
15050#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
15051#else
15052#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
15053#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
15054#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
15055#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
15056#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
15057#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
15058#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
15059#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
15060#endif
15061
15062#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
15063#define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
15064#define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
15065#else
15066#define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
15067#define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
15068#endif
15069
15070// "BDD-style" convenience wrappers
15071#define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
15072#define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
15073#define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
15074#define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
15075#define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
15076#define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
15077#define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
15078#define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
15079
15080// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
15081#else
15082
15083#define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
15084#define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
15085
15086#define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
15087#define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
15088#define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
15089#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
15090#define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
15091#endif // CATCH_CONFIG_DISABLE_MATCHERS
15092#define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
15093
15094#define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
15095#define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
15096#define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
15097#define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
15098#define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
15099
15100#define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
15101#define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
15102#define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
15103#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
15104#define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
15105#endif // CATCH_CONFIG_DISABLE_MATCHERS
15106#define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
15107
15108#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
15109#define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
15110
15111#define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
15112#endif // CATCH_CONFIG_DISABLE_MATCHERS
15113
15114#define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
15115#define UNSCOPED_INFO( msg ) INTERNAL_CATCH_UNSCOPED_INFO( "UNSCOPED_INFO", msg )
15116#define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
15117#define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
15118
15119#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
15120#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
15121#define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
15122#define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
15123#define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
15124#define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
15125#define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
15126#define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
15127#define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
15128#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
15129
15130#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
15131#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
15132#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ )
15133#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
15134#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
15135#define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ )
15136#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ )
15137#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ )
15138#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ )
15139#else
15140#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ ) )
15141#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG( __VA_ARGS__ ) )
15142#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
15143#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
15144#define TEMPLATE_PRODUCT_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE( __VA_ARGS__ ) )
15145#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( __VA_ARGS__ ) )
15146#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, __VA_ARGS__ ) )
15147#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, __VA_ARGS__ ) )
15148#endif
15149
15150#if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
15151#define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
15152#define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
15153#else
15154#define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
15155#define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
15156#endif
15157
15158#endif
15159
15160#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
15161
15162// "BDD-style" convenience wrappers
15163#define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
15164#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
15165
15166#define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
15167#define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
15168#define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
15169#define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
15170#define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
15171#define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
15172
15174
15175#else // CATCH_CONFIG_DISABLE
15176
15177//////
15178// If this config identifier is defined then all CATCH macros are prefixed with CATCH_
15179#ifdef CATCH_CONFIG_PREFIX_ALL
15180
15181#define CATCH_REQUIRE( ... ) (void)(0)
15182#define CATCH_REQUIRE_FALSE( ... ) (void)(0)
15183
15184#define CATCH_REQUIRE_THROWS( ... ) (void)(0)
15185#define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
15186#define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
15187#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
15188#define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
15189#endif// CATCH_CONFIG_DISABLE_MATCHERS
15190#define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
15191
15192#define CATCH_CHECK( ... ) (void)(0)
15193#define CATCH_CHECK_FALSE( ... ) (void)(0)
15194#define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
15195#define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
15196#define CATCH_CHECK_NOFAIL( ... ) (void)(0)
15197
15198#define CATCH_CHECK_THROWS( ... ) (void)(0)
15199#define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
15200#define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
15201#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
15202#define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
15203#endif // CATCH_CONFIG_DISABLE_MATCHERS
15204#define CATCH_CHECK_NOTHROW( ... ) (void)(0)
15205
15206#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
15207#define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
15208
15209#define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
15210#endif // CATCH_CONFIG_DISABLE_MATCHERS
15211
15212#define CATCH_INFO( msg ) (void)(0)
15213#define CATCH_UNSCOPED_INFO( msg ) (void)(0)
15214#define CATCH_WARN( msg ) (void)(0)
15215#define CATCH_CAPTURE( msg ) (void)(0)
15216
15217#define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
15218#define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
15219#define CATCH_METHOD_AS_TEST_CASE( method, ... )
15220#define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
15221#define CATCH_SECTION( ... )
15222#define CATCH_DYNAMIC_SECTION( ... )
15223#define CATCH_FAIL( ... ) (void)(0)
15224#define CATCH_FAIL_CHECK( ... ) (void)(0)
15225#define CATCH_SUCCEED( ... ) (void)(0)
15226
15227#define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
15228
15229#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
15230#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
15231#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
15232#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
15233#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
15234#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
15235#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
15236#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
15237#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
15238#else
15239#define CATCH_TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
15240#define CATCH_TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
15241#define CATCH_TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
15242#define CATCH_TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
15243#define CATCH_TEMPLATE_PRODUCT_TEST_CASE( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
15244#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) CATCH_TEMPLATE_TEST_CASE( __VA_ARGS__ )
15245#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
15246#define CATCH_TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) CATCH_TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
15247#endif
15248
15249// "BDD-style" convenience wrappers
15250#define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
15251#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 )
15252#define CATCH_GIVEN( desc )
15253#define CATCH_AND_GIVEN( desc )
15254#define CATCH_WHEN( desc )
15255#define CATCH_AND_WHEN( desc )
15256#define CATCH_THEN( desc )
15257#define CATCH_AND_THEN( desc )
15258
15259#define CATCH_STATIC_REQUIRE( ... ) (void)(0)
15260#define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
15261
15262// If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
15263#else
15264
15265#define REQUIRE( ... ) (void)(0)
15266#define REQUIRE_FALSE( ... ) (void)(0)
15267
15268#define REQUIRE_THROWS( ... ) (void)(0)
15269#define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
15270#define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
15271#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
15272#define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
15273#endif // CATCH_CONFIG_DISABLE_MATCHERS
15274#define REQUIRE_NOTHROW( ... ) (void)(0)
15275
15276#define CHECK( ... ) (void)(0)
15277#define CHECK_FALSE( ... ) (void)(0)
15278#define CHECKED_IF( ... ) if (__VA_ARGS__)
15279#define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
15280#define CHECK_NOFAIL( ... ) (void)(0)
15281
15282#define CHECK_THROWS( ... ) (void)(0)
15283#define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
15284#define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
15285#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
15286#define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
15287#endif // CATCH_CONFIG_DISABLE_MATCHERS
15288#define CHECK_NOTHROW( ... ) (void)(0)
15289
15290#if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
15291#define CHECK_THAT( arg, matcher ) (void)(0)
15292
15293#define REQUIRE_THAT( arg, matcher ) (void)(0)
15294#endif // CATCH_CONFIG_DISABLE_MATCHERS
15295
15296#define INFO( msg ) (void)(0)
15297#define UNSCOPED_INFO( msg ) (void)(0)
15298#define WARN( msg ) (void)(0)
15299#define CAPTURE( msg ) (void)(0)
15300
15301#define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
15302#define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
15303#define METHOD_AS_TEST_CASE( method, ... )
15304#define REGISTER_TEST_CASE( Function, ... ) (void)(0)
15305#define SECTION( ... )
15306#define DYNAMIC_SECTION( ... )
15307#define FAIL( ... ) (void)(0)
15308#define FAIL_CHECK( ... ) (void)(0)
15309#define SUCCEED( ... ) (void)(0)
15310#define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
15311
15312#ifndef CATCH_CONFIG_TRADITIONAL_MSVC_PREPROCESSOR
15313#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__)
15314#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__)
15315#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__)
15316#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ )
15317#define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
15318#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
15319#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
15320#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
15321#else
15322#define TEMPLATE_TEST_CASE( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_NO_REGISTRATION(__VA_ARGS__) )
15323#define TEMPLATE_TEST_CASE_SIG( ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_SIG_NO_REGISTRATION(__VA_ARGS__) )
15324#define TEMPLATE_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_NO_REGISTRATION(className, __VA_ARGS__ ) )
15325#define TEMPLATE_TEST_CASE_METHOD_SIG( className, ... ) INTERNAL_CATCH_EXPAND_VARGS( INTERNAL_CATCH_TEMPLATE_TEST_CASE_METHOD_SIG_NO_REGISTRATION(className, __VA_ARGS__ ) )
15326#define TEMPLATE_PRODUCT_TEST_CASE( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
15327#define TEMPLATE_PRODUCT_TEST_CASE_SIG( ... ) TEMPLATE_TEST_CASE( __VA_ARGS__ )
15328#define TEMPLATE_PRODUCT_TEST_CASE_METHOD( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
15329#define TEMPLATE_PRODUCT_TEST_CASE_METHOD_SIG( className, ... ) TEMPLATE_TEST_CASE_METHOD( className, __VA_ARGS__ )
15330#endif
15331
15332#define STATIC_REQUIRE( ... ) (void)(0)
15333#define STATIC_REQUIRE_FALSE( ... ) (void)(0)
15334
15335#endif
15336
15337#define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
15338
15339// "BDD-style" convenience wrappers
15340#define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
15341#define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
15342
15343#define GIVEN( desc )
15344#define AND_GIVEN( desc )
15345#define WHEN( desc )
15346#define AND_WHEN( desc )
15347#define THEN( desc )
15348#define AND_THEN( desc )
15349
15351
15352#endif
15353
15354#endif // ! CATCH_CONFIG_IMPL_ONLY
15355
15356// start catch_reenable_warnings.h
15357
15358
15359#ifdef __clang__
15360# ifdef __ICC // icpc defines the __clang__ macro
15361# pragma warning(pop)
15362# else
15363# pragma clang diagnostic pop
15364# endif
15365#elif defined __GNUC__
15366# pragma GCC diagnostic pop
15367#endif
15368
15369// end catch_reenable_warnings.h
15370// end catch.hpp
15371#endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
15372
T abort(T... args)
T append(T... args)
int main(int argc, char *argv[])
T back(T... args)
T begin(T... args)
bool isnan(T)
T c_str(T... args)
#define CATCH_INTERNAL_ERROR(msg)
Definition catch.hpp:3698
#define CATCH_CATCH_ANON(type)
Definition catch.hpp:381
#define CATCH_RUNTIME_ERROR(msg)
Definition catch.hpp:3702
#define CATCH_ENFORCE(condition, msg)
Definition catch.hpp:3704
std::ostream & operator<<(std::ostream &, Catch_global_namespace_dummy)
#define CATCH_TRY
Definition catch.hpp:379
#define CATCH_INTERNAL_LINEINFO
Definition catch.hpp:468
#define CATCH_ERROR(msg)
Definition catch.hpp:3700
#define CATCH_CATCH_ALL
Definition catch.hpp:380
auto allowThrows() const -> bool
void handleExpr(ExprLhs< T > const &expr)
Definition catch.hpp:2396
AssertionHandler(StringRef const &macroName, SourceLineInfo const &lineInfo, StringRef capturedExpression, ResultDisposition::Flags resultDisposition)
void handleExceptionNotThrownAsExpected()
void handleUnexpectedExceptionNotThrown()
AssertionReaction m_reaction
Definition catch.hpp:2379
void handleUnexpectedInflightException()
void handleExceptionThrownAsExpected()
void handleMessage(ResultWas::OfType resultType, StringRef const &message)
AssertionInfo m_assertionInfo
Definition catch.hpp:2378
IResultCapture & m_resultCapture
Definition catch.hpp:2381
void handleExpr(ITransientExpression const &expr)
static auto getResolution() -> uint64_t
auto needsMoreIterations() -> bool
BenchmarkLooper(StringRef name)
Definition catch.hpp:2787
auto operator==(T) const -> BinaryExpr< LhsT, RhsT const & > const
Definition catch.hpp:2107
auto operator||(T) const -> BinaryExpr< LhsT, RhsT const & > const
Definition catch.hpp:2100
auto operator<=(T) const -> BinaryExpr< LhsT, RhsT const & > const
Definition catch.hpp:2142
BinaryExpr(bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs)
Definition catch.hpp:2085
auto operator>=(T) const -> BinaryExpr< LhsT, RhsT const & > const
Definition catch.hpp:2135
auto operator<(T) const -> BinaryExpr< LhsT, RhsT const & > const
Definition catch.hpp:2128
StringRef m_op
Definition catch.hpp:2076
auto operator>(T) const -> BinaryExpr< LhsT, RhsT const & > const
Definition catch.hpp:2121
auto operator!=(T) const -> BinaryExpr< LhsT, RhsT const & > const
Definition catch.hpp:2114
auto operator&&(T) const -> BinaryExpr< LhsT, RhsT const & > const
Definition catch.hpp:2093
void streamReconstructedExpression(std::ostream &os) const override
Definition catch.hpp:2079
void captureValue(size_t index, std::string const &value)
void captureValues(size_t index, T const &value)
Definition catch.hpp:2492
void captureValues(size_t index, T const &value, Ts const &... values)
Definition catch.hpp:2497
Capturer(StringRef macroName, SourceLineInfo const &lineInfo, ResultWas::OfType resultType, StringRef names)
std::vector< MessageInfo > m_messages
Definition catch.hpp:2482
Approx(double value)
Approx & epsilon(T const &newEpsilon)
Definition catch.hpp:3017
void setEpsilon(double epsilon)
Approx & margin(T const &newMargin)
Definition catch.hpp:3024
Approx & scale(T const &newScale)
Definition catch.hpp:3031
std::string toString() const
Approx operator-() const
static Approx custom()
Approx(T const &value)
Definition catch.hpp:2972
Approx operator()(T const &value)
Definition catch.hpp:2963
bool equalityComparisonImpl(double other) const
void setMargin(double margin)
static auto test(...) -> std::false_type
static auto test(int) -> decltype(std::declval< SS & >()<< std::declval< TT >(), std::true_type())
std::string translate(ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd) const override
Definition catch.hpp:2902
ExceptionTranslator(std::string(*translateFunction)(T &))
Definition catch.hpp:2898
ExceptionTranslatorRegistrar(std::string(*translateFunction)(T &))
Definition catch.hpp:2920
auto operator!=(RhsT const &rhs) -> BinaryExpr< LhsT, RhsT const & > const
Definition catch.hpp:2202
auto operator>=(RhsT const &rhs) -> BinaryExpr< LhsT, RhsT const & > const
Definition catch.hpp:2218
auto operator>(RhsT const &rhs) -> BinaryExpr< LhsT, RhsT const & > const
Definition catch.hpp:2210
auto operator<=(RhsT const &rhs) -> BinaryExpr< LhsT, RhsT const & > const
Definition catch.hpp:2222
auto makeUnaryExpr() const -> UnaryExpr< LhsT >
Definition catch.hpp:2240
ExprLhs(LhsT lhs)
Definition catch.hpp:2191
auto operator&&(RhsT const &) -> BinaryExpr< LhsT, RhsT const & > const
Definition catch.hpp:2227
auto operator||(RhsT const &) -> BinaryExpr< LhsT, RhsT const & > const
Definition catch.hpp:2234
auto operator==(RhsT const &rhs) -> BinaryExpr< LhsT, RhsT const & > const
Definition catch.hpp:2194
auto operator<(RhsT const &rhs) -> BinaryExpr< LhsT, RhsT const & > const
Definition catch.hpp:2214
GeneratorException(const char *msg)
Definition catch.hpp:3721
const char *const m_msg
Definition catch.hpp:3718
const char * what() const noexcept override final
ChunkGenerator(size_t size, GeneratorWrapper< T > generator)
Definition catch.hpp:4096
GeneratorWrapper< T > m_generator
Definition catch.hpp:4093
std::vector< T > const & get() const override
Definition catch.hpp:4108
GeneratorWrapper< T > m_generator
Definition catch.hpp:3947
T const & get() const override
Definition catch.hpp:3965
FilterGenerator(P &&pred, GeneratorWrapper< T > &&generator)
Definition catch.hpp:3951
FixedValuesGenerator(std::initializer_list< T > values)
Definition catch.hpp:3770
T const & get() const override
Definition catch.hpp:3772
std::unique_ptr< IGenerator< T > > m_generator
Definition catch.hpp:3783
GeneratorWrapper(std::unique_ptr< IGenerator< T > > generator)
Definition catch.hpp:3785
Generators(Gs... moreGenerators)
Definition catch.hpp:3828
void populate(U &&valueOrGenerator, Gs... moreGenerators)
Definition catch.hpp:3821
std::vector< GeneratorWrapper< T > > m_generators
Definition catch.hpp:3807
void populate(GeneratorWrapper< T > &&generator)
Definition catch.hpp:3810
T const & get() const override
Definition catch.hpp:3833
MapGenerator(F2 &&function, GeneratorWrapper< U > &&generator)
Definition catch.hpp:4046
GeneratorWrapper< U > m_generator
Definition catch.hpp:4040
T const & get() const override
Definition catch.hpp:4052
Float const & get() const override
Definition catch.hpp:4281
std::uniform_real_distribution< Float > m_dist
Definition catch.hpp:4271
std::uniform_int_distribution< Integer > m_dist
Definition catch.hpp:4293
RandomIntegerGenerator(Integer a, Integer b)
Definition catch.hpp:4297
Integer const & get() const override
Definition catch.hpp:4303
T const & get() const override
Definition catch.hpp:4355
RangeGenerator(T const &start, T const &end, T const &step)
Definition catch.hpp:4340
RangeGenerator(T const &start, T const &end)
Definition catch.hpp:4351
T const & get() const override
Definition catch.hpp:3999
RepeatGenerator(size_t repeats, GeneratorWrapper< T > &&generator)
Definition catch.hpp:3992
GeneratorWrapper< T > m_generator
Definition catch.hpp:3986
T const & get() const override
Definition catch.hpp:3757
GeneratorWrapper< T > m_generator
Definition catch.hpp:3911
T const & get() const override
Definition catch.hpp:3921
TakeGenerator(size_t target, GeneratorWrapper< T > &&generator)
Definition catch.hpp:3915
LazyExpression & operator=(LazyExpression const &)=delete
LazyExpression(bool isNegated)
ITransientExpression const * m_transientExpression
Definition catch.hpp:2360
friend struct AssertionStats
Definition catch.hpp:2357
friend auto operator<<(std::ostream &os, LazyExpression const &lazyExpr) -> std::ostream &
LazyExpression(LazyExpression const &other)
friend class RunContext
Definition catch.hpp:2358
StringRef m_matcherString
Definition catch.hpp:3583
MatcherT m_matcher
Definition catch.hpp:3582
void streamReconstructedExpression(std::ostream &os) const override
Definition catch.hpp:3592
MatchExpr(ArgT const &arg, MatcherT const &matcher, StringRef const &matcherString)
Definition catch.hpp:3585
ArgT const & m_arg
Definition catch.hpp:3581
bool match(T const &item) const override
Definition catch.hpp:3313
PredicateMatcher(std::function< bool(T const &)> const &elem, std::string const &descr)
Definition catch.hpp:3308
std::function< bool(T const &)> m_predicate
Definition catch.hpp:3304
std::string describe() const override
Definition catch.hpp:3317
virtual std::string describe() const =0
MatcherUntypedBase(MatcherUntypedBase const &)=default
NonCopyable(NonCopyable &&)=delete
NonCopyable(NonCopyable const &)=delete
virtual ~NonCopyable()
NonCopyable & operator=(NonCopyable const &)=delete
auto str() const -> std::string
auto get() -> std::ostream &
Definition catch.hpp:1318
ScopedMessage(MessageBuilder const &builder)
ScopedMessage(ScopedMessage &duplicate)=delete
ScopedMessage(ScopedMessage &&old)
MessageInfo m_info
Definition catch.hpp:2477
bool m_sectionIncluded
Definition catch.hpp:2752
SectionInfo m_info
Definition catch.hpp:2748
std::string m_name
Definition catch.hpp:2750
Section(SectionInfo const &info)
Counts m_assertions
Definition catch.hpp:2751
A non-owning string class (similar to the forthcoming std::string_view) Note that,...
Definition catch.hpp:532
char const * m_start
Definition catch.hpp:539
std::size_t size_type
Definition catch.hpp:534
auto operator=(StringRef const &other) noexcept -> StringRef &
Definition catch.hpp:582
auto c_str() const -> char const *
auto substr(size_type start, size_type size) const noexcept -> StringRef
StringRef(StringRef const &other) noexcept
Definition catch.hpp:553
StringRef(char const *rawChars, size_type size) noexcept
Definition catch.hpp:568
~StringRef() noexcept
Definition catch.hpp:578
static constexpr char const *const s_empty
Definition catch.hpp:546
StringRef(StringRef &&other) noexcept
Definition catch.hpp:558
friend struct StringRefTestAccess
Definition catch.hpp:537
auto operator[](size_type index) const noexcept -> char
auto numberOfCharacters() const noexcept -> size_type
StringRef(std::string const &stdString) noexcept
Definition catch.hpp:573
void swap(StringRef &other) noexcept
auto isOwned() const noexcept -> bool
size_type m_size
Definition catch.hpp:540
StringRef() noexcept
Definition catch.hpp:549
auto operator!=(StringRef const &other) const noexcept -> bool
auto operator==(StringRef const &other) const noexcept -> bool
auto empty() const noexcept -> bool
Definition catch.hpp:601
auto isSubstring() const noexcept -> bool
auto size() const noexcept -> size_type
Definition catch.hpp:604
StringRef(char const *rawChars) noexcept
auto currentData() const noexcept -> char const *
bool operator<(TestCase const &other) const
TestCase withName(std::string const &_newName) const
void invoke() const
bool operator==(TestCase const &other) const
std::shared_ptr< ITestInvoker > test
Definition catch.hpp:4449
TestCaseInfo const & getTestCaseInfo() const
TestCase(ITestInvoker *testCase, TestCaseInfo &&info)
TestInvokerAsMethod(void(C::*testAsMethod)()) noexcept
Definition catch.hpp:900
void(C::* m_testAsMethod)()
Definition catch.hpp:898
void invoke() const override
Definition catch.hpp:902
auto getElapsedSeconds() const -> double
auto getElapsedNanoseconds() const -> uint64_t
void streamReconstructedExpression(std::ostream &os) const override
Definition catch.hpp:2153
UnaryExpr(LhsT lhs)
Definition catch.hpp:2158
Definition core.h:749
Definition core.h:1120
T clear(T... args)
void print(std::FILE *f, const text_style &ts, const S &format_str, const Args &... args)
Definition color.h:538
FMT_CONSTEXPR text_style operator|(emphasis lhs, emphasis rhs) FMT_NOEXCEPT
Definition color.h:367
T compare(T... args)
T copy(T... args)
FMT_CONSTEXPR auto find(Ptr first, Ptr last, T value, Ptr &out) -> bool
Definition core.h:2078
auto arg(const Char *name, const T &arg) -> detail::named_arg< Char, T >
Definition core.h:1725
constexpr auto count() -> size_t
Definition core.h:1039
type
Definition core.h:1048
T
Definition core.h:320
T current_exception(T... args)
T distance(T... args)
T emplace_back(T... args)
T empty(T... args)
T end(T... args)
T endl(T... args)
T equal(T... args)
T erase(T... args)
T fabs(T... args)
T fail(T... args)
T fclose(T... args)
T fflush(T... args)
T fgets(T... args)
T find_first_not_of(T... args)
T find_if(T... args)
T find_last_not_of(T... args)
T find_last_of(T... args)
T fixed(T... args)
T flags(T... args)
T flush(T... args)
auto to_string(const T &value) -> std::string
Definition format.h:2600
T sprintf(T... args)
T free(T... args)
T front(T... args)
T get(T... args)
T getchar(T... args)
T getline(T... args)
T gmtime(T... args)
T hex(T... args)
T insert(T... args)
T invoke(T... args)
T is_permutation(T... args)
T isnan(T... args)
T left(T... args)
T make_pair(T... args)
T make_shared(T... args)
T malloc(T... args)
T max(T... args)
T memcpy(T... args)
T memset(T... args)
T min(T... args)
std::string convertUnknownEnumToString(E e)
Definition catch.hpp:1512
const std::string unprintableString
std::string rangeToString(InputIterator first, InputIterator last)
Definition catch.hpp:1686
std::enable_if<!std::is_enum< T >::value &&!std::is_base_of< std::exception, T >::value, std::string >::type convertUnstreamable(T const &)
Definition catch.hpp:1445
std::string rawMemoryToString(const void *object, std::size_t size)
std::string stringify(const T &e)
Definition catch.hpp:1507
std::enable_if< std::is_integral< T >::value &&!std::is_same< T, bool >::value, GeneratorWrapper< T > >::type random(T a, T b)
Definition catch.hpp:4317
std::unique_ptr< GeneratorUntypedBase > GeneratorBasePtr
Definition catch.hpp:3665
auto acquireGeneratorTracker(SourceLineInfo const &lineInfo) -> IGeneratorTracker &
GeneratorWrapper< T > filter(Predicate &&pred, GeneratorWrapper< T > &&generator)
Definition catch.hpp:3980
GeneratorWrapper< T > repeat(size_t repeats, GeneratorWrapper< T > &&generator)
Definition catch.hpp:4033
GeneratorWrapper< T > range(T const &start, T const &end, T const &step)
Definition catch.hpp:4366
typename std::remove_reference< typename std::remove_cv< typename std::result_of< Func(U)>::type >::type >::type MapFunctionReturnType
Definition catch.hpp:4072
GeneratorWrapper< std::vector< T > > chunk(size_t size, GeneratorWrapper< T > &&generator)
Definition catch.hpp:4124
auto makeGenerators(GeneratorWrapper< T > &&generator, Gs... moreGenerators) -> Generators< T >
Definition catch.hpp:3859
GeneratorWrapper< T > take(size_t target, GeneratorWrapper< T > &&generator)
Definition catch.hpp:3941
GeneratorWrapper< std::tuple< Ts... > > table(std::initializer_list< std::tuple< typename std::decay< Ts >::type... > > tuples)
Definition catch.hpp:3850
GeneratorWrapper< T > map(Func &&function, GeneratorWrapper< U > &&generator)
Definition catch.hpp:4076
GeneratorWrapper< T > values(std::initializer_list< T > values)
Definition catch.hpp:3801
std::string finalizeDescription(const std::string &desc)
StdString::ContainsMatcher Contains(std::string const &str, CaseSensitive::Choice caseSensitivity=CaseSensitive::Yes)
Floating::WithinAbsMatcher WithinAbs(double target, double margin)
Generic::PredicateMatcher< T > Predicate(std::function< bool(T const &)> const &predicate, std::string const &description="")
Definition catch.hpp:3329
StdString::RegexMatcher Matches(std::string const &regex, CaseSensitive::Choice caseSensitivity=CaseSensitive::Yes)
Vector::ContainsElementMatcher< T > VectorContains(T const &comparator)
Definition catch.hpp:3554
StdString::StartsWithMatcher StartsWith(std::string const &str, CaseSensitive::Choice caseSensitivity=CaseSensitive::Yes)
Vector::UnorderedEqualsMatcher< T > UnorderedEquals(std::vector< T > const &target)
Definition catch.hpp:3569
StdString::EndsWithMatcher EndsWith(std::string const &str, CaseSensitive::Choice caseSensitivity=CaseSensitive::Yes)
Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff)
StdString::EqualsMatcher Equals(std::string const &str, CaseSensitive::Choice caseSensitivity=CaseSensitive::Yes)
std::ostream & cout()
T const & operator+(T const &value, StreamEndStop)
Definition catch.hpp:463
void toLowerInPlace(std::string &s)
std::string trim(std::string const &str)
void cleanUp()
std::vector< TestCase > filterTests(std::vector< TestCase > const &testCases, TestSpec const &testSpec, IConfig const &config)
std::ostream & clog()
IContext & getCurrentContext()
Definition catch.hpp:4179
auto makeMatchExpr(ArgT const &arg, MatcherT const &matcher, StringRef const &matcherString) -> MatchExpr< ArgT, MatcherT >
Definition catch.hpp:3607
void throw_exception(std::exception const &e)
void formatReconstructedExpression(std::ostream &os, std::string const &lhs, StringRef op, std::string const &rhs)
bool isOk(ResultWas::OfType resultType)
bool isJustInfo(int flags)
std::ostream & cerr()
IMutableRegistryHub & getMutableRegistryHub()
IRegistryHub const & getRegistryHub()
TestCase makeTestCase(ITestInvoker *testCase, std::string const &className, NameAndTags const &nameAndTags, SourceLineInfo const &lineInfo)
auto operator+=(std::string &lhs, StringRef const &sr) -> std::string &
void handleExpression(ITransientExpression const &expr)
std::vector< StringRef > splitStringRef(StringRef str, char delimiter)
bool startsWith(std::string const &s, std::string const &prefix)
IMutableContext & getCurrentMutableContext()
Definition catch.hpp:4172
not_this_one end(...)
bool shouldContinueOnFailure(int flags)
auto compareNotEqual(LhsT const &lhs, RhsT &&rhs) -> bool
Definition catch.hpp:2177
std::ostream & operator<<(std::ostream &os, SourceLineInfo const &info)
bool isFalseTest(int flags)
Definition catch.hpp:1252
std::vector< TestCase > const & getAllTestCasesSorted(IConfig const &config)
auto getCurrentNanosecondsSinceEpoch() -> uint64_t
bool contains(std::string const &s, std::string const &infix)
bool matchTest(TestCase const &testCase, TestSpec const &testSpec, IConfig const &config)
ResultDisposition::Flags operator|(ResultDisposition::Flags lhs, ResultDisposition::Flags rhs)
auto makeTestInvoker(void(*testAsFunction)()) noexcept -> ITestInvoker *
bool shouldSuppressFailure(int flags)
Matchers::Impl::MatcherBase< std::string > StringMatcher
Definition catch.hpp:3602
std::string toLower(std::string const &s)
not_this_one begin(...)
auto getEstimatedClockResolution() -> uint64_t
unsigned int rngSeed()
std::shared_ptr< IReporterFactory > IReporterFactoryPtr
Definition catch.hpp:2835
bool endsWith(std::string const &s, std::string const &suffix)
std::string translateActiveException()
void cleanUpContext()
std::string(*)() exceptionTranslateFunction
Definition catch.hpp:2877
void handleExceptionMatchExpr(AssertionHandler &handler, std::string const &str, StringRef const &matcherString)
std::string rangeToString(Range const &range)
Definition catch.hpp:1868
auto makeStream(StringRef const &filename) -> IStream const *
IResultCapture & getResultCapture()
Verbosity
Definition catch.hpp:4197
auto compareEqual(LhsT const &lhs, RhsT const &rhs) -> bool
Definition catch.hpp:2166
std::shared_ptr< IConfig const > IConfigPtr
Definition catch.hpp:4147
bool replaceInPlace(std::string &str, std::string const &replaceThis, std::string const &withThis)
@ left
Definition core.h:1859
@ right
Definition core.h:1859
Definition args.h:19
null gmtime_s(...)
remove_cvref_t< decltype(*detail::range_begin(std::declval< Range >()))> value_type
Definition ranges.h:246
fp operator*(fp x, fp y)
Definition format-inl.h:275
const T & first(const T &value, const Tail &...)
bool operator==(fp x, fp y)
Definition format-inl.h:255
SPDLOG_INLINE bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode)
Definition os-inl.h:123
SPDLOG_INLINE std::shared_ptr< logger > get(const std::string &name)
Definition spdlog-inl.h:20
std::shared_ptr< spdlog::logger > create(std::string logger_name, SinkArgs &&...sink_args)
Definition spdlog.h:34
T next(T... args)
T open(T... args)
T has_value(T... args)
T pop_back(T... args)
T pop(T... args)
T prev(T... args)
T push_back(T... args)
T push(T... args)
T raise(T... args)
T shuffle(T... args)
T rbegin(T... args)
T ref(T... args)
T regex_match(T... args)
T rend(T... args)
T reserve(T... args)
T resize(T... args)
T rethrow_exception(T... args)
T rewind(T... args)
T rfind(T... args)
T setfill(T... args)
T setprecision(T... args)
T setw(T... args)
T size(T... args)
T sort(T... args)
T srand(T... args)
T str(T... args)
T strcmp(T... args)
T strftime(T... args)
T strlen(T... args)
T strncmp(T... args)
SourceLineInfo lineInfo
Definition catch.hpp:1263
ResultDisposition::Flags resultDisposition
Definition catch.hpp:1265
StringRef macroName
Definition catch.hpp:1262
StringRef capturedExpression
Definition catch.hpp:1264
AutoReg(ITestInvoker *invoker, SourceLineInfo const &lineInfo, StringRef const &classOrMethod, NameAndTags const &nameAndTags) noexcept
Counts & operator+=(Counts const &other)
std::size_t failed
Definition catch.hpp:2666
bool allOk() const
bool allPassed() const
std::size_t total() const
Counts operator-(Counts const &other) const
std::size_t failedButOk
Definition catch.hpp:2667
std::size_t passed
Definition catch.hpp:2665
auto operator<=(T const &lhs) -> ExprLhs< T const & >
Definition catch.hpp:2254
std::vector< std::pair< int, std::string > > m_values
Definition catch.hpp:1332
StringRef lookup(int value) const
virtual T const & get() const =0
virtual ~IGenerator()=default
virtual RunTests::InWhatOrder runOrder() const =0
virtual bool includeSuccessfulResults() const =0
virtual bool warnAboutNoTests() const =0
virtual int abortAfter() const =0
virtual std::vector< std::string > const & getTestsOrTags() const =0
virtual bool hasTestFilters() const =0
virtual std::ostream & stream() const =0
virtual Verbosity verbosity() const =0
virtual bool shouldDebugBreak() const =0
virtual TestSpec const & testSpec() const =0
virtual bool warnAboutMissingAssertions() const =0
virtual int benchmarkResolutionMultiple() const =0
virtual UseColour::YesOrNo useColour() const =0
virtual std::string name() const =0
virtual bool showInvisibles() const =0
virtual bool allowThrows() const =0
virtual ShowDurations::OrNot showDurations() const =0
virtual ~IConfig()
virtual unsigned int rngSeed() const =0
virtual std::vector< std::string > const & getSectionsToRun() const =0
virtual IResultCapture * getResultCapture()=0
virtual IRunner * getRunner()=0
virtual IConfigPtr const & getConfig() const =0
virtual ~IContext()
virtual std::string translateActiveException() const =0
virtual std::string translate(ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd) const =0
virtual auto getGenerator() const -> Generators::GeneratorBasePtr const &=0
virtual void setGenerator(Generators::GeneratorBasePtr &&generator)=0
virtual auto hasGenerator() const -> bool=0
static void createContext()
virtual void setResultCapture(IResultCapture *resultCapture)=0
virtual void setConfig(IConfigPtr const &config)=0
friend void cleanUpContext()
static IMutableContext * currentContext
Definition catch.hpp:4166
virtual void setRunner(IRunner *runner)=0
virtual Detail::EnumInfo const & registerEnum(StringRef enumName, StringRef allEnums, std::vector< int > const &values)=0
Detail::EnumInfo const & registerEnum(StringRef enumName, StringRef allEnums, std::initializer_list< E > values)
Definition catch.hpp:1346
virtual void registerTest(TestCase const &testInfo)=0
virtual void registerReporter(std::string const &name, IReporterFactoryPtr const &factory)=0
virtual void registerStartupException() noexcept=0
virtual void registerListener(IReporterFactoryPtr const &factory)=0
virtual void registerTagAlias(std::string const &alias, std::string const &tag, SourceLineInfo const &lineInfo)=0
virtual void registerTranslator(const IExceptionTranslator *translator)=0
virtual ~IRegistryHub()
virtual ITestCaseRegistry const & getTestCaseRegistry() const =0
virtual ITagAliasRegistry const & getTagAliasRegistry() const =0
virtual StartupExceptionRegistry const & getStartupExceptionRegistry() const =0
virtual IExceptionTranslatorRegistry const & getExceptionTranslatorRegistry() const =0
virtual IReporterRegistry const & getReporterRegistry() const =0
virtual void handleMessage(AssertionInfo const &info, ResultWas::OfType resultType, StringRef const &message, AssertionReaction &reaction)=0
virtual void benchmarkStarting(BenchmarkInfo const &info)=0
virtual const AssertionResult * getLastResult() const =0
virtual void popScopedMessage(MessageInfo const &message)=0
virtual void handleFatalErrorCondition(StringRef message)=0
virtual void emplaceUnscopedMessage(MessageBuilder const &builder)=0
virtual void sectionEnded(SectionEndInfo const &endInfo)=0
virtual void handleExpr(AssertionInfo const &info, ITransientExpression const &expr, AssertionReaction &reaction)=0
virtual bool sectionStarted(SectionInfo const &sectionInfo, Counts &assertions)=0
virtual void handleUnexpectedExceptionNotThrown(AssertionInfo const &info, AssertionReaction &reaction)=0
virtual void benchmarkEnded(BenchmarkStats const &stats)=0
virtual void handleIncomplete(AssertionInfo const &info)=0
virtual void pushScopedMessage(MessageInfo const &message)=0
virtual bool lastAssertionPassed()=0
virtual void assertionPassed()=0
virtual auto acquireGeneratorTracker(SourceLineInfo const &lineInfo) -> IGeneratorTracker &=0
virtual void handleNonExpr(AssertionInfo const &info, ResultWas::OfType resultType, AssertionReaction &reaction)=0
virtual void exceptionEarlyReported()=0
virtual std::string getCurrentTestName() const =0
virtual void handleUnexpectedInflightException(AssertionInfo const &info, std::string const &message, AssertionReaction &reaction)=0
virtual void sectionEndedEarly(SectionEndInfo const &endInfo)=0
virtual bool aborting() const =0
virtual ~IRunner()
virtual ~IStream()
virtual std::ostream & stream() const =0
virtual std::vector< TestCase > const & getAllTestsSorted(IConfig const &config) const =0
virtual std::vector< TestCase > const & getAllTests() const =0
virtual ~ITestInvoker()
virtual void invoke() const =0
auto getResult() const -> bool
Definition catch.hpp:2054
auto isBinaryExpression() const -> bool
Definition catch.hpp:2053
virtual void streamReconstructedExpression(std::ostream &os) const =0
ITransientExpression(bool isBinaryExpression, bool result)
Definition catch.hpp:2057
std::string describe() const override
WithinAbsMatcher(double target, double margin)
bool match(double const &matchee) const override
WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
bool match(double const &matchee) const override
std::string describe() const override
std::vector< MatcherBase< ArgT > const * > m_matchers
Definition catch.hpp:3172
std::string describe() const override
Definition catch.hpp:3151
bool match(ArgT const &arg) const override
Definition catch.hpp:3144
std::vector< MatcherBase< ArgT > const * > m_matchers
Definition catch.hpp:3205
std::string describe() const override
Definition catch.hpp:3184
bool match(ArgT const &arg) const override
Definition catch.hpp:3177
bool match(ArgT const &arg) const override
Definition catch.hpp:3213
MatchNotOf(MatcherBase< ArgT > const &underlyingMatcher)
Definition catch.hpp:3211
std::string describe() const override
Definition catch.hpp:3217
MatcherBase< ArgT > const & m_underlyingMatcher
Definition catch.hpp:3220
virtual bool match(ObjectT const &arg) const =0
std::string adjustString(std::string const &str) const
CasedString(std::string const &str, CaseSensitive::Choice caseSensitivity)
CaseSensitive::Choice m_caseSensitivity
Definition catch.hpp:3352
bool match(std::string const &source) const override
ContainsMatcher(CasedString const &comparator)
EndsWithMatcher(CasedString const &comparator)
bool match(std::string const &source) const override
bool match(std::string const &source) const override
EqualsMatcher(CasedString const &comparator)
std::string describe() const override
bool match(std::string const &matchee) const override
RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity)
CaseSensitive::Choice m_caseSensitivity
Definition catch.hpp:3388
StartsWithMatcher(CasedString const &comparator)
bool match(std::string const &source) const override
StringMatcherBase(std::string const &operation, CasedString const &comparator)
std::string describe() const override
std::vector< T > const & m_comparator
Definition catch.hpp:3520
std::string describe() const override
Definition catch.hpp:3501
ApproxMatcher & epsilon(T const &newEpsilon)
Definition catch.hpp:3505
ApproxMatcher & margin(T const &newMargin)
Definition catch.hpp:3510
ApproxMatcher(std::vector< T > const &comparator)
Definition catch.hpp:3491
ApproxMatcher & scale(T const &newScale)
Definition catch.hpp:3515
bool match(std::vector< T > const &v) const override
Definition catch.hpp:3493
bool match(std::vector< T > const &v) const override
Definition catch.hpp:3419
std::string describe() const override
Definition catch.hpp:3428
std::vector< T > const & m_comparator
Definition catch.hpp:3462
std::string describe() const override
Definition catch.hpp:3458
ContainsMatcher(std::vector< T > const &comparator)
Definition catch.hpp:3438
bool match(std::vector< T > const &v) const override
Definition catch.hpp:3440
bool match(std::vector< T > const &v) const override
Definition catch.hpp:3470
std::string describe() const override
Definition catch.hpp:3482
EqualsMatcher(std::vector< T > const &comparator)
Definition catch.hpp:3468
std::vector< T > const & m_comparator
Definition catch.hpp:3485
bool match(std::vector< T > const &vec) const override
Definition catch.hpp:3527
UnorderedEqualsMatcher(std::vector< T > const &target)
Definition catch.hpp:3526
std::string describe() const override
Definition catch.hpp:3536
MessageInfo m_info
Definition catch.hpp:2467
MessageBuilder(StringRef const &macroName, SourceLineInfo const &lineInfo, ResultWas::OfType type)
static unsigned int globalCount
Definition catch.hpp:2442
StringRef macroName
Definition catch.hpp:2433
unsigned int sequence
Definition catch.hpp:2437
bool operator<(MessageInfo const &other) const
SourceLineInfo lineInfo
Definition catch.hpp:2435
std::string message
Definition catch.hpp:2434
ResultWas::OfType type
Definition catch.hpp:2436
bool operator==(MessageInfo const &other) const
MessageInfo(StringRef const &_macroName, SourceLineInfo const &_lineInfo, ResultWas::OfType _type)
ReusableStringStream m_stream
Definition catch.hpp:2453
StringRef tags
Definition catch.hpp:918
StringRef name
Definition catch.hpp:917
NameAndTags(StringRef const &name_=StringRef(), StringRef const &tags_=StringRef()) noexcept
RegistrarForTagAliases(char const *alias, char const *tag, SourceLineInfo const &lineInfo)
SectionInfo sectionInfo
Definition catch.hpp:2705
std::string description
Definition catch.hpp:2700
SectionInfo(SourceLineInfo const &_lineInfo, std::string const &_name, std::string const &)
Definition catch.hpp:2695
SectionInfo(SourceLineInfo const &_lineInfo, std::string const &_name)
std::string name
Definition catch.hpp:2699
SourceLineInfo lineInfo
Definition catch.hpp:2701
bool empty() const noexcept
SourceLineInfo(char const *_file, std::size_t _line) noexcept
Definition catch.hpp:430
SourceLineInfo(SourceLineInfo &&) noexcept=default
SourceLineInfo(SourceLineInfo const &other)=default
std::size_t line
Definition catch.hpp:445
SourceLineInfo & operator=(SourceLineInfo const &)=default
char const * file
Definition catch.hpp:444
bool operator==(SourceLineInfo const &other) const noexcept
bool operator<(SourceLineInfo const &other) const noexcept
std::string operator+() const
static std::string convert(Catch::Detail::Approx const &value)
static std::string convert(R C::*p)
Definition catch.hpp:1666
static std::string convert(U *p)
Definition catch.hpp:1655
static std::string convert(T const(&arr)[SZ])
Definition catch.hpp:1898
static std::string convert(bool b)
static std::string convert(char c)
static std::string convert(char *str)
static std::string convert(char const *str)
static std::string convert(char const *str)
Definition catch.hpp:1575
static std::string convert(double value)
static std::string convert(float value)
static std::string convert(int value)
static std::string convert(long value)
static std::string convert(long long value)
static std::string convert(signed char c)
static std::string convert(signed char const *str)
Definition catch.hpp:1581
static std::string convert(std::nullptr_t)
static std::string convert(const std::string &str)
static std::string convert(const std::wstring &wstr)
static std::string convert(unsigned char c)
static std::string convert(unsigned char const *str)
Definition catch.hpp:1587
static std::string convert(unsigned int value)
static std::string convert(unsigned long value)
static std::string convert(unsigned long long value)
static std::string convert(wchar_t *str)
static std::string convert(wchar_t const *str)
static std::enable_if<::Catch::Detail::IsStreamInsertable< Fake >::value, std::string >::type convert(const Fake &value)
Definition catch.hpp:1482
static std::enable_if<!::Catch::Detail::IsStreamInsertable< Fake >::value, std::string >::type convert(const Fake &value)
Definition catch.hpp:1493
friend void setTags(TestCaseInfo &testCaseInfo, std::vector< std::string > tags)
std::vector< std::string > tags
Definition catch.hpp:4428
std::string tagsAsString() const
std::string className
Definition catch.hpp:4426
std::string description
Definition catch.hpp:4427
std::string name
Definition catch.hpp:4425
bool okToFail() const
std::vector< std::string > lcaseTags
Definition catch.hpp:4429
bool isHidden() const
SourceLineInfo lineInfo
Definition catch.hpp:4430
bool expectedToFail() const
TestCaseInfo(std::string const &_name, std::string const &_className, std::string const &_description, std::vector< std::string > const &_tags, SourceLineInfo const &_lineInfo)
SpecialProperties properties
Definition catch.hpp:4431
bool throws() const
Totals delta(Totals const &prevTotals) const
Counts assertions
Definition catch.hpp:2678
Totals operator-(Totals const &other) const
Totals & operator+=(Totals const &other)
Counts testCases
Definition catch.hpp:2679
static const bool value
Definition catch.hpp:1855
std::size_t m_count
Definition catch.hpp:3085
pluralise(std::size_t count, std::string const &label)
std::string m_label
Definition catch.hpp:3086
Definition format.h:897
T substr(T... args)
T swap(T... args)
T terminate(T... args)
T time(T... args)
T time_since_epoch(T... args)
T tmpfile(T... args)
T to_string(T... args)
T transform(T... args)
T uncaught_exceptions(T... args)
T unique(T... args)
T uppercase(T... args)
T valueless_by_exception(T... args)
T visit(T... args)
T what(T... args)
T width(T... args)
T write(T... args)