11 #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
12 #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
14 #define TWOBLUECUBES_CATCH_HPP_INCLUDED
17 # pragma clang system_header
18 #elif defined __GNUC__
19 # pragma GCC system_header
25 # ifdef __ICC // icpc defines the __clang__ macro
26 # pragma warning(push)
27 # pragma warning(disable: 161 1682)
29 # pragma clang diagnostic ignored "-Wglobal-constructors"
30 # pragma clang diagnostic ignored "-Wvariadic-macros"
31 # pragma clang diagnostic ignored "-Wc99-extensions"
32 # pragma clang diagnostic ignored "-Wunused-variable"
33 # pragma clang diagnostic push
34 # pragma clang diagnostic ignored "-Wpadded"
35 # pragma clang diagnostic ignored "-Wc++98-compat"
36 # pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
37 # pragma clang diagnostic ignored "-Wswitch-enum"
38 # pragma clang diagnostic ignored "-Wcovered-switch-default"
40 #elif defined __GNUC__
41 # pragma GCC diagnostic ignored "-Wvariadic-macros"
42 # pragma GCC diagnostic ignored "-Wunused-variable"
43 # pragma GCC diagnostic ignored "-Wparentheses"
45 # pragma GCC diagnostic push
46 # pragma GCC diagnostic ignored "-Wpadded"
48 #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
53 # ifndef CLARA_CONFIG_MAIN
54 # define CLARA_CONFIG_MAIN_NOT_DEFINED
55 # define CLARA_CONFIG_MAIN
60 #define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_H_INCLUDED
63 #define TWOBLUECUBES_CATCH_COMMON_H_INCLUDED
66 #define TWOBLUECUBES_CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED
102 # if __cplusplus >= 201103L
103 # define CATCH_CPP11_OR_GREATER
106 # if __cplusplus >= 201402L
107 # define CATCH_CPP14_OR_GREATER
114 # if __has_feature(cxx_nullptr)
115 # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
118 # if __has_feature(cxx_noexcept)
119 # define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
122 # if defined(CATCH_CPP11_OR_GREATER)
123 # define CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
124 _Pragma( "clang diagnostic push" ) \
125 _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" )
126 # define CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \
127 _Pragma( "clang diagnostic pop" )
129 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
130 _Pragma( "clang diagnostic push" ) \
131 _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
132 # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
133 _Pragma( "clang diagnostic pop" )
140 #if defined(__CYGWIN__) || defined(__QNX__)
142 # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
143 # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
149 # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
150 # define CATCH_CONFIG_COLOUR_NONE
167 #endif // __BORLANDC__
171 #ifdef __EDG_VERSION__
173 #endif // __EDG_VERSION__
185 # if __GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__)
186 # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
198 #define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
200 #if (_MSC_VER >= 1600)
201 # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
202 # define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR
205 #if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015))
206 #define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
207 #define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
208 #define CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE
209 #define CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS
217 #if ( defined _MSC_VER && _MSC_VER > 1400 && !defined __EDGE__) || \
218 ( defined __WAVE__ && __WAVE_HAS_VARIADICS ) || \
219 ( defined __GNUC__ && __GNUC__ >= 3 ) || \
220 ( !defined __cplusplus && __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L )
222 #define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS
227 #if ( defined _MSC_VER && _MSC_VER >= 1300 ) || \
228 ( defined __GNUC__ && ( __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3 )) ) || \
229 ( defined __clang__ && __clang_major__ >= 3 )
231 #define CATCH_INTERNAL_CONFIG_COUNTER
239 #if defined(CATCH_CPP11_OR_GREATER)
241 # if !defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR)
242 # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
245 # ifndef CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
246 # define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
249 # ifndef CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
250 # define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
253 # ifndef CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM
254 # define CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM
257 # ifndef CATCH_INTERNAL_CONFIG_CPP11_TUPLE
258 # define CATCH_INTERNAL_CONFIG_CPP11_TUPLE
261 # ifndef CATCH_INTERNAL_CONFIG_VARIADIC_MACROS
262 # define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS
265 # if !defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG)
266 # define CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG
269 # if !defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE)
270 # define CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE
272 # if !defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR)
273 # define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR
275 # if !defined(CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE)
276 # define CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE
278 # if !defined(CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS)
279 # define CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS
282 #endif // __cplusplus >= 201103L
285 #if defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NO_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_NO_CPP11)
286 # define CATCH_CONFIG_CPP11_NULLPTR
288 #if defined(CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_NO_CPP11)
289 # define CATCH_CONFIG_CPP11_NOEXCEPT
291 #if defined(CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_NO_CPP11)
292 # define CATCH_CONFIG_CPP11_GENERATED_METHODS
294 #if defined(CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_NO_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_NO_CPP11)
295 # define CATCH_CONFIG_CPP11_IS_ENUM
297 #if defined(CATCH_INTERNAL_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_CPP11_NO_TUPLE) && !defined(CATCH_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_NO_CPP11)
298 # define CATCH_CONFIG_CPP11_TUPLE
300 #if defined(CATCH_INTERNAL_CONFIG_VARIADIC_MACROS) && !defined(CATCH_CONFIG_NO_VARIADIC_MACROS) && !defined(CATCH_CONFIG_VARIADIC_MACROS)
301 # define CATCH_CONFIG_VARIADIC_MACROS
303 #if defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_CPP11_NO_LONG_LONG) && !defined(CATCH_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_NO_CPP11)
304 # define CATCH_CONFIG_CPP11_LONG_LONG
306 #if defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_CPP11_NO_OVERRIDE) && !defined(CATCH_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_NO_CPP11)
307 # define CATCH_CONFIG_CPP11_OVERRIDE
309 #if defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_NO_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_CPP11)
310 # define CATCH_CONFIG_CPP11_UNIQUE_PTR
315 #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) && !defined(__JETBRAINS_IDE__)
316 # define CATCH_CONFIG_COUNTER
318 #if defined(CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_NO_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_NO_CPP11)
319 # define CATCH_CONFIG_CPP11_SHUFFLE
321 # if defined(CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS) && !defined(CATCH_CONFIG_CPP11_NO_TYPE_TRAITS) && !defined(CATCH_CONFIG_CPP11_TYPE_TRAITS) && !defined(CATCH_CONFIG_NO_CPP11)
322 # define CATCH_CONFIG_CPP11_TYPE_TRAITS
324 #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH)
325 # define CATCH_CONFIG_WINDOWS_SEH
328 #if !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
329 # define CATCH_CONFIG_POSIX_SIGNALS
332 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
333 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
334 # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
336 #if !defined(CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS)
337 # define CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS
338 # define CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS
342 #if defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_NOEXCEPT)
343 # define CATCH_NOEXCEPT noexcept
344 # define CATCH_NOEXCEPT_IS(x) noexcept(x)
346 # define CATCH_NOEXCEPT throw()
347 # define CATCH_NOEXCEPT_IS(x)
351 #ifdef CATCH_CONFIG_CPP11_NULLPTR
352 # define CATCH_NULL nullptr
354 # define CATCH_NULL NULL
358 #ifdef CATCH_CONFIG_CPP11_OVERRIDE
359 # define CATCH_OVERRIDE override
361 # define CATCH_OVERRIDE
365 #ifdef CATCH_CONFIG_CPP11_UNIQUE_PTR
366 # define CATCH_AUTO_PTR( T ) std::unique_ptr<T>
368 # define CATCH_AUTO_PTR( T ) std::auto_ptr<T>
371 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
372 #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
373 #ifdef CATCH_CONFIG_COUNTER
374 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
376 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
379 #define INTERNAL_CATCH_STRINGIFY2( expr ) #expr
380 #define INTERNAL_CATCH_STRINGIFY( expr ) INTERNAL_CATCH_STRINGIFY2( expr )
389 struct CaseSensitive {
enum Choice {
395 #ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
396 NonCopyable( NonCopyable
const& ) =
delete;
397 NonCopyable( NonCopyable && ) =
delete;
398 NonCopyable& operator = ( NonCopyable
const& ) =
delete;
399 NonCopyable& operator = ( NonCopyable && ) =
delete;
401 NonCopyable( NonCopyable
const& info );
402 NonCopyable& operator = ( NonCopyable
const& );
407 virtual ~NonCopyable();
412 typedef void (SafeBool::*type)()
const;
414 static type makeSafe(
bool value ) {
415 return value ? &SafeBool::trueValue : 0;
418 void trueValue()
const {}
421 template<
typename ContainerT>
422 void deleteAll( ContainerT& container ) {
423 typename ContainerT::const_iterator it = container.begin();
424 typename ContainerT::const_iterator itEnd = container.end();
425 for(; it != itEnd; ++it )
428 template<
typename AssociativeContainerT>
429 void deleteAllValues( AssociativeContainerT& container ) {
430 typename AssociativeContainerT::const_iterator it = container.begin();
431 typename AssociativeContainerT::const_iterator itEnd = container.end();
432 for(; it != itEnd; ++it )
436 bool startsWith( std::string
const& s, std::string
const& prefix );
437 bool startsWith( std::string
const& s,
char prefix );
438 bool endsWith( std::string
const& s, std::string
const& suffix );
439 bool endsWith( std::string
const& s,
char suffix );
440 bool contains( std::string
const& s, std::string
const& infix );
441 void toLowerInPlace( std::string& s );
442 std::string toLower( std::string
const& s );
443 std::string trim( std::string
const& str );
444 bool replaceInPlace( std::string& str, std::string
const& replaceThis, std::string
const& withThis );
447 pluralise( std::size_t count, std::string
const& label );
449 friend std::ostream& operator << ( std::ostream& os, pluralise
const& pluraliser );
455 struct SourceLineInfo {
458 SourceLineInfo(
char const* _file, std::size_t _line );
459 # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
460 SourceLineInfo(SourceLineInfo
const& other) =
default;
461 SourceLineInfo( SourceLineInfo && ) =
default;
462 SourceLineInfo& operator = ( SourceLineInfo
const& ) =
default;
463 SourceLineInfo& operator = ( SourceLineInfo && ) =
default;
466 bool operator == ( SourceLineInfo
const& other )
const;
467 bool operator < ( SourceLineInfo
const& other )
const;
473 std::ostream& operator << ( std::ostream& os, SourceLineInfo
const& info );
476 inline bool isTrue(
bool value ){
return value; }
477 inline bool alwaysTrue() {
return true; }
478 inline bool alwaysFalse() {
return false; }
480 void throwLogicError( std::string
const& message, SourceLineInfo
const& locationInfo );
482 void seedRng( IConfig
const& config );
483 unsigned int rngSeed();
489 struct StreamEndStop {
490 std::string operator+() {
491 return std::string();
495 T
const& operator + ( T
const& value, StreamEndStop ) {
500 #define CATCH_INTERNAL_LINEINFO ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
501 #define CATCH_INTERNAL_ERROR( msg ) ::Catch::throwLogicError( msg, CATCH_INTERNAL_LINEINFO );
505 class NotImplementedException :
public std::exception
508 NotImplementedException( SourceLineInfo
const& lineInfo );
516 SourceLineInfo m_lineInfo;
522 #define CATCH_NOT_IMPLEMENTED throw Catch::NotImplementedException( CATCH_INTERNAL_LINEINFO )
525 #define TWOBLUECUBES_CATCH_CONTEXT_H_INCLUDED
528 #define TWOBLUECUBES_CATCH_INTERFACES_GENERATORS_H_INCLUDED
534 struct IGeneratorInfo {
535 virtual ~IGeneratorInfo();
536 virtual bool moveNext() = 0;
537 virtual std::size_t getCurrentIndex()
const = 0;
540 struct IGeneratorsForTest {
541 virtual ~IGeneratorsForTest();
543 virtual IGeneratorInfo& getGeneratorInfo( std::string
const& fileInfo, std::size_t size ) = 0;
544 virtual bool moveNext() = 0;
547 IGeneratorsForTest* createGeneratorsForTest();
552 #define TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED
555 #pragma clang diagnostic push
556 #pragma clang diagnostic ignored "-Wpadded"
568 Ptr( T* p ) : m_p( p ){
572 Ptr( Ptr
const& other ) : m_p( other.m_p ){
585 Ptr& operator = ( T* p ){
590 Ptr& operator = ( Ptr
const& other ){
595 void swap( Ptr& other ) { std::swap( m_p, other.m_p ); }
596 T*
get()
const{
return m_p; }
597 T& operator*()
const {
return *m_p; }
598 T* operator->()
const {
return m_p; }
599 bool operator !()
const {
return m_p ==
CATCH_NULL; }
600 operator SafeBool::type()
const {
return SafeBool::makeSafe( m_p !=
CATCH_NULL ); }
606 struct IShared : NonCopyable {
608 virtual void addRef()
const = 0;
609 virtual void release()
const = 0;
612 template<
typename T = IShared>
613 struct SharedImpl : T {
615 SharedImpl() : m_rc( 0 ){}
617 virtual void addRef()
const {
620 virtual void release()
const {
625 mutable unsigned int m_rc;
631 #pragma clang diagnostic pop
638 struct IResultCapture;
640 struct IGeneratorsForTest;
647 virtual IResultCapture* getResultCapture() = 0;
648 virtual IRunner* getRunner() = 0;
649 virtual size_t getGeneratorIndex( std::string
const& fileInfo,
size_t totalSize ) = 0;
650 virtual bool advanceGeneratorsForCurrentTest() = 0;
651 virtual Ptr<IConfig const> getConfig()
const = 0;
654 struct IMutableContext : IContext
656 virtual ~IMutableContext();
657 virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
658 virtual void setRunner( IRunner* runner ) = 0;
659 virtual void setConfig( Ptr<IConfig const>
const& config ) = 0;
662 IContext& getCurrentContext();
663 IMutableContext& getCurrentMutableContext();
664 void cleanUpContext();
665 Stream createStream( std::string
const& streamName );
670 #define TWOBLUECUBES_CATCH_TEST_REGISTRY_HPP_INCLUDED
673 #define TWOBLUECUBES_CATCH_INTERFACES_TESTCASE_H_INCLUDED
681 struct ITestCase : IShared {
682 virtual void invoke ()
const = 0;
684 virtual ~ITestCase();
690 struct ITestCaseRegistry {
691 virtual ~ITestCaseRegistry();
692 virtual std::vector<TestCase>
const& getAllTests()
const = 0;
693 virtual std::vector<TestCase>
const& getAllTestsSorted( IConfig
const& config )
const = 0;
696 bool matchTest( TestCase
const& testCase, TestSpec
const& testSpec, IConfig
const& config );
697 std::vector<TestCase> filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec, IConfig
const& config );
698 std::vector<TestCase>
const& getAllTestCasesSorted( IConfig
const& config );
705 class MethodTestCase :
public SharedImpl<ITestCase> {
708 MethodTestCase(
void (C::*method)() ) : m_method( method ) {}
710 virtual void invoke()
const {
716 virtual ~MethodTestCase() {}
718 void (C::*m_method)();
721 typedef void(*TestFunction)();
724 NameAndDesc(
const char* _name =
"",
const char* _description=
"" )
725 : name( _name ), description( _description )
729 const char* description;
732 void registerTestCase
733 ( ITestCase* testCase,
734 char const* className,
735 NameAndDesc
const& nameAndDesc,
736 SourceLineInfo
const& lineInfo );
741 ( TestFunction
function,
742 SourceLineInfo
const& lineInfo,
743 NameAndDesc
const& nameAndDesc );
747 (
void (C::*method)(),
748 char const* className,
749 NameAndDesc
const& nameAndDesc,
750 SourceLineInfo
const& lineInfo ) {
753 (
new MethodTestCase<C>( method ),
762 AutoReg( AutoReg
const& );
763 void operator= ( AutoReg
const& );
766 void registerTestCaseFunction
767 ( TestFunction
function,
768 SourceLineInfo
const& lineInfo,
769 NameAndDesc
const& nameAndDesc );
773 #ifdef CATCH_CONFIG_VARIADIC_MACROS
774 #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
776 static void TestName(); \
777 CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
778 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); } \
779 CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \
780 static void TestName()
781 #define INTERNAL_CATCH_TESTCASE( ... ) \
782 INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
785 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
786 CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
787 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); } \
788 CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS
791 #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
792 CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
794 struct TestName : ClassName{ \
797 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestName::test, #ClassName, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); \
799 CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \
800 void TestName::test()
801 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
802 INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
805 #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
806 CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
807 Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); \
808 CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS
811 #define INTERNAL_CATCH_TESTCASE2( TestName, Name, Desc ) \
813 static void TestName(); \
814 CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
815 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); } \
816 CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \
817 static void TestName()
818 #define INTERNAL_CATCH_TESTCASE( Name, Desc ) \
819 INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), Name, Desc )
822 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, Name, Desc ) \
823 CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
824 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( Name, Desc ), CATCH_INTERNAL_LINEINFO ); } \
825 CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS
828 #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestCaseName, ClassName, TestName, Desc )\
829 CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
831 struct TestCaseName : ClassName{ \
834 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestCaseName::test, #ClassName, Catch::NameAndDesc( TestName, Desc ), CATCH_INTERNAL_LINEINFO ); \
836 CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \
837 void TestCaseName::test()
838 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, TestName, Desc )\
839 INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, TestName, Desc )
842 #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, Name, Desc ) \
843 CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
844 Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); \
845 CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS
850 #define TWOBLUECUBES_CATCH_CAPTURE_HPP_INCLUDED
853 #define TWOBLUECUBES_CATCH_RESULT_BUILDER_H_INCLUDED
856 #define TWOBLUECUBES_CATCH_RESULT_TYPE_H_INCLUDED
861 struct ResultWas {
enum OfType {
869 ExpressionFailed = FailureBit | 1,
870 ExplicitFailure = FailureBit | 2,
872 Exception = 0x100 | FailureBit,
874 ThrewException = Exception | 1,
875 DidntThrowException = Exception | 2,
877 FatalErrorCondition = 0x200 | FailureBit
881 inline bool isOk( ResultWas::OfType resultType ) {
882 return ( resultType & ResultWas::FailureBit ) == 0;
884 inline bool isJustInfo(
int flags ) {
885 return flags == ResultWas::Info;
889 struct ResultDisposition {
enum Flags {
892 ContinueOnFailure = 0x02,
897 inline ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
898 return static_cast<ResultDisposition::Flags
>(
static_cast<int>( lhs ) | static_cast<int>( rhs ) );
901 inline bool shouldContinueOnFailure(
int flags ) {
return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
902 inline bool isFalseTest(
int flags ) {
return ( flags & ResultDisposition::FalseTest ) != 0; }
903 inline bool shouldSuppressFailure(
int flags ) {
return ( flags & ResultDisposition::SuppressFail ) != 0; }
908 #define TWOBLUECUBES_CATCH_ASSERTIONRESULT_H_INCLUDED
914 struct STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison;
916 struct DecomposedExpression
918 virtual ~DecomposedExpression() {}
919 virtual bool isBinaryExpression()
const {
922 virtual void reconstructExpression( std::string& dest )
const = 0;
926 template<
typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator + ( T
const& );
927 template<
typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator - ( T
const& );
928 template<
typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator * ( T
const& );
929 template<
typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator / ( T
const& );
930 template<
typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator % ( T
const& );
931 template<
typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( T
const& );
932 template<
typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( T
const& );
935 DecomposedExpression& operator = (DecomposedExpression
const&);
941 AssertionInfo(
char const * _macroName,
942 SourceLineInfo
const& _lineInfo,
943 char const * _capturedExpression,
944 ResultDisposition::Flags _resultDisposition,
945 char const * _secondArg =
"");
947 char const * macroName;
948 SourceLineInfo lineInfo;
949 char const * capturedExpression;
950 ResultDisposition::Flags resultDisposition;
951 char const * secondArg;
954 struct AssertionResultData
956 AssertionResultData() : decomposedExpression(
CATCH_NULL )
957 , resultType( ResultWas::Unknown )
959 , parenthesized(
false ) {}
961 void negate(
bool parenthesize ) {
963 parenthesized = parenthesize;
964 if( resultType == ResultWas::Ok )
965 resultType = ResultWas::ExpressionFailed;
966 else if( resultType == ResultWas::ExpressionFailed )
967 resultType = ResultWas::Ok;
970 std::string
const& reconstructExpression()
const {
972 decomposedExpression->reconstructExpression( reconstructedExpression );
973 if( parenthesized ) {
974 reconstructedExpression.insert( 0, 1,
'(' );
975 reconstructedExpression.append( 1,
')' );
978 reconstructedExpression.insert( 0, 1,
'!' );
982 return reconstructedExpression;
985 mutable DecomposedExpression
const* decomposedExpression;
986 mutable std::string reconstructedExpression;
988 ResultWas::OfType resultType;
993 class AssertionResult {
996 AssertionResult( AssertionInfo
const& info, AssertionResultData
const& data );
998 # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
999 AssertionResult( AssertionResult
const& ) =
default;
1000 AssertionResult( AssertionResult && ) =
default;
1001 AssertionResult& operator = ( AssertionResult
const& ) =
default;
1002 AssertionResult& operator = ( AssertionResult && ) =
default;
1006 bool succeeded()
const;
1007 ResultWas::OfType getResultType()
const;
1008 bool hasExpression()
const;
1009 bool hasMessage()
const;
1010 std::string getExpression()
const;
1011 std::string getExpressionInMacro()
const;
1012 bool hasExpandedExpression()
const;
1013 std::string getExpandedExpression()
const;
1014 std::string getMessage()
const;
1015 SourceLineInfo getSourceInfo()
const;
1016 std::string getTestMacroName()
const;
1017 void discardDecomposedExpression()
const;
1018 void expandDecomposedExpression()
const;
1021 AssertionInfo m_info;
1022 AssertionResultData m_resultData;
1028 #define TWOBLUECUBES_CATCH_MATCHERS_HPP_INCLUDED
1031 namespace Matchers {
1034 template<
typename ArgT>
struct MatchAllOf;
1035 template<
typename ArgT>
struct MatchAnyOf;
1036 template<
typename ArgT>
struct MatchNotOf;
1038 class MatcherUntypedBase {
1040 std::string toString()
const {
1041 if( m_cachedToString.empty() )
1042 m_cachedToString = describe();
1043 return m_cachedToString;
1047 virtual ~MatcherUntypedBase();
1048 virtual std::string describe()
const = 0;
1049 mutable std::string m_cachedToString;
1051 MatcherUntypedBase& operator = ( MatcherUntypedBase
const& );
1054 template<
typename ObjectT>
1055 struct MatcherMethod {
1056 virtual bool match( ObjectT
const& arg )
const = 0;
1058 template<
typename PtrT>
1059 struct MatcherMethod<PtrT*> {
1060 virtual bool match( PtrT* arg )
const = 0;
1063 template<
typename ObjectT,
typename ComparatorT = ObjectT>
1064 struct MatcherBase : MatcherUntypedBase, MatcherMethod<ObjectT> {
1066 MatchAllOf<ComparatorT> operator && ( MatcherBase
const& other )
const;
1067 MatchAnyOf<ComparatorT> operator || ( MatcherBase
const& other )
const;
1068 MatchNotOf<ComparatorT> operator ! ()
const;
1071 template<
typename ArgT>
1072 struct MatchAllOf : MatcherBase<ArgT> {
1074 for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
1075 if (!m_matchers[i]->match(arg))
1081 std::string description;
1082 description.reserve( 4 + m_matchers.size()*32 );
1083 description +=
"( ";
1084 for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
1086 description +=
" and ";
1087 description += m_matchers[i]->toString();
1089 description +=
" )";
1093 MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT>
const& other ) {
1094 m_matchers.push_back( &other );
1098 std::vector<MatcherBase<ArgT>
const*> m_matchers;
1100 template<
typename ArgT>
1101 struct MatchAnyOf : MatcherBase<ArgT> {
1104 for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
1105 if (m_matchers[i]->match(arg))
1111 std::string description;
1112 description.reserve( 4 + m_matchers.size()*32 );
1113 description +=
"( ";
1114 for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
1116 description +=
" or ";
1117 description += m_matchers[i]->toString();
1119 description +=
" )";
1123 MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT>
const& other ) {
1124 m_matchers.push_back( &other );
1128 std::vector<MatcherBase<ArgT>
const*> m_matchers;
1131 template<
typename ArgT>
1132 struct MatchNotOf : MatcherBase<ArgT> {
1134 MatchNotOf( MatcherBase<ArgT>
const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
1137 return !m_underlyingMatcher.match( arg );
1141 return "not " + m_underlyingMatcher.toString();
1143 MatcherBase<ArgT>
const& m_underlyingMatcher;
1146 template<
typename ObjectT,
typename ComparatorT>
1147 MatchAllOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator && ( MatcherBase
const& other )
const {
1148 return MatchAllOf<ComparatorT>() && *
this && other;
1150 template<
typename ObjectT,
typename ComparatorT>
1151 MatchAnyOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator || ( MatcherBase
const& other )
const {
1152 return MatchAnyOf<ComparatorT>() || *
this || other;
1154 template<
typename ObjectT,
typename ComparatorT>
1155 MatchNotOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator ! ()
const {
1156 return MatchNotOf<ComparatorT>( *this );
1164 template<
typename T>
1165 Impl::MatchNotOf<T> Not( Impl::MatcherBase<T>
const& underlyingMatcher ) {
1166 return Impl::MatchNotOf<T>( underlyingMatcher );
1168 template<
typename T>
1169 Impl::MatchAllOf<T> AllOf( Impl::MatcherBase<T>
const& m1, Impl::MatcherBase<T>
const& m2 ) {
1170 return Impl::MatchAllOf<T>() && m1 && m2;
1172 template<
typename T>
1173 Impl::MatchAllOf<T> AllOf( Impl::MatcherBase<T>
const& m1, Impl::MatcherBase<T>
const& m2, Impl::MatcherBase<T>
const& m3 ) {
1174 return Impl::MatchAllOf<T>() && m1 && m2 && m3;
1176 template<
typename T>
1177 Impl::MatchAnyOf<T> AnyOf( Impl::MatcherBase<T>
const& m1, Impl::MatcherBase<T>
const& m2 ) {
1178 return Impl::MatchAnyOf<T>() || m1 || m2;
1180 template<
typename T>
1181 Impl::MatchAnyOf<T> AnyOf( Impl::MatcherBase<T>
const& m1, Impl::MatcherBase<T>
const& m2, Impl::MatcherBase<T>
const& m3 ) {
1182 return Impl::MatchAnyOf<T>() || m1 || m2 || m3;
1187 using namespace Matchers;
1188 using Matchers::Impl::MatcherBase;
1194 struct TestFailureException{};
1196 template<
typename T>
class ExpressionLhs;
1198 struct CopyableStream {
1200 CopyableStream( CopyableStream
const& other ) {
1201 oss << other.oss.str();
1203 CopyableStream& operator=( CopyableStream
const& other ) {
1204 oss.str(std::string());
1205 oss << other.oss.str();
1208 std::ostringstream oss;
1211 class ResultBuilder :
public DecomposedExpression {
1213 ResultBuilder(
char const* macroName,
1214 SourceLineInfo
const& lineInfo,
1215 char const* capturedExpression,
1216 ResultDisposition::Flags resultDisposition,
1217 char const* secondArg =
"" );
1220 template<
typename T>
1221 ExpressionLhs<T const&>
operator <= ( T
const& operand );
1224 template<
typename T>
1225 ResultBuilder& operator << ( T
const& value ) {
1226 stream().oss << value;
1230 ResultBuilder& setResultType( ResultWas::OfType result );
1231 ResultBuilder& setResultType(
bool result );
1233 void endExpression( DecomposedExpression
const& expr );
1235 virtual void reconstructExpression( std::string& dest )
const CATCH_OVERRIDE;
1237 AssertionResult build()
const;
1238 AssertionResult build( DecomposedExpression
const& expr )
const;
1240 void useActiveException( ResultDisposition::Flags resultDisposition = ResultDisposition::Normal );
1241 void captureResult( ResultWas::OfType resultType );
1242 void captureExpression();
1243 void captureExpectedException( std::string
const& expectedMessage );
1244 void captureExpectedException( Matchers::Impl::MatcherBase<std::string>
const& matcher );
1245 void handleResult( AssertionResult
const& result );
1247 bool shouldDebugBreak()
const;
1248 bool allowThrows()
const;
1250 template<
typename ArgT,
typename MatcherT>
1251 void captureMatch( ArgT
const& arg, MatcherT
const& matcher,
char const* matcherString );
1253 void setExceptionGuard();
1254 void unsetExceptionGuard();
1257 AssertionInfo m_assertionInfo;
1258 AssertionResultData m_data;
1260 CopyableStream &stream()
1264 m_usedStream =
true;
1265 m_stream().oss.str(
"");
1270 static CopyableStream &m_stream()
1272 static CopyableStream s;
1276 bool m_shouldDebugBreak;
1278 bool m_guardException;
1286 #define TWOBLUECUBES_CATCH_EXPRESSION_LHS_HPP_INCLUDED
1289 #define TWOBLUECUBES_CATCH_EVALUATE_HPP_INCLUDED
1292 #pragma warning(push)
1293 #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
1294 #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
1300 namespace Internal {
1307 IsLessThanOrEqualTo,
1308 IsGreaterThanOrEqualTo
1311 template<Operator Op>
struct OperatorTraits {
static const char* getName(){
return "*error*"; } };
1312 template<>
struct OperatorTraits<IsEqualTo> {
static const char* getName(){
return "=="; } };
1313 template<>
struct OperatorTraits<IsNotEqualTo> {
static const char* getName(){
return "!="; } };
1314 template<>
struct OperatorTraits<IsLessThan> {
static const char* getName(){
return "<"; } };
1315 template<>
struct OperatorTraits<IsGreaterThan> {
static const char* getName(){
return ">"; } };
1316 template<>
struct OperatorTraits<IsLessThanOrEqualTo> {
static const char* getName(){
return "<="; } };
1317 template<>
struct OperatorTraits<IsGreaterThanOrEqualTo>{
static const char* getName(){
return ">="; } };
1319 template<
typename T>
1320 T& opCast(T
const& t) {
return const_cast<T&
>(t); }
1323 #ifdef CATCH_CONFIG_CPP11_NULLPTR
1324 inline std::nullptr_t opCast(std::nullptr_t) {
return nullptr; }
1325 #endif // CATCH_CONFIG_CPP11_NULLPTR
1329 template<
typename T1,
typename T2, Operator Op>
1332 template<
typename T1,
typename T2>
1333 struct Evaluator<T1, T2, IsEqualTo> {
1334 static bool evaluate( T1
const& lhs, T2
const& rhs) {
1335 return bool( opCast( lhs ) == opCast( rhs ) );
1338 template<
typename T1,
typename T2>
1339 struct Evaluator<T1, T2, IsNotEqualTo> {
1340 static bool evaluate( T1
const& lhs, T2
const& rhs ) {
1341 return bool( opCast( lhs ) != opCast( rhs ) );
1344 template<
typename T1,
typename T2>
1345 struct Evaluator<T1, T2, IsLessThan> {
1346 static bool evaluate( T1
const& lhs, T2
const& rhs ) {
1347 return bool( opCast( lhs ) < opCast( rhs ) );
1350 template<
typename T1,
typename T2>
1351 struct Evaluator<T1, T2, IsGreaterThan> {
1352 static bool evaluate( T1
const& lhs, T2
const& rhs ) {
1353 return bool( opCast( lhs ) > opCast( rhs ) );
1356 template<
typename T1,
typename T2>
1357 struct Evaluator<T1, T2, IsGreaterThanOrEqualTo> {
1358 static bool evaluate( T1
const& lhs, T2
const& rhs ) {
1359 return bool( opCast( lhs ) >= opCast( rhs ) );
1362 template<
typename T1,
typename T2>
1363 struct Evaluator<T1, T2, IsLessThanOrEqualTo> {
1364 static bool evaluate( T1
const& lhs, T2
const& rhs ) {
1365 return bool( opCast( lhs ) <= opCast( rhs ) );
1369 template<Operator Op,
typename T1,
typename T2>
1370 bool applyEvaluator( T1
const& lhs, T2
const& rhs ) {
1371 return Evaluator<T1, T2, Op>::evaluate( lhs, rhs );
1378 template<Operator Op,
typename T1,
typename T2>
1379 bool compare( T1
const& lhs, T2
const& rhs ) {
1380 return Evaluator<T1, T2, Op>::evaluate( lhs, rhs );
1384 template<Operator Op>
bool compare(
unsigned int lhs,
int rhs ) {
1385 return applyEvaluator<Op>( lhs,
static_cast<unsigned int>( rhs ) );
1387 template<Operator Op>
bool compare(
unsigned long lhs,
int rhs ) {
1388 return applyEvaluator<Op>( lhs,
static_cast<unsigned int>( rhs ) );
1390 template<Operator Op>
bool compare(
unsigned char lhs,
int rhs ) {
1391 return applyEvaluator<Op>( lhs,
static_cast<unsigned int>( rhs ) );
1395 template<Operator Op>
bool compare(
unsigned int lhs,
long rhs ) {
1396 return applyEvaluator<Op>( lhs,
static_cast<unsigned long>( rhs ) );
1398 template<Operator Op>
bool compare(
unsigned long lhs,
long rhs ) {
1399 return applyEvaluator<Op>( lhs,
static_cast<unsigned long>( rhs ) );
1401 template<Operator Op>
bool compare(
unsigned char lhs,
long rhs ) {
1402 return applyEvaluator<Op>( lhs,
static_cast<unsigned long>( rhs ) );
1406 template<Operator Op>
bool compare(
int lhs,
unsigned int rhs ) {
1407 return applyEvaluator<Op>(
static_cast<unsigned int>( lhs ), rhs );
1409 template<Operator Op>
bool compare(
int lhs,
unsigned long rhs ) {
1410 return applyEvaluator<Op>(
static_cast<unsigned int>( lhs ), rhs );
1412 template<Operator Op>
bool compare(
int lhs,
unsigned char rhs ) {
1413 return applyEvaluator<Op>(
static_cast<unsigned int>( lhs ), rhs );
1417 template<Operator Op>
bool compare(
long lhs,
unsigned int rhs ) {
1418 return applyEvaluator<Op>(
static_cast<unsigned long>( lhs ), rhs );
1420 template<Operator Op>
bool compare(
long lhs,
unsigned long rhs ) {
1421 return applyEvaluator<Op>(
static_cast<unsigned long>( lhs ), rhs );
1423 template<Operator Op>
bool compare(
long lhs,
unsigned char rhs ) {
1424 return applyEvaluator<Op>(
static_cast<unsigned long>( lhs ), rhs );
1428 template<Operator Op,
typename T>
bool compare(
long lhs, T* rhs ) {
1429 return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs );
1431 template<Operator Op,
typename T>
bool compare( T* lhs,
long rhs ) {
1432 return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) );
1436 template<Operator Op,
typename T>
bool compare(
int lhs, T* rhs ) {
1437 return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs );
1439 template<Operator Op,
typename T>
bool compare( T* lhs,
int rhs ) {
1440 return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) );
1443 #ifdef CATCH_CONFIG_CPP11_LONG_LONG
1445 template<Operator Op>
bool compare(
long long lhs,
unsigned int rhs ) {
1446 return applyEvaluator<Op>(
static_cast<unsigned long>( lhs ), rhs );
1448 template<Operator Op>
bool compare(
long long lhs,
unsigned long rhs ) {
1449 return applyEvaluator<Op>(
static_cast<unsigned long>( lhs ), rhs );
1451 template<Operator Op>
bool compare(
long long lhs,
unsigned long long rhs ) {
1452 return applyEvaluator<Op>(
static_cast<unsigned long>( lhs ), rhs );
1454 template<Operator Op>
bool compare(
long long lhs,
unsigned char rhs ) {
1455 return applyEvaluator<Op>(
static_cast<unsigned long>( lhs ), rhs );
1459 template<Operator Op>
bool compare(
unsigned long long lhs,
int rhs ) {
1460 return applyEvaluator<Op>(
static_cast<long>( lhs ), rhs );
1462 template<Operator Op>
bool compare(
unsigned long long lhs,
long rhs ) {
1463 return applyEvaluator<Op>(
static_cast<long>( lhs ), rhs );
1465 template<Operator Op>
bool compare(
unsigned long long lhs,
long long rhs ) {
1466 return applyEvaluator<Op>(
static_cast<long>( lhs ), rhs );
1468 template<Operator Op>
bool compare(
unsigned long long lhs,
char rhs ) {
1469 return applyEvaluator<Op>(
static_cast<long>( lhs ), rhs );
1473 template<Operator Op,
typename T>
bool compare(
long long lhs, T* rhs ) {
1474 return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs );
1476 template<Operator Op,
typename T>
bool compare( T* lhs,
long long rhs ) {
1477 return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) );
1479 #endif // CATCH_CONFIG_CPP11_LONG_LONG
1481 #ifdef CATCH_CONFIG_CPP11_NULLPTR
1483 template<Operator Op,
typename T>
bool compare( std::nullptr_t, T* rhs ) {
1484 return Evaluator<T*, T*, Op>::evaluate(
nullptr, rhs );
1486 template<Operator Op,
typename T>
bool compare( T* lhs, std::nullptr_t ) {
1487 return Evaluator<T*, T*, Op>::evaluate( lhs,
nullptr );
1489 #endif // CATCH_CONFIG_CPP11_NULLPTR
1495 #pragma warning(pop)
1499 #define TWOBLUECUBES_CATCH_TOSTRING_H_INCLUDED
1509 #define TWOBLUECUBES_CATCH_OBJC_ARC_HPP_INCLUDED
1511 #import <Foundation/Foundation.h>
1513 #ifdef __has_feature
1514 #define CATCH_ARC_ENABLED __has_feature(objc_arc)
1516 #define CATCH_ARC_ENABLED 0
1519 void arcSafeRelease( NSObject* obj );
1520 id performOptionalSelector(
id obj,
SEL sel );
1522 #if !CATCH_ARC_ENABLED
1523 inline void arcSafeRelease( NSObject* obj ) {
1526 inline id performOptionalSelector(
id obj,
SEL sel ) {
1527 if( [obj respondsToSelector: sel] )
1528 return [obj performSelector: sel];
1531 #define CATCH_UNSAFE_UNRETAINED
1532 #define CATCH_ARC_STRONG
1534 inline void arcSafeRelease( NSObject* ){}
1535 inline id performOptionalSelector(
id obj,
SEL sel ) {
1537 #pragma clang diagnostic push
1538 #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
1540 if( [obj respondsToSelector: sel] )
1541 return [obj performSelector: sel];
1543 #pragma clang diagnostic pop
1547 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
1548 #define CATCH_ARC_STRONG __strong
1553 #ifdef CATCH_CONFIG_CPP11_TUPLE
1557 #ifdef CATCH_CONFIG_CPP11_IS_ENUM
1558 #include <type_traits>
1564 template<
typename T>
1565 std::string toString( T
const& value );
1569 std::string toString( std::string
const& value );
1570 std::string toString( std::wstring
const& value );
1571 std::string toString(
const char*
const value );
1572 std::string toString(
char*
const value );
1573 std::string toString(
const wchar_t*
const value );
1574 std::string toString(
wchar_t*
const value );
1575 std::string toString(
int value );
1576 std::string toString(
unsigned long value );
1577 std::string toString(
unsigned int value );
1578 std::string toString(
const double value );
1579 std::string toString(
const float value );
1580 std::string toString(
bool value );
1581 std::string toString(
char value );
1582 std::string toString(
signed char value );
1583 std::string toString(
unsigned char value );
1585 #ifdef CATCH_CONFIG_CPP11_LONG_LONG
1586 std::string toString(
long long value );
1587 std::string toString(
unsigned long long value );
1590 #ifdef CATCH_CONFIG_CPP11_NULLPTR
1591 std::string toString( std::nullptr_t );
1595 std::string toString( NSString
const *
const& nsstring );
1596 std::string toString( NSString * CATCH_ARC_STRONG & nsstring );
1597 std::string toString( NSObject*
const& nsObject );
1602 extern const std::string unprintableString;
1604 #if !defined(CATCH_CONFIG_CPP11_STREAM_INSERTABLE_CHECK)
1606 template<
typename T> BorgType( T
const& );
1609 struct TrueType {
char sizer[1]; };
1610 struct FalseType {
char sizer[2]; };
1612 TrueType& testStreamable( std::ostream& );
1613 FalseType testStreamable( FalseType );
1615 FalseType operator<<( std::ostream
const&, BorgType
const& );
1617 template<
typename T>
1618 struct IsStreamInsertable {
1619 static std::ostream &s;
1621 enum { value =
sizeof( testStreamable(s << t) ) ==
sizeof( TrueType ) };
1624 template<
typename T>
1625 class IsStreamInsertable {
1626 template<
typename SS,
typename TT>
1627 static auto test(
int)
1628 -> decltype( std::declval<SS&>() << std::declval<TT>(), std::true_type() );
1630 template<
typename,
typename>
1631 static auto test(...) -> std::false_type;
1634 static const bool value = decltype(test<std::ostream,const T&>(0))::value;
1638 #if defined(CATCH_CONFIG_CPP11_IS_ENUM)
1639 template<
typename T,
1640 bool IsEnum = std::is_enum<T>::value
1642 struct EnumStringMaker
1644 static std::string convert( T
const& ) {
return unprintableString; }
1647 template<
typename T>
1648 struct EnumStringMaker<T,true>
1650 static std::string convert( T
const& v )
1652 return ::Catch::toString(
1653 static_cast<typename std::underlying_type<T>::type
>(v)
1659 struct StringMakerBase {
1660 #if defined(CATCH_CONFIG_CPP11_IS_ENUM)
1661 template<
typename T>
1662 static std::string convert( T
const& v )
1664 return EnumStringMaker<T>::convert( v );
1667 template<
typename T>
1668 static std::string convert( T
const& ) {
return unprintableString; }
1673 struct StringMakerBase<true> {
1674 template<
typename T>
1675 static std::string convert( T
const& _value ) {
1676 std::ostringstream oss;
1682 std::string rawMemoryToString(
const void *
object, std::size_t size );
1684 template<
typename T>
1685 std::string rawMemoryToString(
const T&
object ) {
1686 return rawMemoryToString( &
object,
sizeof(
object) );
1691 template<
typename T>
1692 struct StringMaker :
1693 Detail::StringMakerBase<Detail::IsStreamInsertable<T>::value> {};
1695 template<
typename T>
1696 struct StringMaker<T*> {
1697 template<
typename U>
1698 static std::string convert( U* p ) {
1702 return Detail::rawMemoryToString( p );
1706 template<
typename R,
typename C>
1707 struct StringMaker<R C::*> {
1708 static std::string convert( R C::* p ) {
1712 return Detail::rawMemoryToString( p );
1717 template<
typename InputIterator>
1718 std::string rangeToString( InputIterator first, InputIterator last );
1728 template<
typename T,
typename Allocator>
1729 std::string toString( std::vector<T,Allocator>
const& v ) {
1730 return Detail::rangeToString( v.begin(), v.end() );
1733 #ifdef CATCH_CONFIG_CPP11_TUPLE
1736 namespace TupleDetail {
1740 bool = (N < std::tuple_size<Tuple>::value)
1742 struct ElementPrinter {
1743 static void print(
const Tuple& tuple, std::ostream& os )
1745 os << ( N ?
", " :
" " )
1746 << Catch::toString(std::get<N>(tuple));
1747 ElementPrinter<Tuple,N+1>::print(tuple,os);
1755 struct ElementPrinter<Tuple,N,false> {
1756 static void print(
const Tuple&, std::ostream& ) {}
1761 template<
typename ...Types>
1762 struct StringMaker<std::tuple<Types...>> {
1764 static std::string convert(
const std::tuple<Types...>& tuple )
1766 std::ostringstream os;
1768 TupleDetail::ElementPrinter<std::tuple<Types...>>::print( tuple, os );
1773 #endif // CATCH_CONFIG_CPP11_TUPLE
1776 template<
typename T>
1777 std::string makeString( T
const& value ) {
1778 return StringMaker<T>::convert( value );
1789 template<
typename T>
1790 std::string toString( T
const& value ) {
1791 return StringMaker<T>::convert( value );
1795 template<
typename InputIterator>
1796 std::string rangeToString( InputIterator first, InputIterator last ) {
1797 std::ostringstream oss;
1799 if( first != last ) {
1800 oss << Catch::toString( *first );
1801 for( ++first ; first != last ; ++first )
1802 oss <<
", " << Catch::toString( *first );
1813 template<
typename LhsT, Internal::Operator Op,
typename RhsT>
1814 class BinaryExpression;
1816 template<
typename ArgT,
typename MatcherT>
1817 class MatchExpression;
1821 template<
typename T>
1822 class ExpressionLhs :
public DecomposedExpression {
1824 ExpressionLhs( ResultBuilder& rb, T lhs ) : m_rb( rb ), m_lhs( lhs ), m_truthy(false) {}
1826 ExpressionLhs& operator = (
const ExpressionLhs& );
1828 template<
typename RhsT>
1829 BinaryExpression<T, Internal::IsEqualTo, RhsT const&>
1831 return captureExpression<Internal::IsEqualTo>( rhs );
1834 template<
typename RhsT>
1835 BinaryExpression<T, Internal::IsNotEqualTo, RhsT const&>
1837 return captureExpression<Internal::IsNotEqualTo>( rhs );
1840 template<
typename RhsT>
1841 BinaryExpression<T, Internal::IsLessThan, RhsT const&>
1843 return captureExpression<Internal::IsLessThan>( rhs );
1846 template<
typename RhsT>
1847 BinaryExpression<T, Internal::IsGreaterThan, RhsT const&>
1849 return captureExpression<Internal::IsGreaterThan>( rhs );
1852 template<
typename RhsT>
1853 BinaryExpression<T, Internal::IsLessThanOrEqualTo, RhsT const&>
1855 return captureExpression<Internal::IsLessThanOrEqualTo>( rhs );
1858 template<
typename RhsT>
1859 BinaryExpression<T, Internal::IsGreaterThanOrEqualTo, RhsT const&>
1861 return captureExpression<Internal::IsGreaterThanOrEqualTo>( rhs );
1864 BinaryExpression<T, Internal::IsEqualTo, bool>
operator == (
bool rhs ) {
1865 return captureExpression<Internal::IsEqualTo>( rhs );
1868 BinaryExpression<T, Internal::IsNotEqualTo, bool>
operator != (
bool rhs ) {
1869 return captureExpression<Internal::IsNotEqualTo>( rhs );
1872 void endExpression() {
1873 m_truthy = m_lhs ?
true :
false;
1875 .setResultType( m_truthy )
1876 .endExpression( *
this );
1879 virtual void reconstructExpression( std::string& dest )
const CATCH_OVERRIDE {
1880 dest = Catch::toString( m_lhs );
1884 template<Internal::Operator Op,
typename RhsT>
1885 BinaryExpression<T, Op, RhsT&> captureExpression( RhsT& rhs )
const {
1886 return BinaryExpression<T, Op, RhsT&>( m_rb, m_lhs, rhs );
1889 template<Internal::Operator Op>
1890 BinaryExpression<T, Op, bool> captureExpression(
bool rhs )
const {
1891 return BinaryExpression<T, Op, bool>( m_rb, m_lhs, rhs );
1895 ResultBuilder& m_rb;
1900 template<
typename LhsT, Internal::Operator Op,
typename RhsT>
1901 class BinaryExpression :
public DecomposedExpression {
1903 BinaryExpression( ResultBuilder& rb, LhsT lhs, RhsT rhs )
1904 : m_rb( rb ), m_lhs( lhs ), m_rhs( rhs ) {}
1906 BinaryExpression& operator = ( BinaryExpression& );
1908 void endExpression()
const {
1910 .setResultType( Internal::compare<Op>( m_lhs, m_rhs ) )
1911 .endExpression( *
this );
1918 virtual void reconstructExpression( std::string& dest )
const CATCH_OVERRIDE {
1919 std::string lhs = Catch::toString( m_lhs );
1920 std::string rhs = Catch::toString( m_rhs );
1921 char delim = lhs.size() + rhs.size() < 40 &&
1922 lhs.find(
'\n') == std::string::npos &&
1923 rhs.find(
'\n') == std::string::npos ?
' ' :
'\n';
1924 dest.reserve( 7 + lhs.size() + rhs.size() );
1931 dest += Internal::OperatorTraits<Op>::getName();
1937 ResultBuilder& m_rb;
1942 template<
typename ArgT,
typename MatcherT>
1943 class MatchExpression :
public DecomposedExpression {
1945 MatchExpression( ArgT arg, MatcherT matcher,
char const* matcherString )
1946 : m_arg( arg ), m_matcher( matcher ), m_matcherString( matcherString ) {}
1952 virtual void reconstructExpression( std::string& dest )
const CATCH_OVERRIDE {
1953 std::string matcherAsString = m_matcher.toString();
1954 dest = Catch::toString( m_arg );
1956 if( matcherAsString == Detail::unprintableString )
1957 dest += m_matcherString;
1959 dest += matcherAsString;
1965 char const* m_matcherString;
1973 template<
typename T>
1975 return ExpressionLhs<T const&>( *
this, operand );
1979 return ExpressionLhs<bool>( *
this, value );
1982 template<
typename ArgT,
typename MatcherT>
1983 void ResultBuilder::captureMatch( ArgT
const& arg, MatcherT
const& matcher,
1984 char const* matcherString ) {
1985 MatchExpression<ArgT const&, MatcherT const&> expr( arg, matcher, matcherString );
1986 setResultType( matcher.match( arg ) );
1987 endExpression( expr );
1993 #define TWOBLUECUBES_CATCH_MESSAGE_H_INCLUDED
1999 struct MessageInfo {
2000 MessageInfo( std::string
const& _macroName,
2001 SourceLineInfo
const& _lineInfo,
2002 ResultWas::OfType _type );
2004 std::string macroName;
2005 SourceLineInfo lineInfo;
2006 ResultWas::OfType type;
2007 std::string message;
2008 unsigned int sequence;
2010 bool operator == ( MessageInfo
const& other )
const {
2011 return sequence == other.sequence;
2013 bool operator < ( MessageInfo
const& other )
const {
2014 return sequence < other.sequence;
2017 static unsigned int globalCount;
2020 struct MessageBuilder {
2021 MessageBuilder( std::string
const& macroName,
2022 SourceLineInfo
const& lineInfo,
2023 ResultWas::OfType type )
2024 : m_info( macroName, lineInfo, type )
2027 template<
typename T>
2028 MessageBuilder& operator << ( T
const& value ) {
2034 std::ostringstream m_stream;
2037 class ScopedMessage {
2039 ScopedMessage( MessageBuilder
const& builder );
2040 ScopedMessage( ScopedMessage
const& other );
2049 #define TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED
2056 class AssertionResult;
2057 struct AssertionInfo;
2059 struct SectionEndInfo;
2061 class ScopedMessageBuilder;
2064 struct IResultCapture {
2066 virtual ~IResultCapture();
2068 virtual void assertionEnded( AssertionResult
const& result ) = 0;
2069 virtual bool sectionStarted( SectionInfo
const& sectionInfo,
2070 Counts& assertions ) = 0;
2071 virtual void sectionEnded( SectionEndInfo
const& endInfo ) = 0;
2072 virtual void sectionEndedEarly( SectionEndInfo
const& endInfo ) = 0;
2073 virtual void pushScopedMessage( MessageInfo
const& message ) = 0;
2074 virtual void popScopedMessage( MessageInfo
const& message ) = 0;
2076 virtual std::string getCurrentTestName()
const = 0;
2077 virtual const AssertionResult* getLastResult()
const = 0;
2079 virtual void exceptionEarlyReported() = 0;
2081 virtual void handleFatalErrorCondition( std::string
const& message ) = 0;
2083 virtual bool lastAssertionPassed() = 0;
2084 virtual void assertionPassed() = 0;
2085 virtual void assertionRun() = 0;
2088 IResultCapture& getResultCapture();
2092 #define TWOBLUECUBES_CATCH_DEBUGGER_H_INCLUDED
2095 #define TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED
2097 #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
2098 # define CATCH_PLATFORM_MAC
2099 #elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
2100 # define CATCH_PLATFORM_IPHONE
2101 #elif defined(linux) || defined(__linux) || defined(__linux__)
2102 # define CATCH_PLATFORM_LINUX
2103 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
2104 # define CATCH_PLATFORM_WINDOWS
2105 # if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
2106 # define CATCH_DEFINES_NOMINMAX
2108 # if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
2109 # define CATCH_DEFINES_WIN32_LEAN_AND_MEAN
2117 bool isDebuggerActive();
2118 void writeToDebugConsole( std::string
const& text );
2121 #ifdef CATCH_PLATFORM_MAC
2125 #if defined(__ppc64__) || defined(__ppc__)
2126 #define CATCH_TRAP() \
2127 __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \
2128 : : : "memory","r0","r3","r4" )
2130 #define CATCH_TRAP() __asm__("int $3\n" : : )
2133 #elif defined(CATCH_PLATFORM_LINUX)
2137 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
2138 #define CATCH_TRAP() asm volatile ("int $3")
2139 #else // Fall back to the generic way.
2142 #define CATCH_TRAP() raise(SIGTRAP)
2144 #elif defined(_MSC_VER)
2145 #define CATCH_TRAP() __debugbreak()
2146 #elif defined(__MINGW32__)
2147 extern "C" __declspec(dllimport) void __stdcall DebugBreak();
2148 #define CATCH_TRAP() DebugBreak()
2152 #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
2154 #define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue();
2158 #define TWOBLUECUBES_CATCH_INTERFACES_RUNNER_H_INCLUDED
2165 virtual bool aborting()
const = 0;
2169 #if defined(CATCH_CONFIG_FAST_COMPILE)
2174 #define INTERNAL_CATCH_REACT( resultBuilder ) \
2175 resultBuilder.react();
2182 #define INTERNAL_CATCH_TEST_NO_TRY( macroName, resultDisposition, expr ) \
2184 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
2185 __catchResult.setExceptionGuard(); \
2186 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
2187 ( __catchResult <= expr ).endExpression(); \
2188 CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
2189 __catchResult.unsetExceptionGuard(); \
2190 INTERNAL_CATCH_REACT( __catchResult ) \
2191 } while( Catch::isTrue( false && static_cast<bool>( !!(expr) ) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look
2194 #define INTERNAL_CHECK_THAT_NO_TRY( macroName, matcher, resultDisposition, arg ) \
2196 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg ", " #matcher, resultDisposition ); \
2197 __catchResult.setExceptionGuard(); \
2198 __catchResult.captureMatch( arg, matcher, #matcher ); \
2199 __catchResult.unsetExceptionGuard(); \
2200 INTERNAL_CATCH_REACT( __catchResult ) \
2201 } while( Catch::alwaysFalse() )
2209 #define INTERNAL_CATCH_REACT( resultBuilder ) \
2210 if( resultBuilder.shouldDebugBreak() ) CATCH_BREAK_INTO_DEBUGGER(); \
2211 resultBuilder.react();
2215 #define INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ) \
2217 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
2219 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
2220 ( __catchResult <= expr ).endExpression(); \
2221 CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
2224 __catchResult.useActiveException( resultDisposition ); \
2226 INTERNAL_CATCH_REACT( __catchResult ) \
2227 } while( Catch::isTrue( false && static_cast<bool>( !!(expr) ) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look
2231 #define INTERNAL_CATCH_IF( macroName, resultDisposition, expr ) \
2232 INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ); \
2233 if( Catch::getResultCapture().lastAssertionPassed() )
2236 #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, expr ) \
2237 INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ); \
2238 if( !Catch::getResultCapture().lastAssertionPassed() )
2241 #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, expr ) \
2243 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
2245 static_cast<void>(expr); \
2246 __catchResult.captureResult( Catch::ResultWas::Ok ); \
2249 __catchResult.useActiveException( resultDisposition ); \
2251 INTERNAL_CATCH_REACT( __catchResult ) \
2252 } while( Catch::alwaysFalse() )
2255 #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, matcher, expr ) \
2257 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition, #matcher ); \
2258 if( __catchResult.allowThrows() ) \
2260 static_cast<void>(expr); \
2261 __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \
2264 __catchResult.captureExpectedException( matcher ); \
2267 __catchResult.captureResult( Catch::ResultWas::Ok ); \
2268 INTERNAL_CATCH_REACT( __catchResult ) \
2269 } while( Catch::alwaysFalse() )
2272 #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
2274 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr ", " #exceptionType, resultDisposition ); \
2275 if( __catchResult.allowThrows() ) \
2277 static_cast<void>(expr); \
2278 __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \
2280 catch( exceptionType ) { \
2281 __catchResult.captureResult( Catch::ResultWas::Ok ); \
2284 __catchResult.useActiveException( resultDisposition ); \
2287 __catchResult.captureResult( Catch::ResultWas::Ok ); \
2288 INTERNAL_CATCH_REACT( __catchResult ) \
2289 } while( Catch::alwaysFalse() )
2292 #ifdef CATCH_CONFIG_VARIADIC_MACROS
2293 #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
2295 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
2296 __catchResult << __VA_ARGS__ + ::Catch::StreamEndStop(); \
2297 __catchResult.captureResult( messageType ); \
2298 INTERNAL_CATCH_REACT( __catchResult ) \
2299 } while( Catch::alwaysFalse() )
2301 #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, log ) \
2303 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
2304 __catchResult << log + ::Catch::StreamEndStop(); \
2305 __catchResult.captureResult( messageType ); \
2306 INTERNAL_CATCH_REACT( __catchResult ) \
2307 } while( Catch::alwaysFalse() )
2311 #define INTERNAL_CATCH_INFO( macroName, log ) \
2312 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage ) = Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log;
2315 #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
2317 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg ", " #matcher, resultDisposition ); \
2319 __catchResult.captureMatch( arg, matcher, #matcher ); \
2321 __catchResult.useActiveException( resultDisposition | Catch::ResultDisposition::ContinueOnFailure ); \
2323 INTERNAL_CATCH_REACT( __catchResult ) \
2324 } while( Catch::alwaysFalse() )
2327 #define TWOBLUECUBES_CATCH_SECTION_H_INCLUDED
2330 #define TWOBLUECUBES_CATCH_SECTION_INFO_H_INCLUDED
2333 #define TWOBLUECUBES_CATCH_TOTALS_HPP_INCLUDED
2340 Counts() : passed( 0 ), failed( 0 ), failedButOk( 0 ) {}
2342 Counts operator - ( Counts
const& other )
const {
2344 diff.passed = passed - other.passed;
2345 diff.failed = failed - other.failed;
2346 diff.failedButOk = failedButOk - other.failedButOk;
2349 Counts& operator += ( Counts
const& other ) {
2350 passed += other.passed;
2351 failed += other.failed;
2352 failedButOk += other.failedButOk;
2356 std::size_t total()
const {
2357 return passed + failed + failedButOk;
2359 bool allPassed()
const {
2360 return failed == 0 && failedButOk == 0;
2362 bool allOk()
const {
2368 std::size_t failedButOk;
2373 Totals operator - ( Totals
const& other )
const {
2375 diff.assertions = assertions - other.assertions;
2376 diff.testCases = testCases - other.testCases;
2380 Totals delta( Totals
const& prevTotals )
const {
2381 Totals diff = *
this - prevTotals;
2382 if( diff.assertions.failed > 0 )
2383 ++diff.testCases.failed;
2384 else if( diff.assertions.failedButOk > 0 )
2385 ++diff.testCases.failedButOk;
2387 ++diff.testCases.passed;
2391 Totals& operator += ( Totals
const& other ) {
2392 assertions += other.assertions;
2393 testCases += other.testCases;
2406 struct SectionInfo {
2408 ( SourceLineInfo
const& _lineInfo,
2409 std::string
const& _name,
2410 std::string
const& _description = std::string() );
2413 std::string description;
2414 SourceLineInfo lineInfo;
2417 struct SectionEndInfo {
2418 SectionEndInfo( SectionInfo
const& _sectionInfo, Counts
const& _prevAssertions,
double _durationInSeconds )
2419 : sectionInfo( _sectionInfo ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds )
2422 SectionInfo sectionInfo;
2423 Counts prevAssertions;
2424 double durationInSeconds;
2430 #define TWOBLUECUBES_CATCH_TIMER_H_INCLUDED
2435 typedef unsigned long long UInt64;
2440 typedef uint64_t UInt64;
2447 Timer() : m_ticks( 0 ) {}
2449 unsigned int getElapsedMicroseconds()
const;
2450 unsigned int getElapsedMilliseconds()
const;
2451 double getElapsedSeconds()
const;
2463 class Section : NonCopyable {
2465 Section( SectionInfo
const& info );
2469 operator bool()
const;
2475 Counts m_assertions;
2476 bool m_sectionIncluded;
2482 #ifdef CATCH_CONFIG_VARIADIC_MACROS
2483 #define INTERNAL_CATCH_SECTION( ... ) \
2484 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) )
2486 #define INTERNAL_CATCH_SECTION( name, desc ) \
2487 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, name, desc ) )
2491 #define TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED
2499 template<
typename T>
2501 virtual ~IGenerator() {}
2502 virtual T getValue( std::size_t index )
const = 0;
2503 virtual std::size_t size ()
const = 0;
2506 template<
typename T>
2507 class BetweenGenerator :
public IGenerator<T> {
2509 BetweenGenerator( T from, T to ) : m_from( from ), m_to( to ){}
2511 virtual T getValue( std::size_t index )
const {
2512 return m_from+
static_cast<int>( index );
2515 virtual std::size_t size()
const {
2516 return static_cast<std::size_t
>( 1+m_to-m_from );
2525 template<
typename T>
2526 class ValuesGenerator :
public IGenerator<T> {
2530 void add( T value ) {
2531 m_values.push_back( value );
2534 virtual T getValue( std::size_t index )
const {
2535 return m_values[index];
2538 virtual std::size_t size()
const {
2539 return m_values.size();
2543 std::vector<T> m_values;
2546 template<
typename T>
2547 class CompositeGenerator {
2549 CompositeGenerator() : m_totalSize( 0 ) {}
2552 CompositeGenerator( CompositeGenerator& other )
2553 : m_fileInfo( other.m_fileInfo ),
2559 CompositeGenerator& setFileInfo(
const char* fileInfo ) {
2560 m_fileInfo = fileInfo;
2564 ~CompositeGenerator() {
2565 deleteAll( m_composed );
2568 operator T ()
const {
2569 size_t overallIndex = getCurrentContext().getGeneratorIndex( m_fileInfo, m_totalSize );
2571 typename std::vector<const IGenerator<T>*>::const_iterator it = m_composed.begin();
2572 typename std::vector<const IGenerator<T>*>::const_iterator itEnd = m_composed.end();
2573 for(
size_t index = 0; it != itEnd; ++it )
2575 const IGenerator<T>* generator = *it;
2576 if( overallIndex >= index && overallIndex < index + generator->size() )
2578 return generator->getValue( overallIndex-index );
2580 index += generator->size();
2586 void add(
const IGenerator<T>* generator ) {
2587 m_totalSize += generator->size();
2588 m_composed.push_back( generator );
2591 CompositeGenerator& then( CompositeGenerator& other ) {
2596 CompositeGenerator& then( T value ) {
2597 ValuesGenerator<T>* valuesGen =
new ValuesGenerator<T>();
2598 valuesGen->add( value );
2605 void move( CompositeGenerator& other ) {
2606 m_composed.insert( m_composed.end(), other.m_composed.begin(), other.m_composed.end() );
2607 m_totalSize += other.m_totalSize;
2608 other.m_composed.clear();
2611 std::vector<const IGenerator<T>*> m_composed;
2612 std::string m_fileInfo;
2616 namespace Generators
2618 template<
typename T>
2619 CompositeGenerator<T> between( T from, T to ) {
2620 CompositeGenerator<T> generators;
2621 generators.add(
new BetweenGenerator<T>( from, to ) );
2625 template<
typename T>
2626 CompositeGenerator<T> values( T val1, T val2 ) {
2627 CompositeGenerator<T> generators;
2628 ValuesGenerator<T>* valuesGen =
new ValuesGenerator<T>();
2629 valuesGen->add( val1 );
2630 valuesGen->add( val2 );
2631 generators.add( valuesGen );
2635 template<
typename T>
2636 CompositeGenerator<T> values( T val1, T val2, T val3 ){
2637 CompositeGenerator<T> generators;
2638 ValuesGenerator<T>* valuesGen =
new ValuesGenerator<T>();
2639 valuesGen->add( val1 );
2640 valuesGen->add( val2 );
2641 valuesGen->add( val3 );
2642 generators.add( valuesGen );
2646 template<
typename T>
2647 CompositeGenerator<T> values( T val1, T val2, T val3, T val4 ) {
2648 CompositeGenerator<T> generators;
2649 ValuesGenerator<T>* valuesGen =
new ValuesGenerator<T>();
2650 valuesGen->add( val1 );
2651 valuesGen->add( val2 );
2652 valuesGen->add( val3 );
2653 valuesGen->add( val4 );
2654 generators.add( valuesGen );
2660 using namespace Generators;
2664 #define INTERNAL_CATCH_LINESTR2( line ) #line
2665 #define INTERNAL_CATCH_LINESTR( line ) INTERNAL_CATCH_LINESTR2( line )
2667 #define INTERNAL_CATCH_GENERATE( expr ) expr.setFileInfo( __FILE__ "(" INTERNAL_CATCH_LINESTR( __LINE__ ) ")" )
2670 #define TWOBLUECUBES_CATCH_INTERFACES_EXCEPTION_H_INCLUDED
2676 #define TWOBLUECUBES_CATCH_INTERFACES_REGISTRY_HUB_H_INCLUDED
2683 struct ITestCaseRegistry;
2684 struct IExceptionTranslatorRegistry;
2685 struct IExceptionTranslator;
2686 struct IReporterRegistry;
2687 struct IReporterFactory;
2688 struct ITagAliasRegistry;
2690 struct IRegistryHub {
2691 virtual ~IRegistryHub();
2693 virtual IReporterRegistry
const& getReporterRegistry()
const = 0;
2694 virtual ITestCaseRegistry
const& getTestCaseRegistry()
const = 0;
2695 virtual ITagAliasRegistry
const& getTagAliasRegistry()
const = 0;
2697 virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0;
2700 struct IMutableRegistryHub {
2701 virtual ~IMutableRegistryHub();
2702 virtual void registerReporter( std::string
const& name, Ptr<IReporterFactory>
const& factory ) = 0;
2703 virtual void registerListener( Ptr<IReporterFactory>
const& factory ) = 0;
2704 virtual void registerTest( TestCase
const& testInfo ) = 0;
2705 virtual void registerTranslator(
const IExceptionTranslator* translator ) = 0;
2706 virtual void registerTagAlias( std::string
const& alias, std::string
const& tag, SourceLineInfo
const& lineInfo ) = 0;
2709 IRegistryHub& getRegistryHub();
2710 IMutableRegistryHub& getMutableRegistryHub();
2712 std::string translateActiveException();
2718 typedef std::string(*exceptionTranslateFunction)();
2720 struct IExceptionTranslator;
2721 typedef std::vector<const IExceptionTranslator*> ExceptionTranslators;
2723 struct IExceptionTranslator {
2724 virtual ~IExceptionTranslator();
2725 virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd )
const = 0;
2728 struct IExceptionTranslatorRegistry {
2729 virtual ~IExceptionTranslatorRegistry();
2731 virtual std::string translateActiveException()
const = 0;
2734 class ExceptionTranslatorRegistrar {
2735 template<
typename T>
2736 class ExceptionTranslator :
public IExceptionTranslator {
2739 ExceptionTranslator( std::string(*translateFunction)( T& ) )
2740 : m_translateFunction( translateFunction )
2743 virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd )
const CATCH_OVERRIDE {
2748 return (*it)->translate( it+1, itEnd );
2751 return m_translateFunction( ex );
2756 std::string(*m_translateFunction)( T& );
2760 template<
typename T>
2761 ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
2762 getMutableRegistryHub().registerTranslator
2763 (
new ExceptionTranslator<T>( translateFunction ) );
2769 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
2770 static std::string translatorName( signature ); \
2771 namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); }\
2772 static std::string translatorName( signature )
2774 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
2777 #define TWOBLUECUBES_CATCH_APPROX_HPP_INCLUDED
2782 #if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS)
2783 #include <type_traits>
2791 explicit Approx (
double value )
2792 : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
2798 static Approx custom() {
2802 #if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS)
2804 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2805 Approx operator()( T value ) {
2806 Approx approx( static_cast<double>(value) );
2807 approx.epsilon( m_epsilon );
2808 approx.margin( m_margin );
2809 approx.scale( m_scale );
2813 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2814 explicit Approx( T value ): Approx(static_cast<double>(value))
2817 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2818 friend bool operator == (
const T& lhs, Approx
const& rhs ) {
2820 auto lhs_v = double(lhs);
2821 bool relativeOK = std::fabs(lhs_v - rhs.m_value) < rhs.m_epsilon * (rhs.m_scale + (std::max)(std::fabs(lhs_v), std::fabs(rhs.m_value)));
2825 return std::fabs(lhs_v - rhs.m_value) < rhs.m_margin;
2828 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2829 friend bool operator == ( Approx
const& lhs,
const T& rhs ) {
2833 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2834 friend bool operator != ( T lhs, Approx
const& rhs ) {
2838 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2839 friend bool operator != ( Approx
const& lhs, T rhs ) {
2843 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2844 friend bool operator <= ( T lhs, Approx
const& rhs ) {
2845 return double(lhs) < rhs.m_value || lhs == rhs;
2848 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2849 friend bool operator <= ( Approx
const& lhs, T rhs ) {
2850 return lhs.m_value < double(rhs) || lhs == rhs;
2853 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2854 friend bool operator >= ( T lhs, Approx
const& rhs ) {
2855 return double(lhs) > rhs.m_value || lhs == rhs;
2858 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2859 friend bool operator >= ( Approx
const& lhs, T rhs ) {
2860 return lhs.m_value > double(rhs) || lhs == rhs;
2863 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2864 Approx& epsilon( T newEpsilon ) {
2865 m_epsilon = double(newEpsilon);
2869 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2870 Approx& margin( T newMargin ) {
2871 m_margin = double(newMargin);
2875 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2876 Approx& scale( T newScale ) {
2877 m_scale = double(newScale);
2883 Approx operator()(
double value ) {
2884 Approx approx( value );
2885 approx.epsilon( m_epsilon );
2886 approx.margin( m_margin );
2887 approx.scale( m_scale );
2891 friend bool operator == (
double lhs, Approx
const& rhs ) {
2893 bool relativeOK = std::fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( std::fabs(lhs), std::fabs(rhs.m_value) ) );
2897 return std::fabs(lhs - rhs.m_value) < rhs.m_margin;
2900 friend bool operator == ( Approx
const& lhs,
double rhs ) {
2904 friend bool operator != (
double lhs, Approx
const& rhs ) {
2908 friend bool operator != ( Approx
const& lhs,
double rhs ) {
2912 friend bool operator <= (
double lhs, Approx
const& rhs ) {
2913 return lhs < rhs.m_value || lhs == rhs;
2916 friend bool operator <= ( Approx
const& lhs,
double rhs ) {
2917 return lhs.m_value < rhs || lhs == rhs;
2920 friend bool operator >= (
double lhs, Approx
const& rhs ) {
2921 return lhs > rhs.m_value || lhs == rhs;
2924 friend bool operator >= ( Approx
const& lhs,
double rhs ) {
2925 return lhs.m_value > rhs || lhs == rhs;
2928 Approx& epsilon(
double newEpsilon ) {
2929 m_epsilon = newEpsilon;
2933 Approx& margin(
double newMargin ) {
2934 m_margin = newMargin;
2938 Approx& scale(
double newScale ) {
2944 std::string toString()
const {
2945 std::ostringstream oss;
2946 oss <<
"Approx( " << Catch::toString( m_value ) <<
" )";
2959 inline std::string toString<Detail::Approx>( Detail::Approx
const& value ) {
2960 return value.toString();
2966 #define TWOBLUECUBES_CATCH_MATCHERS_STRING_H_INCLUDED
2969 namespace Matchers {
2971 namespace StdString {
2975 CasedString( std::string
const& str, CaseSensitive::Choice caseSensitivity );
2976 std::string adjustString( std::string
const& str )
const;
2977 std::string caseSensitivitySuffix()
const;
2979 CaseSensitive::Choice m_caseSensitivity;
2983 struct StringMatcherBase : MatcherBase<std::string> {
2984 StringMatcherBase( std::string
const& operation, CasedString
const& comparator );
2987 CasedString m_comparator;
2988 std::string m_operation;
2991 struct EqualsMatcher : StringMatcherBase {
2992 EqualsMatcher( CasedString
const& comparator );
2993 virtual bool match( std::string
const& source )
const CATCH_OVERRIDE;
2995 struct ContainsMatcher : StringMatcherBase {
2996 ContainsMatcher( CasedString
const& comparator );
2997 virtual bool match( std::string
const& source )
const CATCH_OVERRIDE;
2999 struct StartsWithMatcher : StringMatcherBase {
3000 StartsWithMatcher( CasedString
const& comparator );
3001 virtual bool match( std::string
const& source )
const CATCH_OVERRIDE;
3003 struct EndsWithMatcher : StringMatcherBase {
3004 EndsWithMatcher( CasedString
const& comparator );
3005 virtual bool match( std::string
const& source )
const CATCH_OVERRIDE;
3013 StdString::EqualsMatcher Equals( std::string
const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3014 StdString::ContainsMatcher Contains( std::string
const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3015 StdString::EndsWithMatcher EndsWith( std::string
const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3016 StdString::StartsWithMatcher StartsWith( std::string
const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3022 #define TWOBLUECUBES_CATCH_MATCHERS_VECTOR_H_INCLUDED
3025 namespace Matchers {
3029 template<
typename T>
3030 struct ContainsElementMatcher : MatcherBase<std::vector<T>, T> {
3032 ContainsElementMatcher(T
const &comparator) : m_comparator( comparator) {}
3035 return std::find(v.begin(), v.end(), m_comparator) != v.end();
3039 return "Contains: " + Catch::toString( m_comparator );
3042 T
const& m_comparator;
3045 template<
typename T>
3046 struct ContainsMatcher : MatcherBase<std::vector<T>, std::vector<T> > {
3048 ContainsMatcher(std::vector<T>
const &comparator) : m_comparator( comparator ) {}
3052 if (m_comparator.size() > v.size())
3054 for (
size_t i = 0; i < m_comparator.size(); ++i)
3055 if (std::find(v.begin(), v.end(), m_comparator[i]) == v.end())
3060 return "Contains: " + Catch::toString( m_comparator );
3063 std::vector<T>
const& m_comparator;
3066 template<
typename T>
3067 struct EqualsMatcher : MatcherBase<std::vector<T>, std::vector<T> > {
3069 EqualsMatcher(std::vector<T>
const &comparator) : m_comparator( comparator ) {}
3076 if (m_comparator.size() != v.size())
3078 for (
size_t i = 0; i < v.size(); ++i)
3079 if (m_comparator[i] != v[i])
3084 return "Equals: " + Catch::toString( m_comparator );
3086 std::vector<T>
const& m_comparator;
3094 template<
typename T>
3095 Vector::ContainsMatcher<T> Contains( std::vector<T>
const& comparator ) {
3096 return Vector::ContainsMatcher<T>( comparator );
3099 template<
typename T>
3100 Vector::ContainsElementMatcher<T> VectorContains( T
const& comparator ) {
3101 return Vector::ContainsElementMatcher<T>( comparator );
3104 template<
typename T>
3105 Vector::EqualsMatcher<T> Equals( std::vector<T>
const& comparator ) {
3106 return Vector::EqualsMatcher<T>( comparator );
3113 #define TWOBLUECUBES_CATCH_INTERFACES_TAG_ALIAS_REGISTRY_H_INCLUDED
3116 #define TWOBLUECUBES_CATCH_TAG_ALIAS_H_INCLUDED
3123 TagAlias( std::string
const& _tag, SourceLineInfo _lineInfo ) : tag( _tag ), lineInfo( _lineInfo ) {}
3126 SourceLineInfo lineInfo;
3129 struct RegistrarForTagAliases {
3130 RegistrarForTagAliases(
char const* alias,
char const* tag, SourceLineInfo
const& lineInfo );
3135 #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); }
3137 #define TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED
3142 template<
typename T>
3146 Option( T
const& _value )
3147 : nullableValue(
new( storage ) T( _value ) )
3149 Option( Option
const& _other )
3150 : nullableValue( _other ?
new( storage ) T( *_other ) :
CATCH_NULL )
3157 Option& operator= ( Option
const& _other ) {
3158 if( &_other !=
this ) {
3161 nullableValue =
new( storage ) T( *_other );
3165 Option& operator = ( T
const& _value ) {
3167 nullableValue =
new( storage ) T( _value );
3173 nullableValue->~T();
3177 T& operator*() {
return *nullableValue; }
3178 T
const& operator*()
const {
return *nullableValue; }
3179 T* operator->() {
return nullableValue; }
3180 const T* operator->()
const {
return nullableValue; }
3182 T valueOr( T
const& defaultValue )
const {
3183 return nullableValue ? *nullableValue : defaultValue;
3186 bool some()
const {
return nullableValue !=
CATCH_NULL; }
3187 bool none()
const {
return nullableValue ==
CATCH_NULL; }
3189 bool operator !()
const {
return nullableValue ==
CATCH_NULL; }
3190 operator SafeBool::type()
const {
3191 return SafeBool::makeSafe( some() );
3197 char storage[
sizeof(T)];
3203 #ifdef CATCH_CONFIG_CPP11_LONG_LONG
3213 struct ITagAliasRegistry {
3214 virtual ~ITagAliasRegistry();
3215 virtual Option<TagAlias> find( std::string
const& alias )
const = 0;
3216 virtual std::string expandAliases( std::string
const& unexpandedTestSpec )
const = 0;
3218 static ITagAliasRegistry
const&
get();
3226 #define TWOBLUECUBES_CATCH_TEST_CASE_INFO_H_INCLUDED
3232 #pragma clang diagnostic push
3233 #pragma clang diagnostic ignored "-Wpadded"
3240 struct TestCaseInfo {
3241 enum SpecialProperties{
3244 ShouldFail = 1 << 2,
3247 NonPortable = 1 << 5
3250 TestCaseInfo( std::string
const& _name,
3251 std::string
const& _className,
3252 std::string
const& _description,
3253 std::set<std::string>
const& _tags,
3254 SourceLineInfo
const& _lineInfo );
3256 TestCaseInfo( TestCaseInfo
const& other );
3258 friend void setTags( TestCaseInfo& testCaseInfo, std::set<std::string>
const& tags );
3260 bool isHidden()
const;
3261 bool throws()
const;
3262 bool okToFail()
const;
3263 bool expectedToFail()
const;
3266 std::string className;
3267 std::string description;
3268 std::set<std::string> tags;
3269 std::set<std::string> lcaseTags;
3270 std::string tagsAsString;
3271 SourceLineInfo lineInfo;
3272 SpecialProperties properties;
3275 class TestCase :
public TestCaseInfo {
3278 TestCase( ITestCase* testCase, TestCaseInfo
const& info );
3279 TestCase( TestCase
const& other );
3281 TestCase withName( std::string
const& _newName )
const;
3283 void invoke()
const;
3285 TestCaseInfo
const& getTestCaseInfo()
const;
3287 void swap( TestCase& other );
3289 bool operator < ( TestCase
const& other )
const;
3290 TestCase& operator = ( TestCase
const& other );
3293 Ptr<ITestCase> test;
3296 TestCase makeTestCase( ITestCase* testCase,
3297 std::string
const& className,
3298 std::string
const& name,
3299 std::string
const& description,
3300 SourceLineInfo
const& lineInfo );
3304 #pragma clang diagnostic pop
3310 #define TWOBLUECUBES_CATCH_OBJC_HPP_INCLUDED
3312 #import <objc/runtime.h>
3334 class OcMethod :
public SharedImpl<ITestCase> {
3337 OcMethod( Class cls,
SEL sel ) : m_cls( cls ), m_sel( sel ) {}
3339 virtual void invoke()
const {
3340 id obj = [[m_cls alloc] init];
3342 performOptionalSelector( obj,
@selector(setUp) );
3343 performOptionalSelector( obj, m_sel );
3344 performOptionalSelector( obj,
@selector(tearDown) );
3346 arcSafeRelease( obj );
3349 virtual ~OcMethod() {}
3357 inline std::string getAnnotation( Class cls,
3358 std::string
const& annotationName,
3359 std::string
const& testCaseName ) {
3360 NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
3361 SEL sel = NSSelectorFromString( selStr );
3362 arcSafeRelease( selStr );
3363 id value = performOptionalSelector( cls, sel );
3365 return [(NSString*)value UTF8String];
3370 inline size_t registerTestMethods() {
3371 size_t noTestMethods = 0;
3372 int noClasses = objc_getClassList(
CATCH_NULL, 0 );
3374 Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc(
sizeof(Class) * noClasses);
3375 objc_getClassList( classes, noClasses );
3377 for(
int c = 0; c < noClasses; c++ ) {
3378 Class cls = classes[c];
3381 Method* methods = class_copyMethodList( cls, &count );
3382 for( u_int m = 0; m < count ; m++ ) {
3383 SEL selector = method_getName(methods[m]);
3384 std::string methodName = sel_getName(selector);
3385 if( startsWith( methodName,
"Catch_TestCase_" ) ) {
3386 std::string testCaseName = methodName.substr( 15 );
3387 std::string name = Detail::getAnnotation( cls,
"Name", testCaseName );
3388 std::string desc = Detail::getAnnotation( cls,
"Description", testCaseName );
3389 const char* className = class_getName( cls );
3391 getMutableRegistryHub().registerTest( makeTestCase(
new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo() ) );
3398 return noTestMethods;
3401 namespace Matchers {
3403 namespace NSStringMatchers {
3405 struct StringHolder : MatcherBase<NSString*>{
3406 StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
3407 StringHolder( StringHolder
const& other ) : m_substr( [other.m_substr copy] ){}
3409 arcSafeRelease( m_substr );
3419 struct Equals : StringHolder {
3420 Equals( NSString* substr ) : StringHolder( substr ){}
3423 return (str != nil || m_substr == nil ) &&
3424 [str isEqualToString:m_substr];
3428 return "equals string: " + Catch::toString( m_substr );
3432 struct Contains : StringHolder {
3433 Contains( NSString* substr ) : StringHolder( substr ){}
3435 virtual bool match( NSString* str )
const {
3436 return (str != nil || m_substr == nil ) &&
3437 [str rangeOfString:m_substr].location != NSNotFound;
3441 return "contains string: " + Catch::toString( m_substr );
3445 struct StartsWith : StringHolder {
3446 StartsWith( NSString* substr ) : StringHolder( substr ){}
3448 virtual bool match( NSString* str )
const {
3449 return (str != nil || m_substr == nil ) &&
3450 [str rangeOfString:m_substr].location == 0;
3454 return "starts with: " + Catch::toString( m_substr );
3457 struct EndsWith : StringHolder {
3458 EndsWith( NSString* substr ) : StringHolder( substr ){}
3460 virtual bool match( NSString* str )
const {
3461 return (str != nil || m_substr == nil ) &&
3462 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
3466 return "ends with: " + Catch::toString( m_substr );
3473 inline Impl::NSStringMatchers::Equals
3474 Equals( NSString* substr ){
return Impl::NSStringMatchers::Equals( substr ); }
3476 inline Impl::NSStringMatchers::Contains
3477 Contains( NSString* substr ){
return Impl::NSStringMatchers::Contains( substr ); }
3479 inline Impl::NSStringMatchers::StartsWith
3480 StartsWith( NSString* substr ){
return Impl::NSStringMatchers::StartsWith( substr ); }
3482 inline Impl::NSStringMatchers::EndsWith
3483 EndsWith( NSString* substr ){
return Impl::NSStringMatchers::EndsWith( substr ); }
3487 using namespace Matchers;
3492 #define OC_TEST_CASE( name, desc )\
3493 +(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Name_test ) \
3497 +(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Description_test ) \
3501 -(void) INTERNAL_CATCH_UNIQUE_NAME( Catch_TestCase_test )
3508 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
3510 class LeakDetector {
3513 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
3514 flag |= _CRTDBG_LEAK_CHECK_DF;
3515 flag |= _CRTDBG_ALLOC_MEM_DF;
3516 _CrtSetDbgFlag(flag);
3517 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
3518 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
3520 _CrtSetBreakAlloc(-1);
3524 class LeakDetector {};
3527 LeakDetector leakDetector;
3530 #define TWOBLUECUBES_CATCH_IMPL_HPP_INCLUDED
3536 #pragma clang diagnostic push
3537 #pragma clang diagnostic ignored "-Wweak-vtables"
3541 #define TWOBLUECUBES_CATCH_RUNNER_HPP_INCLUDED
3544 #define TWOBLUECUBES_CATCH_COMMANDLINE_HPP_INCLUDED
3547 #define TWOBLUECUBES_CATCH_CONFIG_HPP_INCLUDED
3550 #define TWOBLUECUBES_CATCH_TEST_SPEC_PARSER_HPP_INCLUDED
3553 #pragma clang diagnostic push
3554 #pragma clang diagnostic ignored "-Wpadded"
3558 #define TWOBLUECUBES_CATCH_TEST_SPEC_HPP_INCLUDED
3561 #pragma clang diagnostic push
3562 #pragma clang diagnostic ignored "-Wpadded"
3566 #define TWOBLUECUBES_CATCH_WILDCARD_PATTERN_HPP_INCLUDED
3568 #include <stdexcept>
3572 class WildcardPattern {
3573 enum WildcardPosition {
3575 WildcardAtStart = 1,
3577 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
3582 WildcardPattern( std::string
const& pattern, CaseSensitive::Choice caseSensitivity )
3583 : m_caseSensitivity( caseSensitivity ),
3584 m_wildcard( NoWildcard ),
3585 m_pattern( adjustCase( pattern ) )
3587 if( startsWith( m_pattern,
'*' ) ) {
3588 m_pattern = m_pattern.substr( 1 );
3589 m_wildcard = WildcardAtStart;
3591 if( endsWith( m_pattern,
'*' ) ) {
3592 m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
3593 m_wildcard =
static_cast<WildcardPosition
>( m_wildcard | WildcardAtEnd );
3596 virtual ~WildcardPattern();
3597 virtual bool matches( std::string
const& str )
const {
3598 switch( m_wildcard ) {
3600 return m_pattern == adjustCase( str );
3601 case WildcardAtStart:
3602 return endsWith( adjustCase( str ), m_pattern );
3604 return startsWith( adjustCase( str ), m_pattern );
3605 case WildcardAtBothEnds:
3606 return contains( adjustCase( str ), m_pattern );
3610 #pragma clang diagnostic push
3611 #pragma clang diagnostic ignored "-Wunreachable-code"
3613 throw std::logic_error(
"Unknown enum" );
3615 #pragma clang diagnostic pop
3619 std::string adjustCase( std::string
const& str )
const {
3620 return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
3622 CaseSensitive::Choice m_caseSensitivity;
3623 WildcardPosition m_wildcard;
3624 std::string m_pattern;
3634 struct Pattern : SharedImpl<> {
3636 virtual bool matches( TestCaseInfo
const& testCase )
const = 0;
3638 class NamePattern :
public Pattern {
3640 NamePattern( std::string
const& name )
3641 : m_wildcardPattern( toLower( name ), CaseSensitive::No )
3643 virtual ~NamePattern();
3644 virtual bool matches( TestCaseInfo
const& testCase )
const {
3645 return m_wildcardPattern.matches( toLower( testCase.name ) );
3648 WildcardPattern m_wildcardPattern;
3651 class TagPattern :
public Pattern {
3653 TagPattern( std::string
const& tag ) : m_tag( toLower( tag ) ) {}
3654 virtual ~TagPattern();
3655 virtual bool matches( TestCaseInfo
const& testCase )
const {
3656 return testCase.lcaseTags.find( m_tag ) != testCase.lcaseTags.end();
3662 class ExcludedPattern :
public Pattern {
3664 ExcludedPattern( Ptr<Pattern>
const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
3665 virtual ~ExcludedPattern();
3666 virtual bool matches( TestCaseInfo
const& testCase )
const {
return !m_underlyingPattern->matches( testCase ); }
3668 Ptr<Pattern> m_underlyingPattern;
3672 std::vector<Ptr<Pattern> > m_patterns;
3674 bool matches( TestCaseInfo
const& testCase )
const {
3676 for( std::vector<Ptr<Pattern> >::const_iterator it = m_patterns.begin(), itEnd = m_patterns.end(); it != itEnd; ++it ) {
3677 if( !(*it)->matches( testCase ) )
3685 bool hasFilters()
const {
3686 return !m_filters.empty();
3688 bool matches( TestCaseInfo
const& testCase )
const {
3690 for( std::vector<Filter>::const_iterator it = m_filters.begin(), itEnd = m_filters.end(); it != itEnd; ++it )
3691 if( it->matches( testCase ) )
3697 std::vector<Filter> m_filters;
3699 friend class TestSpecParser;
3704 #pragma clang diagnostic pop
3709 class TestSpecParser {
3710 enum Mode{ None, Name, QuotedName, Tag, EscapedName };
3713 std::size_t m_start, m_pos;
3715 std::vector<std::size_t> m_escapeChars;
3716 TestSpec::Filter m_currentFilter;
3717 TestSpec m_testSpec;
3718 ITagAliasRegistry
const* m_tagAliases;
3721 TestSpecParser( ITagAliasRegistry
const& tagAliases ) :m_mode(None), m_exclusion(false), m_start(0), m_pos(0), m_tagAliases( &tagAliases ) {}
3723 TestSpecParser& parse( std::string
const& arg ) {
3725 m_exclusion =
false;
3726 m_start = std::string::npos;
3727 m_arg = m_tagAliases->expandAliases( arg );
3728 m_escapeChars.clear();
3729 for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
3730 visitChar( m_arg[m_pos] );
3731 if( m_mode == Name )
3732 addPattern<TestSpec::NamePattern>();
3735 TestSpec testSpec() {
3740 void visitChar(
char c ) {
3741 if( m_mode == None ) {
3744 case '~': m_exclusion =
true;
return;
3745 case '[':
return startNewMode( Tag, ++m_pos );
3746 case '"':
return startNewMode( QuotedName, ++m_pos );
3747 case '\\':
return escape();
3748 default: startNewMode( Name, m_pos );
break;
3751 if( m_mode == Name ) {
3753 addPattern<TestSpec::NamePattern>();
3756 else if( c ==
'[' ) {
3757 if( subString() ==
"exclude:" )
3760 addPattern<TestSpec::NamePattern>();
3761 startNewMode( Tag, ++m_pos );
3763 else if( c ==
'\\' )
3766 else if( m_mode == EscapedName )
3768 else if( m_mode == QuotedName && c ==
'"' )
3769 addPattern<TestSpec::NamePattern>();
3770 else if( m_mode == Tag && c ==
']' )
3771 addPattern<TestSpec::TagPattern>();
3773 void startNewMode( Mode mode, std::size_t start ) {
3778 if( m_mode == None )
3780 m_mode = EscapedName;
3781 m_escapeChars.push_back( m_pos );
3783 std::string subString()
const {
return m_arg.substr( m_start, m_pos - m_start ); }
3784 template<
typename T>
3786 std::string token = subString();
3787 for(
size_t i = 0; i < m_escapeChars.size(); ++i )
3788 token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
3789 m_escapeChars.clear();
3790 if( startsWith( token,
"exclude:" ) ) {
3792 token = token.substr( 8 );
3794 if( !token.empty() ) {
3795 Ptr<TestSpec::Pattern> pattern =
new T( token );
3797 pattern =
new TestSpec::ExcludedPattern( pattern );
3798 m_currentFilter.m_patterns.push_back( pattern );
3800 m_exclusion =
false;
3804 if( !m_currentFilter.m_patterns.empty() ) {
3805 m_testSpec.m_filters.push_back( m_currentFilter );
3806 m_currentFilter = TestSpec::Filter();
3810 inline TestSpec parseTestSpec( std::string
const& arg ) {
3817 #pragma clang diagnostic pop
3821 #define TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED
3829 struct Verbosity {
enum Level {
3835 struct WarnAbout {
enum What {
3840 struct ShowDurations {
enum OrNot {
3845 struct RunTests {
enum InWhatOrder {
3847 InLexicographicalOrder,
3850 struct UseColour {
enum YesOrNo {
3858 struct IConfig : IShared {
3862 virtual bool allowThrows()
const = 0;
3863 virtual std::ostream& stream()
const = 0;
3864 virtual std::string name()
const = 0;
3865 virtual bool includeSuccessfulResults()
const = 0;
3866 virtual bool shouldDebugBreak()
const = 0;
3867 virtual bool warnAboutMissingAssertions()
const = 0;
3868 virtual int abortAfter()
const = 0;
3869 virtual bool showInvisibles()
const = 0;
3870 virtual ShowDurations::OrNot showDurations()
const = 0;
3871 virtual TestSpec
const& testSpec()
const = 0;
3872 virtual RunTests::InWhatOrder runOrder()
const = 0;
3873 virtual unsigned int rngSeed()
const = 0;
3874 virtual UseColour::YesOrNo useColour()
const = 0;
3875 virtual std::vector<std::string>
const& getSectionsToRun()
const = 0;
3881 #define TWOBLUECUBES_CATCH_STREAM_H_INCLUDED
3884 #define TWOBLUECUBES_CATCH_STREAMBUF_H_INCLUDED
3886 #include <streambuf>
3890 class StreamBufBase :
public std::streambuf {
3896 #include <streambuf>
3903 std::ostream& cout();
3904 std::ostream& cerr();
3905 std::ostream& clog();
3909 virtual std::ostream& stream() const = 0;
3912 class FileStream : public IStream {
3913 mutable std::ofstream m_ofs;
3915 FileStream( std::string
const& filename );
3921 class CoutStream : public IStream {
3922 mutable std::ostream m_os;
3928 virtual std::ostream& stream() const CATCH_OVERRIDE;
3931 class DebugOutStream : public IStream {
3933 mutable std::ostream m_os;
3939 virtual std::ostream& stream() const CATCH_OVERRIDE;
3946 #include <stdexcept>
3948 #ifndef CATCH_CONFIG_CONSOLE_WIDTH
3949 #define CATCH_CONFIG_CONSOLE_WIDTH 80
3957 : listTests( false ),
3959 listReporters( false ),
3960 listTestNamesOnly( false ),
3961 listExtraInfo( false ),
3962 showSuccessfulTests( false ),
3963 shouldDebugBreak( false ),
3966 showInvisibles( false ),
3967 filenamesAsTags( false ),
3970 verbosity( Verbosity::Normal ),
3971 warnings( WarnAbout::Nothing ),
3972 showDurations( ShowDurations::DefaultForReporter ),
3973 runOrder( RunTests::InDeclarationOrder ),
3974 useColour( UseColour::Auto )
3980 bool listTestNamesOnly;
3983 bool showSuccessfulTests;
3984 bool shouldDebugBreak;
3987 bool showInvisibles;
3988 bool filenamesAsTags;
3991 unsigned int rngSeed;
3993 Verbosity::Level verbosity;
3994 WarnAbout::What warnings;
3995 ShowDurations::OrNot showDurations;
3996 RunTests::InWhatOrder runOrder;
3997 UseColour::YesOrNo useColour;
3999 std::string outputFilename;
4001 std::string processName;
4003 std::vector<std::string> reporterNames;
4004 std::vector<std::string> testsOrTags;
4005 std::vector<std::string> sectionsToRun;
4008 class Config :
public SharedImpl<IConfig> {
4010 Config( Config
const& other );
4011 Config& operator = ( Config
const& other );
4012 virtual void dummy();
4018 Config( ConfigData
const& data )
4020 m_stream( openStream() )
4022 if( !data.testsOrTags.empty() ) {
4024 for( std::size_t i = 0; i < data.testsOrTags.size(); ++i )
4025 parser.parse( data.testsOrTags[i] );
4026 m_testSpec = parser.testSpec();
4030 virtual ~Config() {}
4032 std::string
const& getFilename()
const {
4033 return m_data.outputFilename ;
4036 bool listTests()
const {
return m_data.listTests; }
4037 bool listTestNamesOnly()
const {
return m_data.listTestNamesOnly; }
4038 bool listTags()
const {
return m_data.listTags; }
4039 bool listReporters()
const {
return m_data.listReporters; }
4040 bool listExtraInfo()
const {
return m_data.listExtraInfo; }
4042 std::string getProcessName()
const {
return m_data.processName; }
4044 std::vector<std::string>
const& getReporterNames()
const {
return m_data.reporterNames; }
4045 std::vector<std::string>
const& getSectionsToRun() const CATCH_OVERRIDE {
return m_data.sectionsToRun; }
4047 virtual TestSpec
const& testSpec() const CATCH_OVERRIDE {
return m_testSpec; }
4049 bool showHelp()
const {
return m_data.showHelp; }
4052 virtual bool allowThrows() const CATCH_OVERRIDE {
return !m_data.noThrow; }
4053 virtual std::ostream& stream() const CATCH_OVERRIDE {
return m_stream->stream(); }
4054 virtual std::string name() const CATCH_OVERRIDE {
return m_data.name.empty() ? m_data.processName : m_data.name; }
4055 virtual bool includeSuccessfulResults() const CATCH_OVERRIDE {
return m_data.showSuccessfulTests; }
4056 virtual bool warnAboutMissingAssertions() const CATCH_OVERRIDE {
return m_data.warnings & WarnAbout::NoAssertions; }
4057 virtual ShowDurations::OrNot showDurations() const CATCH_OVERRIDE {
return m_data.showDurations; }
4058 virtual RunTests::InWhatOrder runOrder() const CATCH_OVERRIDE {
return m_data.runOrder; }
4059 virtual unsigned int rngSeed() const CATCH_OVERRIDE {
return m_data.rngSeed; }
4060 virtual UseColour::YesOrNo useColour() const CATCH_OVERRIDE {
return m_data.useColour; }
4061 virtual bool shouldDebugBreak() const CATCH_OVERRIDE {
return m_data.shouldDebugBreak; }
4062 virtual int abortAfter() const CATCH_OVERRIDE {
return m_data.abortAfter; }
4063 virtual bool showInvisibles() const CATCH_OVERRIDE {
return m_data.showInvisibles; }
4067 IStream
const* openStream() {
4068 if( m_data.outputFilename.empty() )
4069 return new CoutStream();
4070 else if( m_data.outputFilename[0] ==
'%' ) {
4071 if( m_data.outputFilename ==
"%debug" )
4072 return new DebugOutStream();
4074 throw std::domain_error(
"Unrecognised stream: " + m_data.outputFilename );
4077 return new FileStream( m_data.outputFilename );
4082 TestSpec m_testSpec;
4088 #define TWOBLUECUBES_CATCH_CLARA_H_INCLUDED
4091 #ifdef CLARA_CONFIG_CONSOLE_WIDTH
4092 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CLARA_CONFIG_CONSOLE_WIDTH
4093 #undef CLARA_CONFIG_CONSOLE_WIDTH
4095 #define CLARA_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH
4098 #define STITCH_CLARA_OPEN_NAMESPACE namespace Catch {
4104 #if !defined(TWOBLUECUBES_CLARA_H_INCLUDED) || defined(STITCH_CLARA_OPEN_NAMESPACE)
4106 #ifndef STITCH_CLARA_OPEN_NAMESPACE
4107 #define TWOBLUECUBES_CLARA_H_INCLUDED
4108 #define STITCH_CLARA_OPEN_NAMESPACE
4109 #define STITCH_CLARA_CLOSE_NAMESPACE
4111 #define STITCH_CLARA_CLOSE_NAMESPACE }
4114 #define STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE STITCH_CLARA_OPEN_NAMESPACE
4119 #if !defined(TBC_TEXT_FORMAT_H_INCLUDED) || defined(STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE)
4120 #ifndef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE
4121 #define TBC_TEXT_FORMAT_H_INCLUDED
4127 #include <algorithm>
4131 #ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE
4132 namespace STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE {
4137 #ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH
4138 const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH;
4140 const unsigned int consoleWidth = 80;
4143 struct TextAttributes {
4145 : initialIndent( std::string::npos ),
4147 width( consoleWidth-1 ),
4151 TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value;
return *
this; }
4152 TextAttributes& setIndent( std::size_t _value ) { indent = _value;
return *
this; }
4153 TextAttributes& setWidth( std::size_t _value ) { width = _value;
return *
this; }
4154 TextAttributes& setTabChar(
char _value ) { tabChar = _value;
return *
this; }
4156 std::size_t initialIndent;
4164 Text( std::string
const& _str, TextAttributes
const& _attr = TextAttributes() )
4167 std::string wrappableChars =
" [({.,/|\\-";
4168 std::size_t indent = _attr.initialIndent != std::string::npos
4169 ? _attr.initialIndent
4171 std::string remainder = _str;
4173 while( !remainder.empty() ) {
4174 if( lines.size() >= 1000 ) {
4175 lines.push_back(
"... message truncated due to excessive size" );
4178 std::size_t tabPos = std::string::npos;
4179 std::size_t width = (std::min)( remainder.size(), _attr.width - indent );
4180 std::size_t pos = remainder.find_first_of(
'\n' );
4181 if( pos <= width ) {
4184 pos = remainder.find_last_of( _attr.tabChar, width );
4185 if( pos != std::string::npos ) {
4187 if( remainder[width] ==
'\n' )
4189 remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 );
4192 if( width == remainder.size() ) {
4193 spliceLine( indent, remainder, width );
4195 else if( remainder[width] ==
'\n' ) {
4196 spliceLine( indent, remainder, width );
4197 if( width <= 1 || remainder.size() != 1 )
4198 remainder = remainder.substr( 1 );
4199 indent = _attr.indent;
4202 pos = remainder.find_last_of( wrappableChars, width );
4203 if( pos != std::string::npos && pos > 0 ) {
4204 spliceLine( indent, remainder, pos );
4205 if( remainder[0] ==
' ' )
4206 remainder = remainder.substr( 1 );
4209 spliceLine( indent, remainder, width-1 );
4210 lines.back() += "-";
4212 if( lines.size() == 1 )
4213 indent = _attr.indent;
4214 if( tabPos != std::string::npos )
4220 void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) {
4221 lines.push_back( std::string( _indent,
' ' ) + _remainder.substr( 0, _pos ) );
4222 _remainder = _remainder.substr( _pos );
4225 typedef std::vector<std::string>::const_iterator const_iterator;
4227 const_iterator begin()
const {
return lines.begin(); }
4228 const_iterator end()
const {
return lines.end(); }
4229 std::string
const& last()
const {
return lines.back(); }
4230 std::size_t size()
const {
return lines.size(); }
4231 std::string
const& operator[]( std::size_t _index )
const {
return lines[_index]; }
4232 std::string toString()
const {
4233 std::ostringstream oss;
4238 friend std::ostream& operator << ( std::ostream& _stream, Text
const& _text ) {
4239 for( Text::const_iterator it = _text.begin(), itEnd = _text.end();
4240 it != itEnd; ++it ) {
4241 if( it != _text.begin() )
4250 TextAttributes attr;
4251 std::vector<std::string> lines;
4256 #ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE
4260 #endif // TBC_TEXT_FORMAT_H_INCLUDED
4265 #undef STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE
4269 #ifndef TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED
4270 #define TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED
4294 #if __has_feature(cxx_nullptr)
4295 #define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR
4298 #if __has_feature(cxx_noexcept)
4299 #define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT
4308 #if __GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__)
4309 #define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR
4321 #if (_MSC_VER >= 1600)
4322 #define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR
4323 #define CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR
4326 #if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015))
4327 #define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT
4328 #define CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
4337 #if defined(__cplusplus) && __cplusplus >= 201103L
4339 #define CLARA_CPP11_OR_GREATER
4341 #if !defined(CLARA_INTERNAL_CONFIG_CPP11_NULLPTR)
4342 #define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR
4345 #ifndef CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT
4346 #define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT
4349 #ifndef CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
4350 #define CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
4353 #if !defined(CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE)
4354 #define CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE
4356 #if !defined(CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR)
4357 #define CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR
4360 #endif // __cplusplus >= 201103L
4363 #if defined(CLARA_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CLARA_CONFIG_CPP11_NO_NULLPTR) && !defined(CLARA_CONFIG_CPP11_NULLPTR) && !defined(CLARA_CONFIG_NO_CPP11)
4364 #define CLARA_CONFIG_CPP11_NULLPTR
4366 #if defined(CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CLARA_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_CONFIG_NO_CPP11)
4367 #define CLARA_CONFIG_CPP11_NOEXCEPT
4369 #if defined(CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CLARA_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CLARA_CONFIG_CPP11_GENERATED_METHODS) && !defined(CLARA_CONFIG_NO_CPP11)
4370 #define CLARA_CONFIG_CPP11_GENERATED_METHODS
4372 #if defined(CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CLARA_CONFIG_NO_OVERRIDE) && !defined(CLARA_CONFIG_CPP11_OVERRIDE) && !defined(CLARA_CONFIG_NO_CPP11)
4373 #define CLARA_CONFIG_CPP11_OVERRIDE
4375 #if defined(CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CLARA_CONFIG_NO_UNIQUE_PTR) && !defined(CLARA_CONFIG_CPP11_UNIQUE_PTR) && !defined(CLARA_CONFIG_NO_CPP11)
4376 #define CLARA_CONFIG_CPP11_UNIQUE_PTR
4380 #if defined(CLARA_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_NOEXCEPT)
4381 #define CLARA_NOEXCEPT noexcept
4382 # define CLARA_NOEXCEPT_IS(x) noexcept(x)
4384 #define CLARA_NOEXCEPT throw()
4385 # define CLARA_NOEXCEPT_IS(x)
4389 #ifdef CLARA_CONFIG_CPP11_NULLPTR
4390 #define CLARA_NULL nullptr
4392 #define CLARA_NULL NULL
4396 #ifdef CLARA_CONFIG_CPP11_OVERRIDE
4397 #define CLARA_OVERRIDE override
4399 #define CLARA_OVERRIDE
4403 #ifdef CLARA_CONFIG_CPP11_UNIQUE_PTR
4404 # define CLARA_AUTO_PTR( T ) std::unique_ptr<T>
4406 # define CLARA_AUTO_PTR( T ) std::auto_ptr<T>
4409 #endif // TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED
4415 #include <stdexcept>
4418 #if defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
4419 #define CLARA_PLATFORM_WINDOWS
4423 #ifdef STITCH_CLARA_OPEN_NAMESPACE
4424 STITCH_CLARA_OPEN_NAMESPACE
4429 struct UnpositionalTag {};
4431 extern UnpositionalTag _;
4433 #ifdef CLARA_CONFIG_MAIN
4439 #ifdef CLARA_CONSOLE_WIDTH
4440 const unsigned int consoleWidth = CLARA_CONFIG_CONSOLE_WIDTH;
4442 const unsigned int consoleWidth = 80;
4445 using namespace Tbc;
4447 inline bool startsWith( std::string
const& str, std::string
const& prefix ) {
4448 return str.size() >= prefix.size() && str.substr( 0, prefix.size() ) == prefix;
4451 template<
typename T>
struct RemoveConstRef{
typedef T type; };
4452 template<
typename T>
struct RemoveConstRef<T&>{
typedef T type; };
4453 template<
typename T>
struct RemoveConstRef<T const&>{
typedef T type; };
4454 template<
typename T>
struct RemoveConstRef<T const>{
typedef T type; };
4456 template<
typename T>
struct IsBool {
static const bool value =
false; };
4457 template<>
struct IsBool<bool> {
static const bool value =
true; };
4459 template<
typename T>
4460 void convertInto( std::string
const& _source, T& _dest ) {
4461 std::stringstream ss;
4465 throw std::runtime_error(
"Unable to convert " + _source +
" to destination type" );
4467 inline void convertInto( std::string
const& _source, std::string& _dest ) {
4470 char toLowerCh(
char c) {
4471 return static_cast<char>( std::tolower( c ) );
4473 inline void convertInto( std::string
const& _source,
bool& _dest ) {
4474 std::string sourceLC = _source;
4475 std::transform( sourceLC.begin(), sourceLC.end(), sourceLC.begin(), toLowerCh );
4476 if( sourceLC ==
"y" || sourceLC ==
"1" || sourceLC ==
"true" || sourceLC ==
"yes" || sourceLC ==
"on" )
4478 else if( sourceLC ==
"n" || sourceLC ==
"0" || sourceLC ==
"false" || sourceLC ==
"no" || sourceLC ==
"off" )
4481 throw std::runtime_error(
"Expected a boolean value but did not recognise:\n '" + _source +
"'" );
4484 template<
typename ConfigT>
4485 struct IArgFunction {
4486 virtual ~IArgFunction() {}
4487 #ifdef CLARA_CONFIG_CPP11_GENERATED_METHODS
4488 IArgFunction() =
default;
4489 IArgFunction( IArgFunction
const& ) =
default;
4491 virtual void set( ConfigT& config, std::string
const& value )
const = 0;
4492 virtual bool takesArg()
const = 0;
4493 virtual IArgFunction* clone()
const = 0;
4496 template<
typename ConfigT>
4497 class BoundArgFunction {
4499 BoundArgFunction() : functionObj( CLARA_NULL ) {}
4500 BoundArgFunction( IArgFunction<ConfigT>* _functionObj ) : functionObj( _functionObj ) {}
4501 BoundArgFunction( BoundArgFunction
const& other ) : functionObj( other.functionObj ? other.functionObj->clone() : CLARA_NULL ) {}
4502 BoundArgFunction& operator = ( BoundArgFunction
const& other ) {
4503 IArgFunction<ConfigT>* newFunctionObj = other.functionObj ? other.functionObj->clone() : CLARA_NULL;
4505 functionObj = newFunctionObj;
4508 ~BoundArgFunction() {
delete functionObj; }
4510 void set( ConfigT& config, std::string
const& value )
const {
4511 functionObj->set( config, value );
4513 bool takesArg()
const {
return functionObj->takesArg(); }
4515 bool isSet()
const {
4516 return functionObj != CLARA_NULL;
4519 IArgFunction<ConfigT>* functionObj;
4522 template<
typename C>
4523 struct NullBinder : IArgFunction<C>{
4524 virtual void set( C&, std::string
const& )
const {}
4525 virtual bool takesArg()
const {
return true; }
4526 virtual IArgFunction<C>* clone()
const {
return new NullBinder( *
this ); }
4529 template<
typename C,
typename M>
4530 struct BoundDataMember : IArgFunction<C>{
4531 BoundDataMember( M C::* _member ) : member( _member ) {}
4532 virtual void set( C& p, std::string
const& stringValue )
const {
4533 convertInto( stringValue, p.*member );
4535 virtual bool takesArg()
const {
return !IsBool<M>::value; }
4536 virtual IArgFunction<C>* clone()
const {
return new BoundDataMember( *
this ); }
4539 template<
typename C,
typename M>
4540 struct BoundUnaryMethod : IArgFunction<C>{
4541 BoundUnaryMethod(
void (C::*_member)( M ) ) : member( _member ) {}
4542 virtual void set( C& p, std::string
const& stringValue )
const {
4543 typename RemoveConstRef<M>::type value;
4544 convertInto( stringValue, value );
4545 (p.*member)( value );
4547 virtual bool takesArg()
const {
return !IsBool<M>::value; }
4548 virtual IArgFunction<C>* clone()
const {
return new BoundUnaryMethod( *
this ); }
4549 void (C::*member)( M );
4551 template<
typename C>
4552 struct BoundNullaryMethod : IArgFunction<C>{
4553 BoundNullaryMethod(
void (C::*_member)() ) : member( _member ) {}
4554 virtual void set( C& p, std::string
const& stringValue )
const {
4556 convertInto( stringValue, value );
4560 virtual bool takesArg()
const {
return false; }
4561 virtual IArgFunction<C>* clone()
const {
return new BoundNullaryMethod( *
this ); }
4562 void (C::*member)();
4565 template<
typename C>
4566 struct BoundUnaryFunction : IArgFunction<C>{
4567 BoundUnaryFunction(
void (*_function)( C& ) ) : function( _function ) {}
4568 virtual void set( C& obj, std::string
const& stringValue )
const {
4570 convertInto( stringValue, value );
4574 virtual bool takesArg()
const {
return false; }
4575 virtual IArgFunction<C>* clone()
const {
return new BoundUnaryFunction( *
this ); }
4576 void (*
function)( C& );
4579 template<
typename C,
typename T>
4580 struct BoundBinaryFunction : IArgFunction<C>{
4581 BoundBinaryFunction(
void (*_function)( C&, T ) ) : function( _function ) {}
4582 virtual void set( C& obj, std::string
const& stringValue )
const {
4583 typename RemoveConstRef<T>::type value;
4584 convertInto( stringValue, value );
4585 function( obj, value );
4587 virtual bool takesArg()
const {
return !IsBool<T>::value; }
4588 virtual IArgFunction<C>* clone()
const {
return new BoundBinaryFunction( *
this ); }
4589 void (*
function)( C&, T );
4594 inline std::vector<std::string> argsToVector(
int argc,
char const*
const*
const argv ) {
4595 std::vector<std::string> args( static_cast<std::size_t>( argc ) );
4596 for( std::size_t i = 0; i < static_cast<std::size_t>( argc ); ++i )
4603 enum Mode { None, MaybeShortOpt, SlashOpt, ShortOpt, LongOpt, Positional };
4610 enum Type { Positional, ShortOpt, LongOpt };
4611 Token( Type _type, std::string
const& _data ) : type( _type ), data( _data ) {}
4616 Parser() : mode( None ), from( 0 ), inQuotes( false ){}
4618 void parseIntoTokens( std::vector<std::string>
const& args, std::vector<Token>& tokens ) {
4619 const std::string doubleDash =
"--";
4620 for( std::size_t i = 1; i < args.size() && args[i] != doubleDash; ++i )
4621 parseIntoTokens( args[i], tokens);
4624 void parseIntoTokens( std::string
const& arg, std::vector<Token>& tokens ) {
4625 for( std::size_t i = 0; i < arg.size(); ++i ) {
4628 inQuotes = !inQuotes;
4629 mode = handleMode( i, c, arg, tokens );
4631 mode = handleMode( arg.size(),
'\0', arg, tokens );
4633 Mode handleMode( std::size_t i,
char c, std::string
const& arg, std::vector<Token>& tokens ) {
4635 case None:
return handleNone( i, c );
4636 case MaybeShortOpt:
return handleMaybeShortOpt( i, c );
4639 case SlashOpt:
return handleOpt( i, c, arg, tokens );
4640 case Positional:
return handlePositional( i, c, arg, tokens );
4641 default:
throw std::logic_error(
"Unknown mode" );
4645 Mode handleNone( std::size_t i,
char c ) {
4651 case '-':
return MaybeShortOpt;
4652 #ifdef CLARA_PLATFORM_WINDOWS
4653 case '/': from = i+1;
return SlashOpt;
4655 default: from = i;
return Positional;
4658 Mode handleMaybeShortOpt( std::size_t i,
char c ) {
4660 case '-': from = i+1;
return LongOpt;
4661 default: from = i;
return ShortOpt;
4665 Mode handleOpt( std::size_t i,
char c, std::string
const& arg, std::vector<Token>& tokens ) {
4666 if( std::string(
":=\0", 3 ).find( c ) == std::string::npos )
4669 std::string optName = arg.substr( from, i-from );
4670 if( mode == ShortOpt )
4671 for( std::size_t j = 0; j < optName.size(); ++j )
4672 tokens.push_back( Token( Token::ShortOpt, optName.substr( j, 1 ) ) );
4673 else if( mode == SlashOpt && optName.size() == 1 )
4674 tokens.push_back( Token( Token::ShortOpt, optName ) );
4676 tokens.push_back( Token( Token::LongOpt, optName ) );
4679 Mode handlePositional( std::size_t i,
char c, std::string
const& arg, std::vector<Token>& tokens ) {
4680 if( inQuotes || std::string(
"\0", 1 ).find( c ) == std::string::npos )
4683 std::string data = arg.substr( from, i-from );
4684 tokens.push_back( Token( Token::Positional, data ) );
4689 template<
typename ConfigT>
4690 struct CommonArgProperties {
4691 CommonArgProperties() {}
4692 CommonArgProperties( Detail::BoundArgFunction<ConfigT>
const& _boundField ) : boundField( _boundField ) {}
4694 Detail::BoundArgFunction<ConfigT> boundField;
4695 std::string description;
4697 std::string placeholder;
4699 bool takesArg()
const {
4700 return !placeholder.empty();
4702 void validate()
const {
4703 if( !boundField.isSet() )
4704 throw std::logic_error(
"option not bound" );
4707 struct OptionArgProperties {
4708 std::vector<std::string> shortNames;
4709 std::string longName;
4711 bool hasShortName( std::string
const& shortName )
const {
4712 return std::find( shortNames.begin(), shortNames.end(), shortName ) != shortNames.end();
4714 bool hasLongName( std::string
const& _longName )
const {
4715 return _longName == longName;
4718 struct PositionalArgProperties {
4719 PositionalArgProperties() : position( -1 ) {}
4722 bool isFixedPositional()
const {
4723 return position != -1;
4727 template<
typename ConfigT>
4730 struct Arg : CommonArgProperties<ConfigT>, OptionArgProperties, PositionalArgProperties {
4732 Arg( Detail::BoundArgFunction<ConfigT>
const& _boundField ) : CommonArgProperties<ConfigT>( _boundField ) {}
4734 using CommonArgProperties<ConfigT>::placeholder;
4736 std::string dbgName()
const {
4737 if( !longName.empty() )
4738 return "--" + longName;
4739 if( !shortNames.empty() )
4740 return "-" + shortNames[0];
4741 return "positional args";
4743 std::string commands()
const {
4744 std::ostringstream oss;
4746 std::vector<std::string>::const_iterator it = shortNames.begin(), itEnd = shortNames.end();
4747 for(; it != itEnd; ++it ) {
4754 if( !longName.empty() ) {
4757 oss <<
"--" << longName;
4759 if( !placeholder.empty() )
4760 oss <<
" <" << placeholder <<
">";
4765 typedef CLARA_AUTO_PTR( Arg ) ArgAutoPtr;
4767 friend
void addOptName( Arg& arg, std::
string const& optName )
4769 if( optName.empty() )
4771 if( Detail::startsWith( optName,
"--" ) ) {
4772 if( !arg.longName.empty() )
4773 throw std::logic_error(
"Only one long opt may be specified. '"
4775 +
"' already specified, now attempting to add '"
4777 arg.longName = optName.substr( 2 );
4779 else if( Detail::startsWith( optName,
"-" ) )
4780 arg.shortNames.push_back( optName.substr( 1 ) );
4782 throw std::logic_error(
"option must begin with - or --. Option was: '" + optName +
"'" );
4784 friend void setPositionalArg( Arg& arg,
int position )
4786 arg.position = position;
4791 ArgBuilder( Arg* arg ) : m_arg( arg ) {}
4794 template<
typename C,
typename M>
4795 void bind( M C::* field, std::string
const& placeholder ) {
4796 m_arg->boundField =
new Detail::BoundDataMember<C,M>( field );
4797 m_arg->placeholder = placeholder;
4800 template<
typename C>
4801 void bind(
bool C::* field ) {
4802 m_arg->boundField =
new Detail::BoundDataMember<C,bool>( field );
4806 template<
typename C,
typename M>
4807 void bind(
void (C::* unaryMethod)( M ), std::string
const& placeholder ) {
4808 m_arg->boundField =
new Detail::BoundUnaryMethod<C,M>( unaryMethod );
4809 m_arg->placeholder = placeholder;
4813 template<
typename C>
4814 void bind(
void (C::* unaryMethod)(
bool ) ) {
4815 m_arg->boundField =
new Detail::BoundUnaryMethod<C,bool>( unaryMethod );
4819 template<
typename C>
4820 void bind(
void (C::* nullaryMethod)() ) {
4821 m_arg->boundField =
new Detail::BoundNullaryMethod<C>( nullaryMethod );
4825 template<
typename C>
4826 void bind(
void (* unaryFunction)( C& ) ) {
4827 m_arg->boundField =
new Detail::BoundUnaryFunction<C>( unaryFunction );
4831 template<
typename C,
typename T>
4832 void bind(
void (* binaryFunction)( C&, T ), std::string
const& placeholder ) {
4833 m_arg->boundField =
new Detail::BoundBinaryFunction<C, T>( binaryFunction );
4834 m_arg->placeholder = placeholder;
4837 ArgBuilder& describe( std::string
const& description ) {
4838 m_arg->description = description;
4841 ArgBuilder& detail( std::string
const& detail ) {
4842 m_arg->detail = detail;
4850 class OptBuilder :
public ArgBuilder {
4852 OptBuilder( Arg* arg ) : ArgBuilder( arg ) {}
4853 OptBuilder( OptBuilder& other ) : ArgBuilder( other ) {}
4855 OptBuilder& operator[]( std::string
const& optName ) {
4856 addOptName( *ArgBuilder::m_arg, optName );
4864 : m_boundProcessName( new Detail::NullBinder<ConfigT>() ),
4865 m_highestSpecifiedArgPosition( 0 ),
4866 m_throwOnUnrecognisedTokens( false )
4868 CommandLine( CommandLine
const& other )
4869 : m_boundProcessName( other.m_boundProcessName ),
4870 m_options ( other.m_options ),
4871 m_positionalArgs( other.m_positionalArgs ),
4872 m_highestSpecifiedArgPosition( other.m_highestSpecifiedArgPosition ),
4873 m_throwOnUnrecognisedTokens( other.m_throwOnUnrecognisedTokens )
4875 if( other.m_floatingArg.get() )
4876 m_floatingArg.reset(
new Arg( *other.m_floatingArg ) );
4879 CommandLine& setThrowOnUnrecognisedTokens(
bool shouldThrow =
true ) {
4880 m_throwOnUnrecognisedTokens = shouldThrow;
4884 OptBuilder operator[]( std::string
const& optName ) {
4885 m_options.push_back( Arg() );
4886 addOptName( m_options.back(), optName );
4887 OptBuilder builder( &m_options.back() );
4891 ArgBuilder operator[](
int position ) {
4892 m_positionalArgs.insert( std::make_pair( position, Arg() ) );
4893 if( position > m_highestSpecifiedArgPosition )
4894 m_highestSpecifiedArgPosition = position;
4895 setPositionalArg( m_positionalArgs[position], position );
4896 ArgBuilder builder( &m_positionalArgs[position] );
4901 ArgBuilder operator[]( UnpositionalTag ) {
4902 if( m_floatingArg.get() )
4903 throw std::logic_error(
"Only one unpositional argument can be added" );
4904 m_floatingArg.reset(
new Arg() );
4905 ArgBuilder builder( m_floatingArg.get() );
4909 template<
typename C,
typename M>
4910 void bindProcessName( M C::* field ) {
4911 m_boundProcessName =
new Detail::BoundDataMember<C,M>( field );
4913 template<
typename C,
typename M>
4914 void bindProcessName(
void (C::*_unaryMethod)( M ) ) {
4915 m_boundProcessName =
new Detail::BoundUnaryMethod<C,M>( _unaryMethod );
4918 void optUsage( std::ostream& os, std::size_t indent = 0, std::size_t width = Detail::consoleWidth )
const {
4919 typename std::vector<Arg>::const_iterator itBegin = m_options.begin(), itEnd = m_options.end(), it;
4920 std::size_t maxWidth = 0;
4921 for( it = itBegin; it != itEnd; ++it )
4922 maxWidth = (std::max)( maxWidth, it->commands().size() );
4924 for( it = itBegin; it != itEnd; ++it ) {
4925 Detail::Text usage( it->commands(), Detail::TextAttributes()
4926 .setWidth( maxWidth+indent )
4927 .setIndent( indent ) );
4928 Detail::Text desc( it->description, Detail::TextAttributes()
4929 .setWidth( width - maxWidth - 3 ) );
4931 for( std::size_t i = 0; i < (std::max)( usage.size(), desc.size() ); ++i ) {
4932 std::string usageCol = i < usage.size() ? usage[i] :
"";
4935 if( i < desc.size() && !desc[i].empty() )
4936 os << std::string( indent + 2 + maxWidth - usageCol.size(),
' ' )
4942 std::string optUsage()
const {
4943 std::ostringstream oss;
4948 void argSynopsis( std::ostream& os )
const {
4949 for(
int i = 1; i <= m_highestSpecifiedArgPosition; ++i ) {
4952 typename std::map<int, Arg>::const_iterator it = m_positionalArgs.find( i );
4953 if( it != m_positionalArgs.end() )
4954 os <<
"<" << it->second.placeholder <<
">";
4955 else if( m_floatingArg.get() )
4956 os <<
"<" << m_floatingArg->placeholder <<
">";
4958 throw std::logic_error(
"non consecutive positional arguments with no floating args" );
4961 if( m_floatingArg.get() ) {
4962 if( m_highestSpecifiedArgPosition > 1 )
4964 os <<
"[<" << m_floatingArg->placeholder <<
"> ...]";
4967 std::string argSynopsis()
const {
4968 std::ostringstream oss;
4973 void usage( std::ostream& os, std::string
const& procName )
const {
4975 os <<
"usage:\n " << procName <<
" ";
4977 if( !m_options.empty() ) {
4978 os <<
" [options]\n\nwhere options are: \n";
4983 std::string usage( std::string
const& procName )
const {
4984 std::ostringstream oss;
4985 usage( oss, procName );
4989 ConfigT parse( std::vector<std::string>
const& args )
const {
4991 parseInto( args, config );
4995 std::vector<Parser::Token> parseInto( std::vector<std::string>
const& args, ConfigT& config )
const {
4996 std::string processName = args.empty() ? std::string() : args[0];
4997 std::size_t lastSlash = processName.find_last_of(
"/\\" );
4998 if( lastSlash != std::string::npos )
4999 processName = processName.substr( lastSlash+1 );
5000 m_boundProcessName.set( config, processName );
5001 std::vector<Parser::Token> tokens;
5003 parser.parseIntoTokens( args, tokens );
5004 return populate( tokens, config );
5007 std::vector<Parser::Token> populate( std::vector<Parser::Token>
const& tokens, ConfigT& config )
const {
5009 std::vector<Parser::Token> unusedTokens = populateOptions( tokens, config );
5010 unusedTokens = populateFixedArgs( unusedTokens, config );
5011 unusedTokens = populateFloatingArgs( unusedTokens, config );
5012 return unusedTokens;
5015 std::vector<Parser::Token> populateOptions( std::vector<Parser::Token>
const& tokens, ConfigT& config )
const {
5016 std::vector<Parser::Token> unusedTokens;
5017 std::vector<std::string> errors;
5018 for( std::size_t i = 0; i < tokens.size(); ++i ) {
5019 Parser::Token
const& token = tokens[i];
5020 typename std::vector<Arg>::const_iterator it = m_options.begin(), itEnd = m_options.end();
5021 for(; it != itEnd; ++it ) {
5022 Arg
const& arg = *it;
5025 if( ( token.type == Parser::Token::ShortOpt && arg.hasShortName( token.data ) ) ||
5026 ( token.type == Parser::Token::LongOpt && arg.hasLongName( token.data ) ) ) {
5027 if( arg.takesArg() ) {
5028 if( i == tokens.size()-1 || tokens[i+1].type != Parser::Token::Positional )
5029 errors.push_back( "Expected argument to option: " + token.data );
5031 arg.boundField.set( config, tokens[++i].data );
5034 arg.boundField.set( config,
"true" );
5039 catch( std::exception& ex ) {
5040 errors.push_back( std::string( ex.what() ) +
"\n- while parsing: (" + arg.commands() + ")" );
5044 if( token.type == Parser::Token::Positional || !m_throwOnUnrecognisedTokens )
5045 unusedTokens.push_back( token );
5046 else if( errors.empty() && m_throwOnUnrecognisedTokens )
5047 errors.push_back(
"unrecognised option: " + token.data );
5050 if( !errors.empty() ) {
5051 std::ostringstream oss;
5052 for( std::vector<std::string>::const_iterator it = errors.begin(), itEnd = errors.end();
5055 if( it != errors.begin() )
5059 throw std::runtime_error( oss.str() );
5061 return unusedTokens;
5063 std::vector<Parser::Token> populateFixedArgs( std::vector<Parser::Token>
const& tokens, ConfigT& config )
const {
5064 std::vector<Parser::Token> unusedTokens;
5066 for( std::size_t i = 0; i < tokens.size(); ++i ) {
5067 Parser::Token
const& token = tokens[i];
5068 typename std::map<int, Arg>::const_iterator it = m_positionalArgs.find( position );
5069 if( it != m_positionalArgs.end() )
5070 it->second.boundField.set( config, token.data );
5072 unusedTokens.push_back( token );
5073 if( token.type == Parser::Token::Positional )
5076 return unusedTokens;
5078 std::vector<Parser::Token> populateFloatingArgs( std::vector<Parser::Token>
const& tokens, ConfigT& config )
const {
5079 if( !m_floatingArg.get() )
5081 std::vector<Parser::Token> unusedTokens;
5082 for( std::size_t i = 0; i < tokens.size(); ++i ) {
5083 Parser::Token
const& token = tokens[i];
5084 if( token.type == Parser::Token::Positional )
5085 m_floatingArg->boundField.set( config, token.data );
5087 unusedTokens.push_back( token );
5089 return unusedTokens;
5092 void validate()
const
5094 if( m_options.empty() && m_positionalArgs.empty() && !m_floatingArg.get() )
5095 throw std::logic_error(
"No options or arguments specified" );
5097 for(
typename std::vector<Arg>::const_iterator it = m_options.begin(),
5098 itEnd = m_options.end();
5104 Detail::BoundArgFunction<ConfigT> m_boundProcessName;
5105 std::vector<Arg> m_options;
5106 std::map<int, Arg> m_positionalArgs;
5107 ArgAutoPtr m_floatingArg;
5108 int m_highestSpecifiedArgPosition;
5109 bool m_throwOnUnrecognisedTokens;
5114 STITCH_CLARA_CLOSE_NAMESPACE
5115 #undef STITCH_CLARA_OPEN_NAMESPACE
5116 #undef STITCH_CLARA_CLOSE_NAMESPACE
5118 #endif // TWOBLUECUBES_CLARA_H_INCLUDED
5119 #undef STITCH_CLARA_OPEN_NAMESPACE
5122 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
5123 #define CLARA_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
5124 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
5132 inline void abortAfterFirst( ConfigData& config ) { config.abortAfter = 1; }
5133 inline void abortAfterX( ConfigData& config,
int x ) {
5135 throw std::runtime_error(
"Value after -x or --abortAfter must be greater than zero" );
5136 config.abortAfter = x;
5138 inline void addTestOrTags( ConfigData& config, std::string
const& _testSpec ) { config.testsOrTags.push_back( _testSpec ); }
5139 inline void addSectionToRun( ConfigData& config, std::string
const& sectionName ) { config.sectionsToRun.push_back( sectionName ); }
5140 inline void addReporterName( ConfigData& config, std::string
const& _reporterName ) { config.reporterNames.push_back( _reporterName ); }
5142 inline void addWarning( ConfigData& config, std::string
const& _warning ) {
5143 if( _warning ==
"NoAssertions" )
5144 config.warnings =
static_cast<WarnAbout::What
>( config.warnings | WarnAbout::NoAssertions );
5146 throw std::runtime_error(
"Unrecognised warning: '" + _warning +
'\'' );
5148 inline void setOrder( ConfigData& config, std::string
const& order ) {
5149 if( startsWith(
"declared", order ) )
5150 config.runOrder = RunTests::InDeclarationOrder;
5151 else if( startsWith(
"lexical", order ) )
5152 config.runOrder = RunTests::InLexicographicalOrder;
5153 else if( startsWith(
"random", order ) )
5154 config.runOrder = RunTests::InRandomOrder;
5156 throw std::runtime_error(
"Unrecognised ordering: '" + order +
'\'' );
5158 inline void setRngSeed( ConfigData& config, std::string
const& seed ) {
5159 if( seed ==
"time" ) {
5160 config.rngSeed =
static_cast<unsigned int>( std::time(0) );
5163 std::stringstream ss;
5165 ss >> config.rngSeed;
5167 throw std::runtime_error(
"Argument to --rng-seed should be the word 'time' or a number" );
5170 inline void setVerbosity( ConfigData& config,
int level ) {
5172 config.verbosity =
static_cast<Verbosity::Level
>( level );
5174 inline void setShowDurations( ConfigData& config,
bool _showDurations ) {
5175 config.showDurations = _showDurations
5176 ? ShowDurations::Always
5177 : ShowDurations::Never;
5179 inline void setUseColour( ConfigData& config, std::string
const& value ) {
5180 std::string mode = toLower( value );
5183 config.useColour = UseColour::Yes;
5184 else if( mode ==
"no" )
5185 config.useColour = UseColour::No;
5186 else if( mode ==
"auto" )
5187 config.useColour = UseColour::Auto;
5189 throw std::runtime_error(
"colour mode must be one of: auto, yes or no" );
5191 inline void forceColour( ConfigData& config ) {
5192 config.useColour = UseColour::Yes;
5194 inline void loadTestNamesFromFile( ConfigData& config, std::string
const& _filename ) {
5195 std::ifstream f( _filename.c_str() );
5197 throw std::domain_error(
"Unable to load input file: " + _filename );
5200 while( std::getline( f, line ) ) {
5202 if( !line.empty() && !startsWith( line,
'#' ) ) {
5203 if( !startsWith( line,
'"' ) )
5204 line =
'"' + line +
'"';
5205 addTestOrTags( config, line +
',' );
5210 inline Clara::CommandLine<ConfigData> makeCommandLineParser() {
5212 using namespace Clara;
5213 CommandLine<ConfigData> cli;
5215 cli.bindProcessName( &ConfigData::processName );
5217 cli["-?"]["-h"]["--help"]
5218 .describe(
"display usage information" )
5219 .bind( &ConfigData::showHelp );
5221 cli["-l"]["--list-tests"]
5222 .describe(
"list all/matching test cases" )
5223 .bind( &ConfigData::listTests );
5225 cli["-t"]["--list-tags"]
5226 .describe(
"list all/matching tags" )
5227 .bind( &ConfigData::listTags );
5229 cli["-s"]["--success"]
5230 .describe(
"include successful tests in output" )
5231 .bind( &ConfigData::showSuccessfulTests );
5233 cli["-b"]["--break"]
5234 .describe(
"break into debugger on failure" )
5235 .bind( &ConfigData::shouldDebugBreak );
5237 cli["-e"]["--nothrow"]
5238 .describe(
"skip exception tests" )
5239 .bind( &ConfigData::noThrow );
5241 cli["-i"]["--invisibles"]
5242 .describe(
"show invisibles (tabs, newlines)" )
5243 .bind( &ConfigData::showInvisibles );
5246 .describe(
"output filename" )
5247 .bind( &ConfigData::outputFilename,
"filename" );
5249 cli["-r"]["--reporter"]
5251 .describe(
"reporter to use (defaults to console)" )
5252 .bind( &addReporterName,
"name" );
5255 .describe(
"suite name" )
5256 .bind( &ConfigData::name,
"name" );
5258 cli["-a"]["--abort"]
5259 .describe(
"abort at first failure" )
5260 .bind( &abortAfterFirst );
5262 cli["-x"]["--abortx"]
5263 .describe(
"abort after x failures" )
5264 .bind( &abortAfterX,
"no. failures" );
5267 .describe(
"enable warnings" )
5268 .bind( &addWarning,
"warning name" );
5278 .describe(
"which test or tests to use" )
5279 .bind( &addTestOrTags,
"test name, pattern or tags" );
5281 cli["-d"]["--durations"]
5282 .describe(
"show test durations" )
5283 .bind( &setShowDurations,
"yes|no" );
5285 cli["-f"]["--input-file"]
5286 .describe(
"load test names to run from a file" )
5287 .bind( &loadTestNamesFromFile,
"filename" );
5289 cli["-#"]["--filenames-as-tags"]
5290 .describe(
"adds a tag for the filename" )
5291 .bind( &ConfigData::filenamesAsTags );
5293 cli["-c"]["--section"]
5294 .describe(
"specify section to run" )
5295 .bind( &addSectionToRun,
"section name" );
5298 cli["--list-test-names-only"]
5299 .describe(
"list all/matching test cases names only" )
5300 .bind( &ConfigData::listTestNamesOnly );
5302 cli["--list-extra-info"]
5303 .describe(
"list all/matching test cases with more info" )
5304 .bind( &ConfigData::listExtraInfo );
5306 cli["--list-reporters"]
5307 .describe(
"list all reporters" )
5308 .bind( &ConfigData::listReporters );
5311 .describe(
"test case order (defaults to decl)" )
5312 .bind( &setOrder,
"decl|lex|rand" );
5315 .describe(
"set a specific seed for random numbers" )
5316 .bind( &setRngSeed,
"'time'|number" );
5318 cli["--force-colour"]
5319 .describe(
"force colourised output (deprecated)" )
5320 .bind( &forceColour );
5323 .describe(
"should output be colourised" )
5324 .bind( &setUseColour,
"yes|no" );
5332 #define TWOBLUECUBES_CATCH_LIST_HPP_INCLUDED
5335 #define TWOBLUECUBES_CATCH_TEXT_H_INCLUDED
5337 #define TBC_TEXT_FORMAT_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH
5339 #define CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE Catch
5342 #ifndef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
5343 # ifdef TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED
5344 # ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
5345 # define TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
5348 # define TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED
5351 #ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
5357 #ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
5358 namespace CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE {
5363 #ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH
5364 const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH;
5366 const unsigned int consoleWidth = 80;
5369 struct TextAttributes {
5371 : initialIndent( std::string::npos ),
5373 width( consoleWidth-1 )
5376 TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value;
return *
this; }
5377 TextAttributes& setIndent( std::size_t _value ) { indent = _value;
return *
this; }
5378 TextAttributes& setWidth( std::size_t _value ) { width = _value;
return *
this; }
5380 std::size_t initialIndent;
5387 Text( std::string
const& _str, TextAttributes
const& _attr = TextAttributes() )
5390 const std::string wrappableBeforeChars =
"[({<\t";
5391 const std::string wrappableAfterChars =
"])}>-,./|\\";
5392 const std::string wrappableInsteadOfChars =
" \n\r";
5393 std::string indent = _attr.initialIndent != std::string::npos
5394 ? std::string( _attr.initialIndent,
' ' )
5395 : std::string( _attr.indent,
' ' );
5397 typedef std::string::const_iterator iterator;
5398 iterator it = _str.begin();
5399 const iterator strEnd = _str.end();
5401 while( it != strEnd ) {
5403 if( lines.size() >= 1000 ) {
5404 lines.push_back(
"... message truncated due to excessive size" );
5409 std::size_t width = (std::min)( static_cast<size_t>( strEnd-it ), _attr.width-static_cast<size_t>( indent.size() ) );
5410 iterator itEnd = it+width;
5411 iterator itNext = _str.end();
5413 iterator itNewLine = std::find( it, itEnd,
'\n' );
5414 if( itNewLine != itEnd )
5417 if( itEnd != strEnd ) {
5418 bool foundWrapPoint =
false;
5419 iterator findIt = itEnd;
5421 if( wrappableAfterChars.find( *findIt ) != std::string::npos && findIt != itEnd ) {
5424 foundWrapPoint =
true;
5426 else if( findIt > it && wrappableBeforeChars.find( *findIt ) != std::string::npos ) {
5429 foundWrapPoint =
true;
5431 else if( wrappableInsteadOfChars.find( *findIt ) != std::string::npos ) {
5434 foundWrapPoint =
true;
5441 while( !foundWrapPoint );
5443 if( !foundWrapPoint ) {
5450 while( itEnd > it && wrappableInsteadOfChars.find( *(itEnd-1) ) != std::string::npos )
5454 lines.push_back( indent + std::string( it, itEnd ) + suffix );
5456 if( indent.size() != _attr.indent )
5457 indent = std::string( _attr.indent,
' ' );
5462 typedef std::vector<std::string>::const_iterator const_iterator;
5464 const_iterator begin()
const {
return lines.begin(); }
5465 const_iterator end()
const {
return lines.end(); }
5466 std::string
const& last()
const {
return lines.back(); }
5467 std::size_t size()
const {
return lines.size(); }
5468 std::string
const& operator[]( std::size_t _index )
const {
return lines[_index]; }
5469 std::string toString()
const {
5470 std::ostringstream oss;
5475 inline friend std::ostream& operator << ( std::ostream& _stream, Text
const& _text ) {
5476 for( Text::const_iterator it = _text.begin(), itEnd = _text.end();
5477 it != itEnd; ++it ) {
5478 if( it != _text.begin() )
5487 TextAttributes attr;
5488 std::vector<std::string> lines;
5493 #ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
5497 #endif // TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
5498 #undef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
5502 using Tbc::TextAttributes;
5506 #define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_HPP_INCLUDED
5524 BrightRed = Bright | Red,
5525 BrightGreen = Bright | Green,
5526 LightGrey = Bright | Grey,
5527 BrightWhite = Bright | White,
5530 FileName = LightGrey,
5532 ResultError = BrightRed,
5533 ResultSuccess = BrightGreen,
5534 ResultExpectedFailure = Warning,
5539 OriginalExpression = Cyan,
5540 ReconstructedExpression = Yellow,
5542 SecondaryText = LightGrey,
5547 Colour( Code _colourCode );
5548 Colour( Colour
const& other );
5552 static void use( Code _colourCode );
5558 inline std::ostream& operator << ( std::ostream& os, Colour
const& ) {
return os; }
5563 #define TWOBLUECUBES_CATCH_INTERFACES_REPORTER_H_INCLUDED
5571 struct ReporterConfig {
5572 explicit ReporterConfig( Ptr<IConfig const>
const& _fullConfig )
5573 : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
5575 ReporterConfig( Ptr<IConfig const>
const& _fullConfig, std::ostream& _stream )
5576 : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
5578 std::ostream& stream()
const {
return *m_stream; }
5579 Ptr<IConfig const> fullConfig()
const {
return m_fullConfig; }
5582 std::ostream* m_stream;
5583 Ptr<IConfig const> m_fullConfig;
5586 struct ReporterPreferences {
5587 ReporterPreferences()
5588 : shouldRedirectStdOut( false )
5591 bool shouldRedirectStdOut;
5594 template<
typename T>
5595 struct LazyStat : Option<T> {
5596 LazyStat() : used( false ) {}
5597 LazyStat& operator=( T
const& _value ) {
5598 Option<T>::operator=( _value );
5609 struct TestRunInfo {
5610 TestRunInfo( std::string
const& _name ) : name( _name ) {}
5614 GroupInfo( std::string
const& _name,
5615 std::size_t _groupIndex,
5616 std::size_t _groupsCount )
5618 groupIndex( _groupIndex ),
5619 groupsCounts( _groupsCount )
5623 std::size_t groupIndex;
5624 std::size_t groupsCounts;
5627 struct AssertionStats {
5628 AssertionStats( AssertionResult
const& _assertionResult,
5629 std::vector<MessageInfo>
const& _infoMessages,
5630 Totals
const& _totals )
5631 : assertionResult( _assertionResult ),
5632 infoMessages( _infoMessages ),
5635 if( assertionResult.hasMessage() ) {
5638 MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
5639 builder << assertionResult.getMessage();
5640 builder.m_info.message = builder.m_stream.str();
5642 infoMessages.push_back( builder.m_info );
5645 virtual ~AssertionStats();
5647 # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
5648 AssertionStats( AssertionStats
const& ) =
default;
5649 AssertionStats( AssertionStats && ) =
default;
5650 AssertionStats& operator = ( AssertionStats
const& ) =
default;
5651 AssertionStats& operator = ( AssertionStats && ) =
default;
5654 AssertionResult assertionResult;
5655 std::vector<MessageInfo> infoMessages;
5659 struct SectionStats {
5660 SectionStats( SectionInfo
const& _sectionInfo,
5661 Counts
const& _assertions,
5662 double _durationInSeconds,
5663 bool _missingAssertions )
5664 : sectionInfo( _sectionInfo ),
5665 assertions( _assertions ),
5666 durationInSeconds( _durationInSeconds ),
5667 missingAssertions( _missingAssertions )
5669 virtual ~SectionStats();
5670 # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
5671 SectionStats( SectionStats
const& ) =
default;
5672 SectionStats( SectionStats && ) =
default;
5673 SectionStats& operator = ( SectionStats
const& ) =
default;
5674 SectionStats& operator = ( SectionStats && ) =
default;
5677 SectionInfo sectionInfo;
5679 double durationInSeconds;
5680 bool missingAssertions;
5683 struct TestCaseStats {
5684 TestCaseStats( TestCaseInfo
const& _testInfo,
5685 Totals
const& _totals,
5686 std::string
const& _stdOut,
5687 std::string
const& _stdErr,
5689 : testInfo( _testInfo ),
5693 aborting( _aborting )
5695 virtual ~TestCaseStats();
5697 # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
5698 TestCaseStats( TestCaseStats
const& ) =
default;
5699 TestCaseStats( TestCaseStats && ) =
default;
5700 TestCaseStats& operator = ( TestCaseStats
const& ) =
default;
5701 TestCaseStats& operator = ( TestCaseStats && ) =
default;
5704 TestCaseInfo testInfo;
5711 struct TestGroupStats {
5712 TestGroupStats( GroupInfo
const& _groupInfo,
5713 Totals
const& _totals,
5715 : groupInfo( _groupInfo ),
5717 aborting( _aborting )
5719 TestGroupStats( GroupInfo
const& _groupInfo )
5720 : groupInfo( _groupInfo ),
5723 virtual ~TestGroupStats();
5725 # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
5726 TestGroupStats( TestGroupStats
const& ) =
default;
5727 TestGroupStats( TestGroupStats && ) =
default;
5728 TestGroupStats& operator = ( TestGroupStats
const& ) =
default;
5729 TestGroupStats& operator = ( TestGroupStats && ) =
default;
5732 GroupInfo groupInfo;
5737 struct TestRunStats {
5738 TestRunStats( TestRunInfo
const& _runInfo,
5739 Totals
const& _totals,
5741 : runInfo( _runInfo ),
5743 aborting( _aborting )
5745 virtual ~TestRunStats();
5747 # ifndef CATCH_CONFIG_CPP11_GENERATED_METHODS
5748 TestRunStats( TestRunStats
const& _other )
5749 : runInfo( _other.runInfo ),
5750 totals( _other.totals ),
5751 aborting( _other.aborting )
5754 TestRunStats( TestRunStats
const& ) =
default;
5755 TestRunStats( TestRunStats && ) =
default;
5756 TestRunStats& operator = ( TestRunStats
const& ) =
default;
5757 TestRunStats& operator = ( TestRunStats && ) =
default;
5760 TestRunInfo runInfo;
5765 class MultipleReporters;
5767 struct IStreamingReporter : IShared {
5768 virtual ~IStreamingReporter();
5773 virtual ReporterPreferences getPreferences()
const = 0;
5775 virtual void noMatchingTestCases( std::string
const& spec ) = 0;
5777 virtual void testRunStarting( TestRunInfo
const& testRunInfo ) = 0;
5778 virtual void testGroupStarting( GroupInfo
const& groupInfo ) = 0;
5780 virtual void testCaseStarting( TestCaseInfo
const& testInfo ) = 0;
5781 virtual void sectionStarting( SectionInfo
const& sectionInfo ) = 0;
5783 virtual void assertionStarting( AssertionInfo
const& assertionInfo ) = 0;
5786 virtual bool assertionEnded( AssertionStats
const& assertionStats ) = 0;
5788 virtual void sectionEnded( SectionStats
const& sectionStats ) = 0;
5789 virtual void testCaseEnded( TestCaseStats
const& testCaseStats ) = 0;
5790 virtual void testGroupEnded( TestGroupStats
const& testGroupStats ) = 0;
5791 virtual void testRunEnded( TestRunStats
const& testRunStats ) = 0;
5793 virtual void skipTest( TestCaseInfo
const& testInfo ) = 0;
5795 virtual MultipleReporters* tryAsMulti() {
return CATCH_NULL; }
5798 struct IReporterFactory : IShared {
5799 virtual ~IReporterFactory();
5800 virtual IStreamingReporter* create( ReporterConfig
const& config )
const = 0;
5801 virtual std::string getDescription()
const = 0;
5804 struct IReporterRegistry {
5805 typedef std::map<std::string, Ptr<IReporterFactory> > FactoryMap;
5806 typedef std::vector<Ptr<IReporterFactory> > Listeners;
5808 virtual ~IReporterRegistry();
5809 virtual IStreamingReporter* create( std::string
const& name, Ptr<IConfig const>
const& config )
const = 0;
5810 virtual FactoryMap
const& getFactories()
const = 0;
5811 virtual Listeners
const& getListeners()
const = 0;
5814 Ptr<IStreamingReporter> addReporter( Ptr<IStreamingReporter>
const& existingReporter, Ptr<IStreamingReporter>
const& additionalReporter );
5819 #include <algorithm>
5823 inline std::size_t listTests( Config
const& config ) {
5825 TestSpec testSpec = config.testSpec();
5826 if( config.testSpec().hasFilters() )
5827 Catch::cout() <<
"Matching test cases:\n";
5829 Catch::cout() <<
"All available test cases:\n";
5833 std::size_t matchedTests = 0;
5834 TextAttributes nameAttr, descAttr, tagsAttr;
5835 nameAttr.setInitialIndent( 2 ).setIndent( 4 );
5836 descAttr.setIndent( 4 );
5837 tagsAttr.setIndent( 6 );
5839 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
5840 for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();
5844 TestCaseInfo
const& testCaseInfo = it->getTestCaseInfo();
5845 Colour::Code colour = testCaseInfo.isHidden()
5846 ? Colour::SecondaryText
5848 Colour colourGuard( colour );
5850 Catch::cout() << Text( testCaseInfo.name, nameAttr ) << std::endl;
5851 if( config.listExtraInfo() ) {
5852 Catch::cout() <<
" " << testCaseInfo.lineInfo << std::endl;
5853 std::string description = testCaseInfo.description;
5854 if( description.empty() )
5855 description =
"(NO DESCRIPTION)";
5856 Catch::cout() << Text( description, descAttr ) << std::endl;
5858 if( !testCaseInfo.tags.empty() )
5859 Catch::cout() << Text( testCaseInfo.tagsAsString, tagsAttr ) << std::endl;
5862 if( !config.testSpec().hasFilters() )
5863 Catch::cout() << pluralise( matchedTests,
"test case" ) <<
'\n' << std::endl;
5865 Catch::cout() << pluralise( matchedTests,
"matching test case" ) <<
'\n' << std::endl;
5866 return matchedTests;
5869 inline std::size_t listTestsNamesOnly( Config
const& config ) {
5870 TestSpec testSpec = config.testSpec();
5871 if( !config.testSpec().hasFilters() )
5873 std::size_t matchedTests = 0;
5874 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
5875 for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();
5879 TestCaseInfo
const& testCaseInfo = it->getTestCaseInfo();
5880 if( startsWith( testCaseInfo.name,
'#' ) )
5881 Catch::cout() <<
'"' << testCaseInfo.name <<
'"';
5883 Catch::cout() << testCaseInfo.name;
5884 if ( config.listExtraInfo() )
5885 Catch::cout() <<
"\t@" << testCaseInfo.lineInfo;
5886 Catch::cout() << std::endl;
5888 return matchedTests;
5892 TagInfo() : count ( 0 ) {}
5893 void add( std::string
const& spelling ) {
5895 spellings.insert( spelling );
5897 std::string all()
const {
5899 for( std::set<std::string>::const_iterator it = spellings.begin(), itEnd = spellings.end();
5902 out += "[" + *it + "]";
5905 std::set<std::string> spellings;
5909 inline std::size_t listTags( Config
const& config ) {
5910 TestSpec testSpec = config.testSpec();
5911 if( config.testSpec().hasFilters() )
5912 Catch::cout() <<
"Tags for matching test cases:\n";
5914 Catch::cout() <<
"All available tags:\n";
5918 std::map<std::string, TagInfo> tagCounts;
5920 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
5921 for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();
5924 for( std::set<std::string>::const_iterator tagIt = it->getTestCaseInfo().tags.begin(),
5925 tagItEnd = it->getTestCaseInfo().tags.end();
5928 std::string tagName = *tagIt;
5929 std::string lcaseTagName = toLower( tagName );
5930 std::map<std::string, TagInfo>::iterator countIt = tagCounts.find( lcaseTagName );
5931 if( countIt == tagCounts.end() )
5932 countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
5933 countIt->second.add( tagName );
5937 for( std::map<std::string, TagInfo>::const_iterator countIt = tagCounts.begin(),
5938 countItEnd = tagCounts.end();
5939 countIt != countItEnd;
5941 std::ostringstream oss;
5942 oss <<
" " << std::setw(2) << countIt->second.count <<
" ";
5943 Text wrapper( countIt->second.all(), TextAttributes()
5944 .setInitialIndent( 0 )
5945 .setIndent( oss.str().size() )
5946 .setWidth( CATCH_CONFIG_CONSOLE_WIDTH-10 ) );
5947 Catch::cout() << oss.str() << wrapper <<
'\n';
5949 Catch::cout() << pluralise( tagCounts.size(),
"tag" ) <<
'\n' << std::endl;
5950 return tagCounts.size();
5953 inline std::size_t listReporters( Config
const& ) {
5954 Catch::cout() <<
"Available reporters:\n";
5955 IReporterRegistry::FactoryMap
const& factories = getRegistryHub().getReporterRegistry().getFactories();
5956 IReporterRegistry::FactoryMap::const_iterator itBegin = factories.begin(), itEnd = factories.end(), it;
5957 std::size_t maxNameLen = 0;
5958 for(it = itBegin; it != itEnd; ++it )
5959 maxNameLen = (std::max)( maxNameLen, it->first.size() );
5961 for(it = itBegin; it != itEnd; ++it ) {
5962 Text wrapper( it->second->getDescription(), TextAttributes()
5963 .setInitialIndent( 0 )
5964 .setIndent( 7+maxNameLen )
5965 .setWidth( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) );
5966 Catch::cout() <<
" "
5969 << std::string( maxNameLen - it->first.size() + 2, ' ' )
5972 Catch::cout() << std::endl;
5973 return factories.size();
5976 inline Option<std::size_t> list( Config
const& config ) {
5977 Option<std::size_t> listedCount;
5978 if( config.listTests() || ( config.listExtraInfo() && !config.listTestNamesOnly() ) )
5979 listedCount = listedCount.valueOr(0) + listTests( config );
5980 if( config.listTestNamesOnly() )
5981 listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
5982 if( config.listTags() )
5983 listedCount = listedCount.valueOr(0) + listTags( config );
5984 if( config.listReporters() )
5985 listedCount = listedCount.valueOr(0) + listReporters( config );
5992 #define TWOBLUECUBES_CATCH_RUNNER_IMPL_HPP_INCLUDED
5995 #define TWOBLUECUBES_CATCH_TEST_CASE_TRACKER_HPP_INCLUDED
5997 #include <algorithm>
6001 #include <stdexcept>
6006 namespace TestCaseTracking {
6008 struct NameAndLocation {
6010 SourceLineInfo location;
6012 NameAndLocation( std::string
const& _name, SourceLineInfo
const& _location )
6014 location( _location )
6018 struct ITracker : SharedImpl<> {
6019 virtual ~ITracker();
6022 virtual NameAndLocation
const& nameAndLocation()
const = 0;
6025 virtual bool isComplete()
const = 0;
6026 virtual bool isSuccessfullyCompleted()
const = 0;
6027 virtual bool isOpen()
const = 0;
6028 virtual bool hasChildren()
const = 0;
6030 virtual ITracker& parent() = 0;
6033 virtual void close() = 0;
6034 virtual void fail() = 0;
6035 virtual void markAsNeedingAnotherRun() = 0;
6037 virtual void addChild( Ptr<ITracker>
const& child ) = 0;
6038 virtual ITracker* findChild( NameAndLocation
const& nameAndLocation ) = 0;
6039 virtual void openChild() = 0;
6042 virtual bool isSectionTracker()
const = 0;
6043 virtual bool isIndexTracker()
const = 0;
6046 class TrackerContext {
6054 Ptr<ITracker> m_rootTracker;
6055 ITracker* m_currentTracker;
6056 RunState m_runState;
6060 static TrackerContext& instance() {
6061 static TrackerContext s_instance;
6067 m_runState( NotStarted )
6070 ITracker& startRun();
6073 m_rootTracker.reset();
6075 m_runState = NotStarted;
6079 m_currentTracker = m_rootTracker.get();
6080 m_runState = Executing;
6082 void completeCycle() {
6083 m_runState = CompletedCycle;
6086 bool completedCycle()
const {
6087 return m_runState == CompletedCycle;
6089 ITracker& currentTracker() {
6090 return *m_currentTracker;
6092 void setCurrentTracker( ITracker* tracker ) {
6093 m_currentTracker = tracker;
6097 class TrackerBase :
public ITracker {
6104 CompletedSuccessfully,
6107 class TrackerHasName {
6108 NameAndLocation m_nameAndLocation;
6110 TrackerHasName( NameAndLocation
const& nameAndLocation ) : m_nameAndLocation( nameAndLocation ) {}
6111 bool operator ()( Ptr<ITracker>
const& tracker ) {
6113 tracker->nameAndLocation().name == m_nameAndLocation.name &&
6114 tracker->nameAndLocation().location == m_nameAndLocation.location;
6117 typedef std::vector<Ptr<ITracker> > Children;
6118 NameAndLocation m_nameAndLocation;
6119 TrackerContext& m_ctx;
6121 Children m_children;
6122 CycleState m_runState;
6124 TrackerBase( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
6125 : m_nameAndLocation( nameAndLocation ),
6128 m_runState( NotStarted )
6130 virtual ~TrackerBase();
6132 virtual NameAndLocation
const& nameAndLocation() const CATCH_OVERRIDE {
6133 return m_nameAndLocation;
6135 virtual bool isComplete() const CATCH_OVERRIDE {
6136 return m_runState == CompletedSuccessfully || m_runState == Failed;
6138 virtual bool isSuccessfullyCompleted() const CATCH_OVERRIDE {
6139 return m_runState == CompletedSuccessfully;
6141 virtual bool isOpen() const CATCH_OVERRIDE {
6142 return m_runState != NotStarted && !isComplete();
6144 virtual bool hasChildren() const CATCH_OVERRIDE {
6145 return !m_children.empty();
6148 virtual void addChild( Ptr<ITracker>
const& child ) CATCH_OVERRIDE {
6149 m_children.push_back( child );
6152 virtual ITracker* findChild( NameAndLocation
const& nameAndLocation ) CATCH_OVERRIDE {
6153 Children::const_iterator it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( nameAndLocation ) );
6154 return( it != m_children.end() )
6158 virtual ITracker& parent() CATCH_OVERRIDE {
6163 virtual void openChild() CATCH_OVERRIDE {
6164 if( m_runState != ExecutingChildren ) {
6165 m_runState = ExecutingChildren;
6167 m_parent->openChild();
6171 virtual bool isSectionTracker() const CATCH_OVERRIDE {
return false; }
6172 virtual bool isIndexTracker() const CATCH_OVERRIDE {
return false; }
6175 m_runState = Executing;
6178 m_parent->openChild();
6181 virtual void close() CATCH_OVERRIDE {
6184 while( &m_ctx.currentTracker() != this )
6185 m_ctx.currentTracker().close();
6187 switch( m_runState ) {
6189 case CompletedSuccessfully:
6191 throw std::logic_error(
"Illogical state" );
6193 case NeedsAnotherRun:
6197 m_runState = CompletedSuccessfully;
6199 case ExecutingChildren:
6200 if( m_children.empty() || m_children.back()->isComplete() )
6201 m_runState = CompletedSuccessfully;
6205 throw std::logic_error(
"Unexpected state" );
6208 m_ctx.completeCycle();
6210 virtual void fail() CATCH_OVERRIDE {
6211 m_runState = Failed;
6213 m_parent->markAsNeedingAnotherRun();
6215 m_ctx.completeCycle();
6217 virtual void markAsNeedingAnotherRun() CATCH_OVERRIDE {
6218 m_runState = NeedsAnotherRun;
6221 void moveToParent() {
6223 m_ctx.setCurrentTracker( m_parent );
6226 m_ctx.setCurrentTracker(
this );
6230 class SectionTracker :
public TrackerBase {
6231 std::vector<std::string> m_filters;
6233 SectionTracker( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
6234 : TrackerBase( nameAndLocation, ctx, parent )
6237 while( !parent->isSectionTracker() )
6238 parent = &parent->parent();
6240 SectionTracker& parentSection =
static_cast<SectionTracker&
>( *parent );
6241 addNextFilters( parentSection.m_filters );
6244 virtual ~SectionTracker();
6246 virtual bool isSectionTracker() const CATCH_OVERRIDE {
return true; }
6248 static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation
const& nameAndLocation ) {
6251 ITracker& currentTracker = ctx.currentTracker();
6252 if( ITracker* childTracker = currentTracker.findChild( nameAndLocation ) ) {
6253 assert( childTracker );
6254 assert( childTracker->isSectionTracker() );
6255 section =
static_cast<SectionTracker*
>( childTracker );
6258 section =
new SectionTracker( nameAndLocation, ctx, ¤tTracker );
6259 currentTracker.addChild( section );
6261 if( !ctx.completedCycle() )
6267 if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
6271 void addInitialFilters( std::vector<std::string>
const& filters ) {
6272 if( !filters.empty() ) {
6273 m_filters.push_back(
"");
6274 m_filters.push_back(
"");
6275 m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
6278 void addNextFilters( std::vector<std::string>
const& filters ) {
6279 if( filters.size() > 1 )
6280 m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
6284 class IndexTracker :
public TrackerBase {
6288 IndexTracker( NameAndLocation
const& nameAndLocation, TrackerContext& ctx, ITracker* parent,
int size )
6289 : TrackerBase( nameAndLocation, ctx, parent ),
6293 virtual ~IndexTracker();
6295 virtual bool isIndexTracker() const CATCH_OVERRIDE {
return true; }
6297 static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation
const& nameAndLocation,
int size ) {
6300 ITracker& currentTracker = ctx.currentTracker();
6301 if( ITracker* childTracker = currentTracker.findChild( nameAndLocation ) ) {
6302 assert( childTracker );
6303 assert( childTracker->isIndexTracker() );
6304 tracker =
static_cast<IndexTracker*
>( childTracker );
6307 tracker =
new IndexTracker( nameAndLocation, ctx, ¤tTracker, size );
6308 currentTracker.addChild( tracker );
6311 if( !ctx.completedCycle() && !tracker->isComplete() ) {
6312 if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
6313 tracker->moveNext();
6320 int index()
const {
return m_index; }
6327 virtual void close() CATCH_OVERRIDE {
6328 TrackerBase::close();
6329 if( m_runState == CompletedSuccessfully && m_index < m_size-1 )
6330 m_runState = Executing;
6334 inline ITracker& TrackerContext::startRun() {
6337 m_runState = Executing;
6338 return *m_rootTracker;
6343 using TestCaseTracking::ITracker;
6344 using TestCaseTracking::TrackerContext;
6345 using TestCaseTracking::SectionTracker;
6346 using TestCaseTracking::IndexTracker;
6353 #define TWOBLUECUBES_CATCH_FATAL_CONDITION_H_INCLUDED
6358 inline void reportFatal( std::string
const& message ) {
6359 IContext& context = Catch::getCurrentContext();
6360 IResultCapture* resultCapture = context.getResultCapture();
6361 resultCapture->handleFatalErrorCondition( message );
6366 #if defined ( CATCH_PLATFORM_WINDOWS )
6367 // #included from: catch_windows_h_proxy.h
6369 #define TWOBLUECUBES_CATCH_WINDOWS_H_PROXY_H_INCLUDED
6371 #ifdef CATCH_DEFINES_NOMINMAX
6374 #ifdef CATCH_DEFINES_WIN32_LEAN_AND_MEAN
6375 # define WIN32_LEAN_AND_MEAN
6381 #include <windows.h>
6384 #ifdef CATCH_DEFINES_NOMINMAX
6387 #ifdef CATCH_DEFINES_WIN32_LEAN_AND_MEAN
6388 # undef WIN32_LEAN_AND_MEAN
6392 # if !defined ( CATCH_CONFIG_WINDOWS_SEH )
6395 struct FatalConditionHandler {
6400 # else // CATCH_CONFIG_WINDOWS_SEH is defined
6404 struct SignalDefs { DWORD id;
const char* name; };
6405 extern SignalDefs signalDefs[];
6409 SignalDefs signalDefs[] = {
6410 { EXCEPTION_ILLEGAL_INSTRUCTION,
"SIGILL - Illegal instruction signal" },
6411 { EXCEPTION_STACK_OVERFLOW,
"SIGSEGV - Stack overflow" },
6412 { EXCEPTION_ACCESS_VIOLATION,
"SIGSEGV - Segmentation violation signal" },
6413 { EXCEPTION_INT_DIVIDE_BY_ZERO,
"Divide by zero error" },
6416 struct FatalConditionHandler {
6418 static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
6419 for (
int i = 0; i <
sizeof(signalDefs) /
sizeof(SignalDefs); ++i) {
6420 if (ExceptionInfo->ExceptionRecord->ExceptionCode == signalDefs[i].id) {
6421 reportFatal(signalDefs[i].name);
6426 return EXCEPTION_CONTINUE_SEARCH;
6429 FatalConditionHandler() {
6433 guaranteeSize = 32 * 1024;
6436 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
6438 SetThreadStackGuarantee(&guaranteeSize);
6441 static void reset() {
6444 RemoveVectoredExceptionHandler(exceptionHandlerHandle);
6445 SetThreadStackGuarantee(&guaranteeSize);
6451 ~FatalConditionHandler() {
6456 static ULONG guaranteeSize;
6457 static PVOID exceptionHandlerHandle;
6460 bool FatalConditionHandler::isSet =
false;
6461 ULONG FatalConditionHandler::guaranteeSize = 0;
6462 PVOID FatalConditionHandler::exceptionHandlerHandle =
CATCH_NULL;
6466 # endif // CATCH_CONFIG_WINDOWS_SEH
6468 #else // Not Windows - assumed to be POSIX compatible
6470 # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
6473 struct FatalConditionHandler {
6478 # else // CATCH_CONFIG_POSIX_SIGNALS is defined
6488 extern SignalDefs signalDefs[];
6489 SignalDefs signalDefs[] = {
6490 { SIGINT,
"SIGINT - Terminal interrupt signal" },
6491 { SIGILL,
"SIGILL - Illegal instruction signal" },
6492 { SIGFPE,
"SIGFPE - Floating point error signal" },
6493 { SIGSEGV,
"SIGSEGV - Segmentation violation signal" },
6494 { SIGTERM,
"SIGTERM - Termination request signal" },
6495 { SIGABRT,
"SIGABRT - Abort (abnormal termination) signal" }
6498 struct FatalConditionHandler {
6501 static struct sigaction oldSigActions [sizeof(signalDefs)/sizeof(SignalDefs)];
6502 static stack_t oldSigStack;
6503 static char altStackMem[SIGSTKSZ];
6505 static void handleSignal(
int sig ) {
6506 std::string name =
"<unknown signal>";
6507 for (std::size_t i = 0; i <
sizeof(signalDefs) /
sizeof(SignalDefs); ++i) {
6508 SignalDefs &def = signalDefs[i];
6509 if (sig == def.id) {
6519 FatalConditionHandler() {
6522 sigStack.ss_sp = altStackMem;
6523 sigStack.ss_size = SIGSTKSZ;
6524 sigStack.ss_flags = 0;
6525 sigaltstack(&sigStack, &oldSigStack);
6526 struct sigaction sa = { 0 };
6528 sa.sa_handler = handleSignal;
6529 sa.sa_flags = SA_ONSTACK;
6530 for (std::size_t i = 0; i <
sizeof(signalDefs)/
sizeof(SignalDefs); ++i) {
6531 sigaction(signalDefs[i].
id, &sa, &oldSigActions[i]);
6535 ~FatalConditionHandler() {
6538 static void reset() {
6541 for( std::size_t i = 0; i <
sizeof(signalDefs)/
sizeof(SignalDefs); ++i ) {
6542 sigaction(signalDefs[i].
id, &oldSigActions[i],
CATCH_NULL);
6551 bool FatalConditionHandler::isSet =
false;
6552 struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
6553 stack_t FatalConditionHandler::oldSigStack = {};
6554 char FatalConditionHandler::altStackMem[SIGSTKSZ] = {};
6558 # endif // CATCH_CONFIG_POSIX_SIGNALS
6560 #endif // not Windows
6567 class StreamRedirect {
6570 StreamRedirect( std::ostream& stream, std::string& targetString )
6571 : m_stream( stream ),
6572 m_prevBuf( stream.rdbuf() ),
6573 m_targetString( targetString )
6575 stream.rdbuf( m_oss.rdbuf() );
6579 m_targetString += m_oss.str();
6580 m_stream.rdbuf( m_prevBuf );
6584 std::ostream& m_stream;
6585 std::streambuf* m_prevBuf;
6586 std::ostringstream m_oss;
6587 std::string& m_targetString;
6593 class StdErrRedirect {
6595 StdErrRedirect(std::string& targetString)
6596 :m_cerrBuf( cerr().rdbuf() ), m_clogBuf(clog().rdbuf()),
6597 m_targetString(targetString){
6598 cerr().rdbuf(m_oss.rdbuf());
6599 clog().rdbuf(m_oss.rdbuf());
6602 m_targetString += m_oss.str();
6603 cerr().rdbuf(m_cerrBuf);
6604 clog().rdbuf(m_clogBuf);
6607 std::streambuf* m_cerrBuf;
6608 std::streambuf* m_clogBuf;
6609 std::ostringstream m_oss;
6610 std::string& m_targetString;
6615 class RunContext :
public IResultCapture,
public IRunner {
6617 RunContext( RunContext
const& );
6618 void operator =( RunContext
const& );
6622 explicit RunContext( Ptr<IConfig const>
const& _config, Ptr<IStreamingReporter>
const& reporter )
6623 : m_runInfo( _config->name() ),
6624 m_context( getCurrentMutableContext() ),
6626 m_config( _config ),
6627 m_reporter( reporter ),
6628 m_shouldReportUnexpected ( true )
6630 m_context.setRunner(
this );
6631 m_context.setConfig( m_config );
6632 m_context.setResultCapture(
this );
6633 m_reporter->testRunStarting( m_runInfo );
6636 virtual ~RunContext() {
6637 m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, aborting() ) );
6640 void testGroupStarting( std::string
const& testSpec, std::size_t groupIndex, std::size_t groupsCount ) {
6641 m_reporter->testGroupStarting( GroupInfo( testSpec, groupIndex, groupsCount ) );
6643 void testGroupEnded( std::string
const& testSpec, Totals
const& totals, std::size_t groupIndex, std::size_t groupsCount ) {
6644 m_reporter->testGroupEnded( TestGroupStats( GroupInfo( testSpec, groupIndex, groupsCount ), totals, aborting() ) );
6647 Totals runTest( TestCase
const& testCase ) {
6648 Totals prevTotals = m_totals;
6650 std::string redirectedCout;
6651 std::string redirectedCerr;
6653 TestCaseInfo testInfo = testCase.getTestCaseInfo();
6655 m_reporter->testCaseStarting( testInfo );
6657 m_activeTestCase = &testCase;
6660 ITracker& rootTracker = m_trackerContext.startRun();
6661 assert( rootTracker.isSectionTracker() );
6662 static_cast<SectionTracker&
>( rootTracker ).addInitialFilters( m_config->getSectionsToRun() );
6664 m_trackerContext.startCycle();
6665 m_testCaseTracker = &SectionTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( testInfo.name, testInfo.lineInfo ) );
6666 runCurrentTest( redirectedCout, redirectedCerr );
6668 while( !m_testCaseTracker->isSuccessfullyCompleted() && !aborting() );
6671 while( getCurrentContext().advanceGeneratorsForCurrentTest() && !aborting() );
6673 Totals deltaTotals = m_totals.delta( prevTotals );
6674 if( testInfo.expectedToFail() && deltaTotals.testCases.passed > 0 ) {
6675 deltaTotals.assertions.failed++;
6676 deltaTotals.testCases.passed--;
6677 deltaTotals.testCases.failed++;
6679 m_totals.testCases += deltaTotals.testCases;
6680 m_reporter->testCaseEnded( TestCaseStats( testInfo,
6692 Ptr<IConfig const> config()
const {
6698 virtual void assertionEnded( AssertionResult
const& result ) {
6699 if( result.getResultType() == ResultWas::Ok ) {
6700 m_totals.assertions.passed++;
6702 else if( !result.isOk() ) {
6703 m_totals.assertions.failed++;
6708 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
6711 m_lastAssertionInfo = AssertionInfo(
"", m_lastAssertionInfo.lineInfo,
"{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition );
6712 m_lastResult = result;
6715 virtual bool lastAssertionPassed()
6717 return m_totals.assertions.passed == (m_prevPassed + 1);
6720 virtual void assertionPassed()
6722 m_totals.assertions.passed++;
6723 m_lastAssertionInfo.capturedExpression =
"{Unknown expression after the reported line}";
6724 m_lastAssertionInfo.macroName =
"";
6727 virtual void assertionRun()
6729 m_prevPassed = m_totals.assertions.passed;
6732 virtual bool sectionStarted (
6733 SectionInfo
const& sectionInfo,
6737 ITracker& sectionTracker = SectionTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( sectionInfo.name, sectionInfo.lineInfo ) );
6738 if( !sectionTracker.isOpen() )
6740 m_activeSections.push_back( §ionTracker );
6742 m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
6744 m_reporter->sectionStarting( sectionInfo );
6746 assertions = m_totals.assertions;
6750 bool testForMissingAssertions( Counts& assertions ) {
6751 if( assertions.total() != 0 )
6753 if( !m_config->warnAboutMissingAssertions() )
6755 if( m_trackerContext.currentTracker().hasChildren() )
6757 m_totals.assertions.failed++;
6758 assertions.failed++;
6762 virtual void sectionEnded( SectionEndInfo
const& endInfo ) {
6763 Counts assertions = m_totals.assertions - endInfo.prevAssertions;
6764 bool missingAssertions = testForMissingAssertions( assertions );
6766 if( !m_activeSections.empty() ) {
6767 m_activeSections.back()->close();
6768 m_activeSections.pop_back();
6771 m_reporter->sectionEnded( SectionStats( endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions ) );
6775 virtual void sectionEndedEarly( SectionEndInfo
const& endInfo ) {
6776 if( m_unfinishedSections.empty() )
6777 m_activeSections.back()->fail();
6779 m_activeSections.back()->close();
6780 m_activeSections.pop_back();
6782 m_unfinishedSections.push_back( endInfo );
6785 virtual void pushScopedMessage( MessageInfo
const& message ) {
6786 m_messages.push_back( message );
6789 virtual void popScopedMessage( MessageInfo
const& message ) {
6790 m_messages.erase( std::remove( m_messages.begin(), m_messages.end(), message ), m_messages.end() );
6793 virtual std::string getCurrentTestName()
const {
6794 return m_activeTestCase
6795 ? m_activeTestCase->getTestCaseInfo().name
6799 virtual const AssertionResult* getLastResult()
const {
6800 return &m_lastResult;
6803 virtual void exceptionEarlyReported() {
6804 m_shouldReportUnexpected =
false;
6807 virtual void handleFatalErrorCondition( std::string
const& message ) {
6810 AssertionResultData tempResult;
6811 tempResult.resultType = ResultWas::FatalErrorCondition;
6812 tempResult.message = message;
6813 AssertionResult result(m_lastAssertionInfo, tempResult);
6815 getResultCapture().assertionEnded(result);
6817 handleUnfinishedSections();
6820 TestCaseInfo
const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
6821 SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description );
6824 assertions.failed = 1;
6825 SectionStats testCaseSectionStats( testCaseSection, assertions, 0,
false );
6826 m_reporter->sectionEnded( testCaseSectionStats );
6828 TestCaseInfo testInfo = m_activeTestCase->getTestCaseInfo();
6831 deltaTotals.testCases.failed = 1;
6832 deltaTotals.assertions.failed = 1;
6833 m_reporter->testCaseEnded( TestCaseStats( testInfo,
6838 m_totals.testCases.failed++;
6839 testGroupEnded( std::string(), m_totals, 1, 1 );
6840 m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals,
false ) );
6845 bool aborting()
const {
6846 return m_totals.assertions.failed ==
static_cast<std::size_t
>( m_config->abortAfter() );
6851 void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ) {
6852 TestCaseInfo
const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
6853 SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description );
6854 m_reporter->sectionStarting( testCaseSection );
6855 Counts prevAssertions = m_totals.assertions;
6856 double duration = 0;
6857 m_shouldReportUnexpected =
true;
6859 m_lastAssertionInfo = AssertionInfo(
"TEST_CASE", testCaseInfo.lineInfo,
"", ResultDisposition::Normal );
6861 seedRng( *m_config );
6865 if( m_reporter->getPreferences().shouldRedirectStdOut ) {
6866 StreamRedirect coutRedir( Catch::cout(), redirectedCout );
6867 StdErrRedirect errRedir( redirectedCerr );
6868 invokeActiveTestCase();
6871 invokeActiveTestCase();
6873 duration = timer.getElapsedSeconds();
6875 catch( TestFailureException& ) {
6881 if (m_shouldReportUnexpected) {
6882 makeUnexpectedResultBuilder().useActiveException();
6885 m_testCaseTracker->close();
6886 handleUnfinishedSections();
6889 Counts assertions = m_totals.assertions - prevAssertions;
6890 bool missingAssertions = testForMissingAssertions( assertions );
6892 if( testCaseInfo.okToFail() ) {
6893 std::swap( assertions.failedButOk, assertions.failed );
6894 m_totals.assertions.failed -= assertions.failedButOk;
6895 m_totals.assertions.failedButOk += assertions.failedButOk;
6898 SectionStats testCaseSectionStats( testCaseSection, assertions, duration, missingAssertions );
6899 m_reporter->sectionEnded( testCaseSectionStats );
6902 void invokeActiveTestCase() {
6903 FatalConditionHandler fatalConditionHandler;
6904 m_activeTestCase->invoke();
6905 fatalConditionHandler.reset();
6910 ResultBuilder makeUnexpectedResultBuilder()
const {
6911 return ResultBuilder( m_lastAssertionInfo.macroName,
6912 m_lastAssertionInfo.lineInfo,
6913 m_lastAssertionInfo.capturedExpression,
6914 m_lastAssertionInfo.resultDisposition );
6917 void handleUnfinishedSections() {
6920 for( std::vector<SectionEndInfo>::const_reverse_iterator it = m_unfinishedSections.rbegin(),
6921 itEnd = m_unfinishedSections.rend();
6924 sectionEnded( *it );
6925 m_unfinishedSections.clear();
6928 TestRunInfo m_runInfo;
6929 IMutableContext& m_context;
6930 TestCase
const* m_activeTestCase;
6931 ITracker* m_testCaseTracker;
6932 ITracker* m_currentSectionTracker;
6933 AssertionResult m_lastResult;
6935 Ptr<IConfig const> m_config;
6937 Ptr<IStreamingReporter> m_reporter;
6938 std::vector<MessageInfo> m_messages;
6939 AssertionInfo m_lastAssertionInfo;
6940 std::vector<SectionEndInfo> m_unfinishedSections;
6941 std::vector<ITracker*> m_activeSections;
6942 TrackerContext m_trackerContext;
6943 size_t m_prevPassed;
6944 bool m_shouldReportUnexpected;
6947 IResultCapture& getResultCapture() {
6948 if( IResultCapture* capture = getCurrentContext().getResultCapture() )
6951 throw std::logic_error(
"No result capture instance" );
6957 #define TWOBLUECUBES_CATCH_VERSION_H_INCLUDED
6963 Version(
unsigned int _majorVersion,
6964 unsigned int _minorVersion,
6965 unsigned int _patchNumber,
6966 char const *
const _branchName,
6967 unsigned int _buildNumber );
6969 unsigned int const majorVersion;
6970 unsigned int const minorVersion;
6971 unsigned int const patchNumber;
6974 char const *
const branchName;
6975 unsigned int const buildNumber;
6977 friend std::ostream& operator << ( std::ostream& os, Version
const& version );
6980 void operator=( Version
const& );
6983 inline Version libraryVersion();
6992 Ptr<IStreamingReporter> createReporter( std::string
const& reporterName, Ptr<Config>
const& config ) {
6993 Ptr<IStreamingReporter> reporter = getRegistryHub().getReporterRegistry().create( reporterName, config.get() );
6995 std::ostringstream oss;
6996 oss <<
"No reporter registered with name: '" << reporterName <<
"'";
6997 throw std::domain_error( oss.str() );
7002 #if !defined(CATCH_CONFIG_DEFAULT_REPORTER)
7003 #define CATCH_CONFIG_DEFAULT_REPORTER "console"
7006 Ptr<IStreamingReporter> makeReporter( Ptr<Config>
const& config ) {
7007 std::vector<std::string> reporters = config->getReporterNames();
7008 if( reporters.empty() )
7009 reporters.push_back( CATCH_CONFIG_DEFAULT_REPORTER );
7011 Ptr<IStreamingReporter> reporter;
7012 for( std::vector<std::string>::const_iterator it = reporters.begin(), itEnd = reporters.end();
7015 reporter = addReporter( reporter, createReporter( *it, config ) );
7018 Ptr<IStreamingReporter> addListeners( Ptr<IConfig const>
const& config, Ptr<IStreamingReporter> reporters ) {
7019 IReporterRegistry::Listeners listeners = getRegistryHub().getReporterRegistry().getListeners();
7020 for( IReporterRegistry::Listeners::const_iterator it = listeners.begin(), itEnd = listeners.end();
7023 reporters = addReporter(reporters, (*it)->create( ReporterConfig( config ) ) );
7027 Totals runTests( Ptr<Config>
const& config ) {
7029 Ptr<IConfig const> iconfig = config.get();
7031 Ptr<IStreamingReporter> reporter = makeReporter( config );
7032 reporter = addListeners( iconfig, reporter );
7034 RunContext context( iconfig, reporter );
7038 context.testGroupStarting( config->name(), 1, 1 );
7040 TestSpec testSpec = config->testSpec();
7041 if( !testSpec.hasFilters() )
7044 std::vector<TestCase>
const& allTestCases = getAllTestCasesSorted( *iconfig );
7045 for( std::vector<TestCase>::const_iterator it = allTestCases.begin(), itEnd = allTestCases.end();
7048 if( !context.aborting() && matchTest( *it, testSpec, *iconfig ) )
7049 totals += context.runTest( *it );
7051 reporter->skipTest( *it );
7054 context.testGroupEnded( iconfig->name(), totals, 1, 1 );
7058 void applyFilenamesAsTags( IConfig
const& config ) {
7059 std::vector<TestCase>
const& tests = getAllTestCasesSorted( config );
7060 for(std::size_t i = 0; i < tests.size(); ++i ) {
7061 TestCase& test =
const_cast<TestCase&
>( tests[i] );
7062 std::set<std::string> tags = test.tags;
7064 std::string filename = test.lineInfo.file;
7065 std::string::size_type lastSlash = filename.find_last_of(
"\\/" );
7066 if( lastSlash != std::string::npos )
7067 filename = filename.substr( lastSlash+1 );
7069 std::string::size_type lastDot = filename.find_last_of(
'.' );
7070 if( lastDot != std::string::npos )
7071 filename = filename.substr( 0, lastDot );
7073 tags.insert(
'#' + filename );
7074 setTags( test, tags );
7078 class Session : NonCopyable {
7079 static bool alreadyInstantiated;
7083 struct OnUnusedOptions {
enum DoWhat { Ignore, Fail }; };
7086 : m_cli( makeCommandLineParser() ) {
7087 if( alreadyInstantiated ) {
7088 std::string msg =
"Only one instance of Catch::Session can ever be used";
7089 Catch::cerr() << msg << std::endl;
7090 throw std::logic_error( msg );
7092 alreadyInstantiated =
true;
7098 void showHelp( std::string
const& processName ) {
7099 Catch::cout() <<
"\nCatch v" << libraryVersion() <<
"\n";
7101 m_cli.usage( Catch::cout(), processName );
7102 Catch::cout() <<
"For more detail usage please see the project docs\n" << std::endl;
7105 int applyCommandLine(
int argc,
char const*
const*
const argv, OnUnusedOptions::DoWhat unusedOptionBehaviour = OnUnusedOptions::Fail ) {
7107 m_cli.setThrowOnUnrecognisedTokens( unusedOptionBehaviour == OnUnusedOptions::Fail );
7108 m_unusedTokens = m_cli.parseInto( Clara::argsToVector( argc, argv ), m_configData );
7109 if( m_configData.showHelp )
7110 showHelp( m_configData.processName );
7113 catch( std::exception& ex ) {
7115 Colour colourGuard( Colour::Red );
7117 <<
"\nError(s) in input:\n"
7118 << Text( ex.what(), TextAttributes().setIndent(2) )
7121 m_cli.usage( Catch::cout(), m_configData.processName );
7122 return (std::numeric_limits<int>::max)();
7127 void useConfigData( ConfigData
const& _configData ) {
7128 m_configData = _configData;
7132 int run(
int argc,
char const*
const*
const argv ) {
7134 int returnCode = applyCommandLine( argc, argv );
7135 if( returnCode == 0 )
7140 #if defined(WIN32) && defined(UNICODE)
7141 int run(
int argc,
wchar_t const*
const*
const argv ) {
7143 char **utf8Argv =
new char *[ argc ];
7145 for (
int i = 0; i < argc; ++i ) {
7146 int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
7148 utf8Argv[ i ] =
new char[ bufSize ];
7150 WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
7153 int returnCode = applyCommandLine( argc, utf8Argv );
7154 if( returnCode == 0 )
7157 for (
int i = 0; i < argc; ++i )
7158 delete [] utf8Argv[ i ];
7167 if( m_configData.showHelp )
7174 seedRng( *m_config );
7176 if( m_configData.filenamesAsTags )
7177 applyFilenamesAsTags( *m_config );
7180 if( Option<std::size_t> listed = list( config() ) )
7181 return static_cast<int>( *listed );
7183 return static_cast<int>( runTests( m_config ).assertions.failed );
7185 catch( std::exception& ex ) {
7186 Catch::cerr() << ex.what() << std::endl;
7187 return (std::numeric_limits<int>::max)();
7191 Clara::CommandLine<ConfigData>
const& cli()
const {
7194 std::vector<Clara::Parser::Token>
const& unusedTokens()
const {
7195 return m_unusedTokens;
7197 ConfigData& configData() {
7198 return m_configData;
7202 m_config =
new Config( m_configData );
7206 Clara::CommandLine<ConfigData> m_cli;
7207 std::vector<Clara::Parser::Token> m_unusedTokens;
7208 ConfigData m_configData;
7209 Ptr<Config> m_config;
7212 bool Session::alreadyInstantiated =
false;
7217 #define TWOBLUECUBES_CATCH_REGISTRY_HUB_HPP_INCLUDED
7220 #define TWOBLUECUBES_CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED
7225 #include <algorithm>
7229 struct RandomNumberGenerator {
7230 typedef std::ptrdiff_t result_type;
7232 result_type operator()( result_type n )
const {
return std::rand() % n; }
7234 #ifdef CATCH_CONFIG_CPP11_SHUFFLE
7235 static constexpr result_type min() {
return 0; }
7236 static constexpr result_type max() {
return 1000000; }
7237 result_type operator()()
const {
return std::rand() % max(); }
7239 template<
typename V>
7240 static void shuffle( V& vector ) {
7241 RandomNumberGenerator rng;
7242 #ifdef CATCH_CONFIG_CPP11_SHUFFLE
7243 std::shuffle( vector.begin(), vector.end(), rng );
7245 std::random_shuffle( vector.begin(), vector.end(), rng );
7250 inline std::vector<TestCase> sortTests( IConfig
const& config, std::vector<TestCase>
const& unsortedTestCases ) {
7252 std::vector<TestCase> sorted = unsortedTestCases;
7254 switch( config.runOrder() ) {
7255 case RunTests::InLexicographicalOrder:
7256 std::sort( sorted.begin(), sorted.end() );
7258 case RunTests::InRandomOrder:
7261 RandomNumberGenerator::shuffle( sorted );
7264 case RunTests::InDeclarationOrder:
7270 bool matchTest( TestCase
const& testCase, TestSpec
const& testSpec, IConfig
const& config ) {
7271 return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
7274 void enforceNoDuplicateTestCases( std::vector<TestCase>
const& functions ) {
7275 std::set<TestCase> seenFunctions;
7276 for( std::vector<TestCase>::const_iterator it = functions.begin(), itEnd = functions.end();
7279 std::pair<std::set<TestCase>::const_iterator,
bool> prev = seenFunctions.insert( *it );
7280 if( !prev.second ) {
7281 std::ostringstream ss;
7283 ss << Colour( Colour::Red )
7284 <<
"error: TEST_CASE( \"" << it->name <<
"\" ) already defined.\n"
7285 <<
"\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo <<
'\n'
7286 <<
"\tRedefined at " << it->getTestCaseInfo().lineInfo << std::endl;
7288 throw std::runtime_error(ss.str());
7293 std::vector<TestCase> filterTests( std::vector<TestCase>
const& testCases, TestSpec
const& testSpec, IConfig
const& config ) {
7294 std::vector<TestCase> filtered;
7295 filtered.reserve( testCases.size() );
7296 for( std::vector<TestCase>::const_iterator it = testCases.begin(), itEnd = testCases.end();
7299 if( matchTest( *it, testSpec, config ) )
7300 filtered.push_back( *it );
7303 std::vector<TestCase>
const& getAllTestCasesSorted( IConfig
const& config ) {
7304 return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
7307 class TestRegistry :
public ITestCaseRegistry {
7310 : m_currentSortOrder( RunTests::InDeclarationOrder ),
7313 virtual ~TestRegistry();
7315 virtual void registerTest( TestCase
const& testCase ) {
7316 std::string name = testCase.getTestCaseInfo().name;
7317 if( name.empty() ) {
7318 std::ostringstream oss;
7319 oss <<
"Anonymous test case " << ++m_unnamedCount;
7320 return registerTest( testCase.withName( oss.str() ) );
7322 m_functions.push_back( testCase );
7325 virtual std::vector<TestCase>
const& getAllTests()
const {
7328 virtual std::vector<TestCase>
const& getAllTestsSorted( IConfig
const& config )
const {
7329 if( m_sortedFunctions.empty() )
7330 enforceNoDuplicateTestCases( m_functions );
7332 if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
7333 m_sortedFunctions = sortTests( config, m_functions );
7334 m_currentSortOrder = config.runOrder();
7336 return m_sortedFunctions;
7340 std::vector<TestCase> m_functions;
7341 mutable RunTests::InWhatOrder m_currentSortOrder;
7342 mutable std::vector<TestCase> m_sortedFunctions;
7343 size_t m_unnamedCount;
7344 std::ios_base::Init m_ostreamInit;
7349 class FreeFunctionTestCase :
public SharedImpl<ITestCase> {
7352 FreeFunctionTestCase( TestFunction fun ) : m_fun( fun ) {}
7354 virtual void invoke()
const {
7359 virtual ~FreeFunctionTestCase();
7364 inline std::string extractClassName( std::string
const& classOrQualifiedMethodName ) {
7365 std::string className = classOrQualifiedMethodName;
7366 if( startsWith( className,
'&' ) )
7368 std::size_t lastColons = className.rfind(
"::" );
7369 std::size_t penultimateColons = className.rfind(
"::", lastColons-1 );
7370 if( penultimateColons == std::string::npos )
7371 penultimateColons = 1;
7372 className = className.substr( penultimateColons, lastColons-penultimateColons );
7377 void registerTestCase
7378 ( ITestCase* testCase,
7379 char const* classOrQualifiedMethodName,
7380 NameAndDesc
const& nameAndDesc,
7381 SourceLineInfo
const& lineInfo ) {
7383 getMutableRegistryHub().registerTest
7386 extractClassName( classOrQualifiedMethodName ),
7388 nameAndDesc.description,
7391 void registerTestCaseFunction
7392 ( TestFunction
function,
7393 SourceLineInfo
const& lineInfo,
7394 NameAndDesc
const& nameAndDesc ) {
7395 registerTestCase(
new FreeFunctionTestCase(
function ),
"", nameAndDesc, lineInfo );
7401 ( TestFunction
function,
7402 SourceLineInfo
const& lineInfo,
7403 NameAndDesc
const& nameAndDesc ) {
7404 registerTestCaseFunction(
function, lineInfo, nameAndDesc );
7407 AutoReg::~AutoReg() {}
7412 #define TWOBLUECUBES_CATCH_REPORTER_REGISTRY_HPP_INCLUDED
7418 class ReporterRegistry :
public IReporterRegistry {
7422 virtual ~ReporterRegistry() CATCH_OVERRIDE {}
7424 virtual IStreamingReporter* create( std::string
const& name, Ptr<IConfig const>
const& config )
const CATCH_OVERRIDE {
7425 FactoryMap::const_iterator it = m_factories.find( name );
7426 if( it == m_factories.end() )
7428 return it->second->create( ReporterConfig( config ) );
7431 void registerReporter( std::string
const& name, Ptr<IReporterFactory>
const& factory ) {
7432 m_factories.insert( std::make_pair( name, factory ) );
7434 void registerListener( Ptr<IReporterFactory>
const& factory ) {
7435 m_listeners.push_back( factory );
7438 virtual FactoryMap
const& getFactories() const CATCH_OVERRIDE {
7441 virtual Listeners
const& getListeners() const CATCH_OVERRIDE {
7446 FactoryMap m_factories;
7447 Listeners m_listeners;
7452 #define TWOBLUECUBES_CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED
7455 #import "Foundation/Foundation.h"
7460 class ExceptionTranslatorRegistry :
public IExceptionTranslatorRegistry {
7462 ~ExceptionTranslatorRegistry() {
7463 deleteAll( m_translators );
7466 virtual void registerTranslator(
const IExceptionTranslator* translator ) {
7467 m_translators.push_back( translator );
7470 virtual std::string translateActiveException()
const {
7475 return tryTranslators();
7477 @catch (NSException *exception) {
7478 return Catch::toString( [exception description] );
7481 return tryTranslators();
7484 catch( TestFailureException& ) {
7487 catch( std::exception& ex ) {
7490 catch( std::string& msg ) {
7493 catch(
const char* msg ) {
7497 return "Unknown exception";
7501 std::string tryTranslators()
const {
7502 if( m_translators.empty() )
7505 return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() );
7509 std::vector<const IExceptionTranslator*> m_translators;
7514 #define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_H_INCLUDED
7520 class TagAliasRegistry :
public ITagAliasRegistry {
7522 virtual ~TagAliasRegistry();
7523 virtual Option<TagAlias> find( std::string
const& alias )
const;
7524 virtual std::string expandAliases( std::string
const& unexpandedTestSpec )
const;
7525 void add( std::string
const& alias, std::string
const& tag, SourceLineInfo
const& lineInfo );
7528 std::map<std::string, TagAlias> m_registry;
7537 class RegistryHub :
public IRegistryHub,
public IMutableRegistryHub {
7539 RegistryHub( RegistryHub
const& );
7540 void operator=( RegistryHub
const& );
7545 virtual IReporterRegistry
const& getReporterRegistry() const CATCH_OVERRIDE {
7546 return m_reporterRegistry;
7548 virtual ITestCaseRegistry
const& getTestCaseRegistry() const CATCH_OVERRIDE {
7549 return m_testCaseRegistry;
7551 virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() CATCH_OVERRIDE {
7552 return m_exceptionTranslatorRegistry;
7554 virtual ITagAliasRegistry
const& getTagAliasRegistry() const CATCH_OVERRIDE {
7555 return m_tagAliasRegistry;
7559 virtual void registerReporter( std::string
const& name, Ptr<IReporterFactory>
const& factory ) CATCH_OVERRIDE {
7560 m_reporterRegistry.registerReporter( name, factory );
7562 virtual void registerListener( Ptr<IReporterFactory>
const& factory ) CATCH_OVERRIDE {
7563 m_reporterRegistry.registerListener( factory );
7565 virtual void registerTest( TestCase
const& testInfo ) CATCH_OVERRIDE {
7566 m_testCaseRegistry.registerTest( testInfo );
7568 virtual void registerTranslator(
const IExceptionTranslator* translator ) CATCH_OVERRIDE {
7569 m_exceptionTranslatorRegistry.registerTranslator( translator );
7571 virtual void registerTagAlias( std::string
const& alias, std::string
const& tag, SourceLineInfo
const& lineInfo ) CATCH_OVERRIDE {
7572 m_tagAliasRegistry.add( alias, tag, lineInfo );
7576 TestRegistry m_testCaseRegistry;
7577 ReporterRegistry m_reporterRegistry;
7578 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
7579 TagAliasRegistry m_tagAliasRegistry;
7583 inline RegistryHub*& getTheRegistryHub() {
7584 static RegistryHub* theRegistryHub =
CATCH_NULL;
7585 if( !theRegistryHub )
7586 theRegistryHub =
new RegistryHub();
7587 return theRegistryHub;
7591 IRegistryHub& getRegistryHub() {
7592 return *getTheRegistryHub();
7594 IMutableRegistryHub& getMutableRegistryHub() {
7595 return *getTheRegistryHub();
7598 delete getTheRegistryHub();
7602 std::string translateActiveException() {
7603 return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
7609 #define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_HPP_INCLUDED
7615 NotImplementedException::NotImplementedException( SourceLineInfo
const& lineInfo )
7616 : m_lineInfo( lineInfo ) {
7617 std::ostringstream oss;
7618 oss << lineInfo <<
": function ";
7619 oss <<
"not implemented";
7623 const char* NotImplementedException::what() const CATCH_NOEXCEPT {
7624 return m_what.c_str();
7630 #define TWOBLUECUBES_CATCH_CONTEXT_IMPL_HPP_INCLUDED
7633 #define TWOBLUECUBES_CATCH_STREAM_HPP_INCLUDED
7635 #include <stdexcept>
7641 template<
typename WriterF,
size_t bufferSize=256>
7642 class StreamBufImpl :
public StreamBufBase {
7643 char data[bufferSize];
7648 setp( data, data +
sizeof(data) );
7651 ~StreamBufImpl() CATCH_NOEXCEPT {
7656 int overflow(
int c ) {
7660 if( pbase() == epptr() )
7661 m_writer( std::string( 1, static_cast<char>( c ) ) );
7663 sputc( static_cast<char>( c ) );
7669 if( pbase() != pptr() ) {
7670 m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
7671 setp( pbase(), epptr() );
7679 FileStream::FileStream( std::string
const& filename ) {
7680 m_ofs.open( filename.c_str() );
7681 if( m_ofs.fail() ) {
7682 std::ostringstream oss;
7683 oss <<
"Unable to open file: '" << filename <<
'\'';
7684 throw std::domain_error( oss.str() );
7688 std::ostream& FileStream::stream()
const {
7692 struct OutputDebugWriter {
7694 void operator()( std::string
const&str ) {
7695 writeToDebugConsole( str );
7699 DebugOutStream::DebugOutStream()
7700 : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
7701 m_os( m_streamBuf.
get() )
7704 std::ostream& DebugOutStream::stream()
const {
7710 CoutStream::CoutStream()
7711 : m_os( Catch::cout().rdbuf() )
7714 std::ostream& CoutStream::stream()
const {
7718 #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
7719 std::ostream& cout() {
7722 std::ostream& cerr() {
7725 std::ostream& clog() {
7733 class Context :
public IMutableContext {
7736 Context( Context
const& );
7737 void operator=( Context
const& );
7740 virtual ~Context() {
7741 deleteAllValues( m_generatorsByTestName );
7745 virtual IResultCapture* getResultCapture() {
7746 return m_resultCapture;
7748 virtual IRunner* getRunner() {
7751 virtual size_t getGeneratorIndex( std::string
const& fileInfo,
size_t totalSize ) {
7752 return getGeneratorsForCurrentTest()
7753 .getGeneratorInfo( fileInfo, totalSize )
7756 virtual bool advanceGeneratorsForCurrentTest() {
7757 IGeneratorsForTest* generators = findGeneratorsForCurrentTest();
7758 return generators && generators->moveNext();
7761 virtual Ptr<IConfig const> getConfig()
const {
7766 virtual void setResultCapture( IResultCapture* resultCapture ) {
7767 m_resultCapture = resultCapture;
7769 virtual void setRunner( IRunner* runner ) {
7772 virtual void setConfig( Ptr<IConfig const>
const& config ) {
7776 friend IMutableContext& getCurrentMutableContext();
7779 IGeneratorsForTest* findGeneratorsForCurrentTest() {
7780 std::string testName = getResultCapture()->getCurrentTestName();
7782 std::map<std::string, IGeneratorsForTest*>::const_iterator it =
7783 m_generatorsByTestName.find( testName );
7784 return it != m_generatorsByTestName.end()
7789 IGeneratorsForTest& getGeneratorsForCurrentTest() {
7790 IGeneratorsForTest* generators = findGeneratorsForCurrentTest();
7792 std::string testName = getResultCapture()->getCurrentTestName();
7793 generators = createGeneratorsForTest();
7794 m_generatorsByTestName.insert( std::make_pair( testName, generators ) );
7800 Ptr<IConfig const> m_config;
7802 IResultCapture* m_resultCapture;
7803 std::map<std::string, IGeneratorsForTest*> m_generatorsByTestName;
7809 IMutableContext& getCurrentMutableContext() {
7810 if( !currentContext )
7811 currentContext =
new Context();
7812 return *currentContext;
7814 IContext& getCurrentContext() {
7815 return getCurrentMutableContext();
7818 void cleanUpContext() {
7819 delete currentContext;
7825 #define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_IMPL_HPP_INCLUDED
7828 #define TWOBLUECUBES_CATCH_ERRNO_GUARD_HPP_INCLUDED
7836 ErrnoGuard():m_oldErrno(errno){}
7837 ~ErrnoGuard() { errno = m_oldErrno; }
7847 struct IColourImpl {
7848 virtual ~IColourImpl() {}
7849 virtual void use( Colour::Code _colourCode ) = 0;
7852 struct NoColourImpl : IColourImpl {
7853 void use( Colour::Code ) {}
7855 static IColourImpl* instance() {
7856 static NoColourImpl s_instance;
7864 #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
7865 # ifdef CATCH_PLATFORM_WINDOWS
7866 # define CATCH_CONFIG_COLOUR_WINDOWS
7868 # define CATCH_CONFIG_COLOUR_ANSI
7872 #if defined ( CATCH_CONFIG_COLOUR_WINDOWS )
7877 class Win32ColourImpl :
public IColourImpl {
7879 Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
7881 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
7882 GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
7883 originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
7884 originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
7887 virtual void use( Colour::Code _colourCode ) {
7888 switch( _colourCode ) {
7889 case Colour::None:
return setTextAttribute( originalForegroundAttributes );
7890 case Colour::White:
return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
7891 case Colour::Red:
return setTextAttribute( FOREGROUND_RED );
7892 case Colour::Green:
return setTextAttribute( FOREGROUND_GREEN );
7893 case Colour::Blue:
return setTextAttribute( FOREGROUND_BLUE );
7894 case Colour::Cyan:
return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
7895 case Colour::Yellow:
return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
7896 case Colour::Grey:
return setTextAttribute( 0 );
7898 case Colour::LightGrey:
return setTextAttribute( FOREGROUND_INTENSITY );
7899 case Colour::BrightRed:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
7900 case Colour::BrightGreen:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
7901 case Colour::BrightWhite:
return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
7903 case Colour::Bright:
throw std::logic_error(
"not a colour" );
7908 void setTextAttribute( WORD _textAttribute ) {
7909 SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
7911 HANDLE stdoutHandle;
7912 WORD originalForegroundAttributes;
7913 WORD originalBackgroundAttributes;
7916 IColourImpl* platformColourInstance() {
7917 static Win32ColourImpl s_instance;
7919 Ptr<IConfig const> config = getCurrentContext().getConfig();
7920 UseColour::YesOrNo colourMode = config
7921 ? config->useColour()
7923 if( colourMode == UseColour::Auto )
7924 colourMode = !isDebuggerActive()
7927 return colourMode == UseColour::Yes
7929 : NoColourImpl::instance();
7935 #elif defined( CATCH_CONFIG_COLOUR_ANSI )
7946 class PosixColourImpl :
public IColourImpl {
7948 virtual void use( Colour::Code _colourCode ) {
7949 switch( _colourCode ) {
7951 case Colour::White:
return setColour(
"[0m" );
7952 case Colour::Red:
return setColour(
"[0;31m" );
7953 case Colour::Green:
return setColour(
"[0;32m" );
7954 case Colour::Blue:
return setColour(
"[0;34m" );
7955 case Colour::Cyan:
return setColour(
"[0;36m" );
7956 case Colour::Yellow:
return setColour(
"[0;33m" );
7957 case Colour::Grey:
return setColour(
"[1;30m" );
7959 case Colour::LightGrey:
return setColour(
"[0;37m" );
7960 case Colour::BrightRed:
return setColour(
"[1;31m" );
7961 case Colour::BrightGreen:
return setColour(
"[1;32m" );
7962 case Colour::BrightWhite:
return setColour(
"[1;37m" );
7964 case Colour::Bright:
throw std::logic_error(
"not a colour" );
7967 static IColourImpl* instance() {
7968 static PosixColourImpl s_instance;
7973 void setColour(
const char* _escapeCode ) {
7974 Catch::cout() <<
'\033' << _escapeCode;
7978 IColourImpl* platformColourInstance() {
7980 Ptr<IConfig const> config = getCurrentContext().getConfig();
7981 UseColour::YesOrNo colourMode = config
7982 ? config->useColour()
7984 if( colourMode == UseColour::Auto )
7985 colourMode = (!isDebuggerActive() && isatty(STDOUT_FILENO) )
7988 return colourMode == UseColour::Yes
7989 ? PosixColourImpl::instance()
7990 : NoColourImpl::instance();
7996 #else // not Windows or ANSI
8000 static IColourImpl* platformColourInstance() {
return NoColourImpl::instance(); }
8004 #endif // Windows/ ANSI/ None
8008 Colour::Colour( Code _colourCode ) : m_moved( false ) { use( _colourCode ); }
8009 Colour::Colour( Colour
const& _other ) : m_moved( false ) {
const_cast<Colour&
>( _other ).m_moved =
true; }
8010 Colour::~Colour(){
if( !m_moved ) use( None ); }
8012 void Colour::use( Code _colourCode ) {
8013 static IColourImpl* impl = platformColourInstance();
8014 impl->use( _colourCode );
8020 #define TWOBLUECUBES_CATCH_GENERATORS_IMPL_HPP_INCLUDED
8028 struct GeneratorInfo : IGeneratorInfo {
8030 GeneratorInfo( std::size_t size )
8036 if( ++m_currentIndex == m_size ) {
8043 std::size_t getCurrentIndex()
const {
8044 return m_currentIndex;
8048 std::size_t m_currentIndex;
8053 class GeneratorsForTest :
public IGeneratorsForTest {
8056 ~GeneratorsForTest() {
8057 deleteAll( m_generatorsInOrder );
8060 IGeneratorInfo& getGeneratorInfo( std::string
const& fileInfo, std::size_t size ) {
8061 std::map<std::string, IGeneratorInfo*>::const_iterator it = m_generatorsByName.find( fileInfo );
8062 if( it == m_generatorsByName.end() ) {
8063 IGeneratorInfo* info =
new GeneratorInfo( size );
8064 m_generatorsByName.insert( std::make_pair( fileInfo, info ) );
8065 m_generatorsInOrder.push_back( info );
8072 std::vector<IGeneratorInfo*>::const_iterator it = m_generatorsInOrder.begin();
8073 std::vector<IGeneratorInfo*>::const_iterator itEnd = m_generatorsInOrder.end();
8074 for(; it != itEnd; ++it ) {
8075 if( (*it)->moveNext() )
8082 std::map<std::string, IGeneratorInfo*> m_generatorsByName;
8083 std::vector<IGeneratorInfo*> m_generatorsInOrder;
8086 IGeneratorsForTest* createGeneratorsForTest()
8088 return new GeneratorsForTest();
8094 #define TWOBLUECUBES_CATCH_ASSERTIONRESULT_HPP_INCLUDED
8098 AssertionInfo::AssertionInfo():macroName(
""), capturedExpression(
""), resultDisposition(ResultDisposition::Normal), secondArg(
""){}
8100 AssertionInfo::AssertionInfo(
char const * _macroName,
8101 SourceLineInfo
const& _lineInfo,
8102 char const * _capturedExpression,
8103 ResultDisposition::Flags _resultDisposition,
8104 char const * _secondArg)
8105 : macroName( _macroName ),
8106 lineInfo( _lineInfo ),
8107 capturedExpression( _capturedExpression ),
8108 resultDisposition( _resultDisposition ),
8109 secondArg( _secondArg )
8112 AssertionResult::AssertionResult() {}
8114 AssertionResult::AssertionResult( AssertionInfo
const& info, AssertionResultData
const& data )
8116 m_resultData( data )
8119 AssertionResult::~AssertionResult() {}
8122 bool AssertionResult::succeeded()
const {
8123 return Catch::isOk( m_resultData.resultType );
8127 bool AssertionResult::isOk()
const {
8128 return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
8131 ResultWas::OfType AssertionResult::getResultType()
const {
8132 return m_resultData.resultType;
8135 bool AssertionResult::hasExpression()
const {
8136 return m_info.capturedExpression[0] != 0;
8139 bool AssertionResult::hasMessage()
const {
8140 return !m_resultData.message.empty();
8143 std::string capturedExpressionWithSecondArgument(
char const * capturedExpression,
char const * secondArg ) {
8144 return (secondArg[0] == 0 || secondArg[0] ==
'"' && secondArg[1] ==
'"')
8145 ? capturedExpression
8146 : std::string(capturedExpression) + ", " + secondArg;
8149 std::string AssertionResult::getExpression()
const {
8150 if( isFalseTest( m_info.resultDisposition ) )
8151 return '!' + capturedExpressionWithSecondArgument(m_info.capturedExpression, m_info.secondArg);
8153 return capturedExpressionWithSecondArgument(m_info.capturedExpression, m_info.secondArg);
8155 std::string AssertionResult::getExpressionInMacro()
const {
8156 if( m_info.macroName[0] == 0 )
8157 return capturedExpressionWithSecondArgument(m_info.capturedExpression, m_info.secondArg);
8159 return std::string(m_info.macroName) + "( " + capturedExpressionWithSecondArgument(m_info.capturedExpression, m_info.secondArg) + " )";
8162 bool AssertionResult::hasExpandedExpression()
const {
8163 return hasExpression() && getExpandedExpression() != getExpression();
8166 std::string AssertionResult::getExpandedExpression()
const {
8167 return m_resultData.reconstructExpression();
8170 std::string AssertionResult::getMessage()
const {
8171 return m_resultData.message;
8173 SourceLineInfo AssertionResult::getSourceInfo()
const {
8174 return m_info.lineInfo;
8177 std::string AssertionResult::getTestMacroName()
const {
8178 return m_info.macroName;
8181 void AssertionResult::discardDecomposedExpression()
const {
8182 m_resultData.decomposedExpression =
CATCH_NULL;
8185 void AssertionResult::expandDecomposedExpression()
const {
8186 m_resultData.reconstructExpression();
8192 #define TWOBLUECUBES_CATCH_TEST_CASE_INFO_HPP_INCLUDED
8198 inline TestCaseInfo::SpecialProperties parseSpecialTag( std::string
const& tag ) {
8199 if( startsWith( tag,
'.' ) ||
8202 return TestCaseInfo::IsHidden;
8203 else if( tag ==
"!throws" )
8204 return TestCaseInfo::Throws;
8205 else if( tag ==
"!shouldfail" )
8206 return TestCaseInfo::ShouldFail;
8207 else if( tag ==
"!mayfail" )
8208 return TestCaseInfo::MayFail;
8209 else if( tag ==
"!nonportable" )
8210 return TestCaseInfo::NonPortable;
8212 return TestCaseInfo::None;
8214 inline bool isReservedTag( std::string
const& tag ) {
8215 return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( tag[0] );
8217 inline void enforceNotReservedTag( std::string
const& tag, SourceLineInfo
const& _lineInfo ) {
8218 if( isReservedTag( tag ) ) {
8219 std::ostringstream ss;
8220 ss << Colour(Colour::Red)
8221 <<
"Tag name [" << tag <<
"] not allowed.\n"
8222 <<
"Tag names starting with non alpha-numeric characters are reserved\n"
8223 << Colour(Colour::FileName)
8224 << _lineInfo <<
'\n';
8225 throw std::runtime_error(ss.str());
8229 TestCase makeTestCase( ITestCase* _testCase,
8230 std::string
const& _className,
8231 std::string
const& _name,
8232 std::string
const& _descOrTags,
8233 SourceLineInfo
const& _lineInfo )
8235 bool isHidden( startsWith( _name,
"./" ) );
8238 std::set<std::string> tags;
8239 std::string desc, tag;
8241 for( std::size_t i = 0; i < _descOrTags.size(); ++i ) {
8242 char c = _descOrTags[i];
8251 TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
8252 if( prop == TestCaseInfo::IsHidden )
8254 else if( prop == TestCaseInfo::None )
8255 enforceNotReservedTag( tag, _lineInfo );
8266 tags.insert(
"hide" );
8270 TestCaseInfo info( _name, _className, desc, tags, _lineInfo );
8271 return TestCase( _testCase, info );
8274 void setTags( TestCaseInfo& testCaseInfo, std::set<std::string>
const& tags )
8276 testCaseInfo.tags = tags;
8277 testCaseInfo.lcaseTags.clear();
8279 std::ostringstream oss;
8280 for( std::set<std::string>::const_iterator it = tags.begin(), itEnd = tags.end(); it != itEnd; ++it ) {
8281 oss <<
'[' << *it <<
']';
8282 std::string lcaseTag = toLower( *it );
8283 testCaseInfo.properties =
static_cast<TestCaseInfo::SpecialProperties
>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
8284 testCaseInfo.lcaseTags.insert( lcaseTag );
8286 testCaseInfo.tagsAsString = oss.str();
8289 TestCaseInfo::TestCaseInfo( std::string
const& _name,
8290 std::string
const& _className,
8291 std::string
const& _description,
8292 std::set<std::string>
const& _tags,
8293 SourceLineInfo
const& _lineInfo )
8295 className( _className ),
8296 description( _description ),
8297 lineInfo( _lineInfo ),
8300 setTags( *
this, _tags );
8303 TestCaseInfo::TestCaseInfo( TestCaseInfo
const& other )
8304 : name( other.name ),
8305 className( other.className ),
8306 description( other.description ),
8308 lcaseTags( other.lcaseTags ),
8309 tagsAsString( other.tagsAsString ),
8310 lineInfo( other.lineInfo ),
8311 properties( other.properties )
8314 bool TestCaseInfo::isHidden()
const {
8315 return ( properties & IsHidden ) != 0;
8317 bool TestCaseInfo::throws()
const {
8318 return ( properties & Throws ) != 0;
8320 bool TestCaseInfo::okToFail()
const {
8321 return ( properties & (ShouldFail | MayFail ) ) != 0;
8323 bool TestCaseInfo::expectedToFail()
const {
8324 return ( properties & (ShouldFail ) ) != 0;
8327 TestCase::TestCase( ITestCase* testCase, TestCaseInfo
const& info ) : TestCaseInfo( info ), test( testCase ) {}
8329 TestCase::TestCase( TestCase
const& other )
8330 : TestCaseInfo( other ),
8334 TestCase TestCase::withName( std::string
const& _newName )
const {
8335 TestCase other( *
this );
8336 other.name = _newName;
8340 void TestCase::swap( TestCase& other ) {
8341 test.swap( other.test );
8342 name.swap( other.name );
8343 className.swap( other.className );
8344 description.swap( other.description );
8345 tags.swap( other.tags );
8346 lcaseTags.swap( other.lcaseTags );
8347 tagsAsString.swap( other.tagsAsString );
8348 std::swap( TestCaseInfo::properties, static_cast<TestCaseInfo&>( other ).properties );
8349 std::swap( lineInfo, other.lineInfo );
8352 void TestCase::invoke()
const {
8357 return test.get() == other.test.get() &&
8358 name == other.name &&
8359 className == other.className;
8363 return name < other.name;
8365 TestCase& TestCase::operator = ( TestCase
const& other ) {
8366 TestCase temp( other );
8371 TestCaseInfo
const& TestCase::getTestCaseInfo()
const
8379 #define TWOBLUECUBES_CATCH_VERSION_HPP_INCLUDED
8384 (
unsigned int _majorVersion,
8385 unsigned int _minorVersion,
8386 unsigned int _patchNumber,
8387 char const *
const _branchName,
8388 unsigned int _buildNumber )
8389 : majorVersion( _majorVersion ),
8390 minorVersion( _minorVersion ),
8391 patchNumber( _patchNumber ),
8392 branchName( _branchName ),
8393 buildNumber( _buildNumber )
8396 std::ostream& operator << ( std::ostream& os, Version
const& version ) {
8397 os << version.majorVersion <<
'.'
8398 << version.minorVersion <<
'.'
8399 << version.patchNumber;
8401 if (version.branchName[0]) {
8402 os <<
'-' << version.branchName
8403 <<
'.' << version.buildNumber;
8408 inline Version libraryVersion() {
8409 static Version version( 1, 9, 7,
"", 0 );
8416 #define TWOBLUECUBES_CATCH_MESSAGE_HPP_INCLUDED
8420 MessageInfo::MessageInfo( std::string
const& _macroName,
8421 SourceLineInfo
const& _lineInfo,
8422 ResultWas::OfType _type )
8423 : macroName( _macroName ),
8424 lineInfo( _lineInfo ),
8426 sequence( ++globalCount )
8430 unsigned int MessageInfo::globalCount = 0;
8434 ScopedMessage::ScopedMessage( MessageBuilder
const& builder )
8435 : m_info( builder.m_info )
8437 m_info.message = builder.m_stream.str();
8438 getResultCapture().pushScopedMessage( m_info );
8440 ScopedMessage::ScopedMessage( ScopedMessage
const& other )
8441 : m_info( other.m_info )
8444 ScopedMessage::~ScopedMessage() {
8445 if ( !std::uncaught_exception() ){
8446 getResultCapture().popScopedMessage(m_info);
8453 #define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_HPP_INCLUDED
8456 #define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_H_INCLUDED
8461 struct IReporter : IShared {
8462 virtual ~IReporter();
8464 virtual bool shouldRedirectStdout()
const = 0;
8466 virtual void StartTesting() = 0;
8467 virtual void EndTesting( Totals
const& totals ) = 0;
8468 virtual void StartGroup( std::string
const& groupName ) = 0;
8469 virtual void EndGroup( std::string
const& groupName, Totals
const& totals ) = 0;
8470 virtual void StartTestCase( TestCaseInfo
const& testInfo ) = 0;
8471 virtual void EndTestCase( TestCaseInfo
const& testInfo, Totals
const& totals, std::string
const& stdOut, std::string
const& stdErr ) = 0;
8472 virtual void StartSection( std::string
const& sectionName, std::string
const& description ) = 0;
8473 virtual void EndSection( std::string
const& sectionName, Counts
const& assertions ) = 0;
8474 virtual void NoAssertionsInSection( std::string
const& sectionName ) = 0;
8475 virtual void NoAssertionsInTestCase( std::string
const& testName ) = 0;
8476 virtual void Aborted() = 0;
8477 virtual void Result( AssertionResult
const& result ) = 0;
8480 class LegacyReporterAdapter :
public SharedImpl<IStreamingReporter>
8483 LegacyReporterAdapter( Ptr<IReporter>
const& legacyReporter );
8484 virtual ~LegacyReporterAdapter();
8486 virtual ReporterPreferences getPreferences()
const;
8487 virtual void noMatchingTestCases( std::string
const& );
8488 virtual void testRunStarting( TestRunInfo
const& );
8489 virtual void testGroupStarting( GroupInfo
const& groupInfo );
8490 virtual void testCaseStarting( TestCaseInfo
const& testInfo );
8491 virtual void sectionStarting( SectionInfo
const& sectionInfo );
8492 virtual void assertionStarting( AssertionInfo
const& );
8493 virtual bool assertionEnded( AssertionStats
const& assertionStats );
8494 virtual void sectionEnded( SectionStats
const& sectionStats );
8495 virtual void testCaseEnded( TestCaseStats
const& testCaseStats );
8496 virtual void testGroupEnded( TestGroupStats
const& testGroupStats );
8497 virtual void testRunEnded( TestRunStats
const& testRunStats );
8498 virtual void skipTest( TestCaseInfo
const& );
8501 Ptr<IReporter> m_legacyReporter;
8507 LegacyReporterAdapter::LegacyReporterAdapter( Ptr<IReporter>
const& legacyReporter )
8508 : m_legacyReporter( legacyReporter )
8510 LegacyReporterAdapter::~LegacyReporterAdapter() {}
8512 ReporterPreferences LegacyReporterAdapter::getPreferences()
const {
8513 ReporterPreferences prefs;
8514 prefs.shouldRedirectStdOut = m_legacyReporter->shouldRedirectStdout();
8518 void LegacyReporterAdapter::noMatchingTestCases( std::string
const& ) {}
8519 void LegacyReporterAdapter::testRunStarting( TestRunInfo
const& ) {
8520 m_legacyReporter->StartTesting();
8522 void LegacyReporterAdapter::testGroupStarting( GroupInfo
const& groupInfo ) {
8523 m_legacyReporter->StartGroup( groupInfo.name );
8525 void LegacyReporterAdapter::testCaseStarting( TestCaseInfo
const& testInfo ) {
8526 m_legacyReporter->StartTestCase( testInfo );
8528 void LegacyReporterAdapter::sectionStarting( SectionInfo
const& sectionInfo ) {
8529 m_legacyReporter->StartSection( sectionInfo.name, sectionInfo.description );
8531 void LegacyReporterAdapter::assertionStarting( AssertionInfo
const& ) {
8535 bool LegacyReporterAdapter::assertionEnded( AssertionStats
const& assertionStats ) {
8536 if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) {
8537 for( std::vector<MessageInfo>::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end();
8540 if( it->type == ResultWas::Info ) {
8541 ResultBuilder rb( it->macroName.c_str(), it->lineInfo,
"", ResultDisposition::Normal );
8543 rb.setResultType( ResultWas::Info );
8544 AssertionResult result = rb.build();
8545 m_legacyReporter->Result( result );
8549 m_legacyReporter->Result( assertionStats.assertionResult );
8552 void LegacyReporterAdapter::sectionEnded( SectionStats
const& sectionStats ) {
8553 if( sectionStats.missingAssertions )
8554 m_legacyReporter->NoAssertionsInSection( sectionStats.sectionInfo.name );
8555 m_legacyReporter->EndSection( sectionStats.sectionInfo.name, sectionStats.assertions );
8557 void LegacyReporterAdapter::testCaseEnded( TestCaseStats
const& testCaseStats ) {
8558 m_legacyReporter->EndTestCase
8559 ( testCaseStats.testInfo,
8560 testCaseStats.totals,
8561 testCaseStats.stdOut,
8562 testCaseStats.stdErr );
8564 void LegacyReporterAdapter::testGroupEnded( TestGroupStats
const& testGroupStats ) {
8565 if( testGroupStats.aborting )
8566 m_legacyReporter->Aborted();
8567 m_legacyReporter->EndGroup( testGroupStats.groupInfo.name, testGroupStats.totals );
8569 void LegacyReporterAdapter::testRunEnded( TestRunStats
const& testRunStats ) {
8570 m_legacyReporter->EndTesting( testRunStats.totals );
8572 void LegacyReporterAdapter::skipTest( TestCaseInfo
const& ) {
8579 #pragma clang diagnostic push
8580 #pragma clang diagnostic ignored "-Wc++11-long-long"
8583 #ifdef CATCH_PLATFORM_WINDOWS
8587 #include <sys/time.h>
8594 #ifdef CATCH_PLATFORM_WINDOWS
8595 UInt64 getCurrentTicks() {
8596 static UInt64 hz=0, hzo=0;
8598 QueryPerformanceFrequency( reinterpret_cast<LARGE_INTEGER*>( &hz ) );
8599 QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER*>( &hzo ) );
8602 QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER*>( &t ) );
8603 return ((t-hzo)*1000000)/hz;
8606 UInt64 getCurrentTicks() {
8609 return static_cast<UInt64
>( t.tv_sec ) * 1000000ull + static_cast<UInt64>( t.tv_usec );
8614 void Timer::start() {
8615 m_ticks = getCurrentTicks();
8617 unsigned int Timer::getElapsedMicroseconds()
const {
8618 return static_cast<unsigned int>(getCurrentTicks() - m_ticks);
8620 unsigned int Timer::getElapsedMilliseconds()
const {
8621 return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
8623 double Timer::getElapsedSeconds()
const {
8624 return getElapsedMicroseconds()/1000000.0;
8630 #pragma clang diagnostic pop
8633 #define TWOBLUECUBES_CATCH_COMMON_HPP_INCLUDED
8640 bool startsWith( std::string
const& s, std::string
const& prefix ) {
8641 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
8643 bool startsWith( std::string
const& s,
char prefix ) {
8644 return !s.empty() && s[0] == prefix;
8646 bool endsWith( std::string
const& s, std::string
const& suffix ) {
8647 return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
8649 bool endsWith( std::string
const& s,
char suffix ) {
8650 return !s.empty() && s[s.size()-1] == suffix;
8652 bool contains( std::string
const& s, std::string
const& infix ) {
8653 return s.find( infix ) != std::string::npos;
8655 char toLowerCh(
char c) {
8656 return static_cast<char>( std::tolower( c ) );
8658 void toLowerInPlace( std::string& s ) {
8659 std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
8661 std::string toLower( std::string
const& s ) {
8663 toLowerInPlace( lc );
8666 std::string trim( std::string
const& str ) {
8667 static char const* whitespaceChars =
"\n\r\t ";
8668 std::string::size_type start = str.find_first_not_of( whitespaceChars );
8669 std::string::size_type end = str.find_last_not_of( whitespaceChars );
8671 return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
8674 bool replaceInPlace( std::string& str, std::string
const& replaceThis, std::string
const& withThis ) {
8675 bool replaced =
false;
8676 std::size_t i = str.find( replaceThis );
8677 while( i != std::string::npos ) {
8679 str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
8680 if( i < str.size()-withThis.size() )
8681 i = str.find( replaceThis, i+withThis.size() );
8683 i = std::string::npos;
8688 pluralise::pluralise( std::size_t count, std::string
const& label )
8693 std::ostream& operator << ( std::ostream& os, pluralise
const& pluraliser ) {
8694 os << pluraliser.m_count <<
' ' << pluraliser.m_label;
8695 if( pluraliser.m_count != 1 )
8700 SourceLineInfo::SourceLineInfo() : file(
""), line( 0 ){}
8701 SourceLineInfo::SourceLineInfo(
char const* _file, std::size_t _line )
8705 bool SourceLineInfo::empty()
const {
8706 return file[0] ==
'\0';
8709 return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
8712 return line < other.line || ( line == other.line && (std::strcmp(file, other.file) < 0));
8715 void seedRng( IConfig
const& config ) {
8716 if( config.rngSeed() != 0 )
8717 std::srand( config.rngSeed() );
8719 unsigned int rngSeed() {
8720 return getCurrentContext().getConfig()->rngSeed();
8723 std::ostream& operator << ( std::ostream& os, SourceLineInfo
const& info ) {
8725 os << info.file <<
'(' << info.line <<
')';
8727 os << info.file <<
':' << info.line;
8732 void throwLogicError( std::string
const& message, SourceLineInfo
const& locationInfo ) {
8733 std::ostringstream oss;
8734 oss << locationInfo <<
": Internal Catch error: '" << message <<
'\'';
8736 throw std::logic_error( oss.str() );
8741 #define TWOBLUECUBES_CATCH_SECTION_HPP_INCLUDED
8745 SectionInfo::SectionInfo
8746 ( SourceLineInfo
const& _lineInfo,
8747 std::string
const& _name,
8748 std::string
const& _description )
8750 description( _description ),
8751 lineInfo( _lineInfo )
8754 Section::Section( SectionInfo
const& info )
8756 m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
8761 #if defined(_MSC_VER)
8762 #pragma warning(push)
8763 #pragma warning(disable:4996) // std::uncaught_exception is deprecated in C++17
8765 Section::~Section() {
8766 if( m_sectionIncluded ) {
8767 SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() );
8768 if( std::uncaught_exception() )
8769 getResultCapture().sectionEndedEarly( endInfo );
8771 getResultCapture().sectionEnded( endInfo );
8774 #if defined(_MSC_VER)
8775 #pragma warning(pop)
8779 Section::operator bool()
const {
8780 return m_sectionIncluded;
8786 #define TWOBLUECUBES_CATCH_DEBUGGER_HPP_INCLUDED
8788 #ifdef CATCH_PLATFORM_MAC
8791 #include <stdbool.h>
8792 #include <sys/types.h>
8794 #include <sys/sysctl.h>
8803 bool isDebuggerActive(){
8806 struct kinfo_proc info;
8812 info.kp_proc.p_flag = 0;
8819 mib[2] = KERN_PROC_PID;
8824 size =
sizeof(info);
8825 if( sysctl(mib,
sizeof(mib) /
sizeof(*mib), &info, &size,
CATCH_NULL, 0) != 0 ) {
8826 Catch::cerr() <<
"\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
8832 return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
8836 #elif defined(CATCH_PLATFORM_LINUX)
8848 bool isDebuggerActive(){
8852 std::ifstream in(
"/proc/self/status");
8853 for( std::string line; std::getline(in, line); ) {
8854 static const int PREFIX_LEN = 11;
8855 if( line.compare(0, PREFIX_LEN,
"TracerPid:\t") == 0 ) {
8859 return line.length() > PREFIX_LEN && line[PREFIX_LEN] !=
'0';
8866 #elif defined(_MSC_VER)
8867 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
8869 bool isDebuggerActive() {
8870 return IsDebuggerPresent() != 0;
8873 #elif defined(__MINGW32__)
8874 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
8876 bool isDebuggerActive() {
8877 return IsDebuggerPresent() != 0;
8882 inline bool isDebuggerActive() {
return false; }
8886 #ifdef CATCH_PLATFORM_WINDOWS
8889 void writeToDebugConsole( std::string
const& text ) {
8890 ::OutputDebugStringA( text.c_str() );
8895 void writeToDebugConsole( std::string
const& text ) {
8897 Catch::cout() << text;
8903 #define TWOBLUECUBES_CATCH_TOSTRING_HPP_INCLUDED
8909 const std::string unprintableString =
"{?}";
8912 const int hexThreshold = 255;
8915 enum Arch { Big, Little };
8917 static Arch which() {
8920 char asChar[sizeof (int)];
8924 return ( u.asChar[
sizeof(
int)-1] == 1 ) ? Big : Little;
8929 std::string rawMemoryToString(
const void *
object, std::size_t size )
8932 int i = 0, end =
static_cast<int>( size ), inc = 1;
8933 if( Endianness::which() == Endianness::Little ) {
8938 unsigned char const *bytes =
static_cast<unsigned char const *
>(object);
8939 std::ostringstream os;
8940 os <<
"0x" << std::setfill(
'0') << std::hex;
8941 for( ; i != end; i += inc )
8942 os << std::setw(2) << static_cast<unsigned>(bytes[i]);
8947 std::string toString( std::string
const& value ) {
8948 std::string s = value;
8949 if( getCurrentContext().getConfig()->showInvisibles() ) {
8950 for(
size_t i = 0; i < s.size(); ++i ) {
8953 case '\n': subs =
"\\n";
break;
8954 case '\t': subs =
"\\t";
break;
8957 if( !subs.empty() ) {
8958 s = s.substr( 0, i ) + subs + s.substr( i+1 );
8963 return '"' + s + '"';
8965 std::string toString( std::wstring
const& value ) {
8968 s.reserve( value.size() );
8969 for(
size_t i = 0; i < value.size(); ++i )
8970 s += value[i] <= 0xff ? static_cast<char>( value[i] ) : '?';
8971 return Catch::toString( s );
8974 std::string toString(
const char*
const value ) {
8975 return value ? Catch::toString( std::string( value ) ) : std::string(
"{null string}" );
8978 std::string toString(
char*
const value ) {
8979 return Catch::toString( static_cast<const char*>( value ) );
8982 std::string toString(
const wchar_t*
const value )
8984 return value ? Catch::toString( std::wstring(value) ) : std::string(
"{null string}" );
8987 std::string toString(
wchar_t*
const value )
8989 return Catch::toString( static_cast<const wchar_t*>( value ) );
8992 std::string toString(
int value ) {
8993 std::ostringstream oss;
8995 if( value > Detail::hexThreshold )
8996 oss <<
" (0x" << std::hex << value <<
')';
9000 std::string toString(
unsigned long value ) {
9001 std::ostringstream oss;
9003 if( value > Detail::hexThreshold )
9004 oss <<
" (0x" << std::hex << value <<
')';
9008 std::string toString(
unsigned int value ) {
9009 return Catch::toString( static_cast<unsigned long>( value ) );
9012 template<
typename T>
9013 std::string fpToString( T value,
int precision ) {
9014 std::ostringstream oss;
9015 oss << std::setprecision( precision )
9018 std::string d = oss.str();
9019 std::size_t i = d.find_last_not_of(
'0' );
9020 if( i != std::string::npos && i != d.size()-1 ) {
9023 d = d.substr( 0, i+1 );
9028 std::string toString(
const double value ) {
9029 return fpToString( value, 10 );
9031 std::string toString(
const float value ) {
9032 return fpToString( value, 5 ) + 'f';
9035 std::string toString(
bool value ) {
9036 return value ?
"true" :
"false";
9039 std::string toString(
char value ) {
9040 if ( value ==
'\r' )
9042 if ( value ==
'\f' )
9044 if ( value ==
'\n' )
9046 if ( value ==
'\t' )
9048 if (
'\0' <= value && value <
' ' )
9049 return toString( static_cast<unsigned int>( value ) );
9050 char chstr[] =
"' '";
9055 std::string toString(
signed char value ) {
9056 return toString( static_cast<char>( value ) );
9059 std::string toString(
unsigned char value ) {
9060 return toString( static_cast<char>( value ) );
9063 #ifdef CATCH_CONFIG_CPP11_LONG_LONG
9064 std::string toString(
long long value ) {
9065 std::ostringstream oss;
9067 if( value > Detail::hexThreshold )
9068 oss <<
" (0x" << std::hex << value <<
')';
9071 std::string toString(
unsigned long long value ) {
9072 std::ostringstream oss;
9074 if( value > Detail::hexThreshold )
9075 oss <<
" (0x" << std::hex << value <<
')';
9080 #ifdef CATCH_CONFIG_CPP11_NULLPTR
9081 std::string toString( std::nullptr_t ) {
9087 std::string toString( NSString
const *
const& nsstring ) {
9090 return "@" + toString([nsstring UTF8String]);
9092 std::string toString( NSString * CATCH_ARC_STRONG & nsstring ) {
9095 return "@" + toString([nsstring UTF8String]);
9097 std::string toString( NSObject*
const& nsObject ) {
9098 return toString( [nsObject description] );
9105 #define TWOBLUECUBES_CATCH_RESULT_BUILDER_HPP_INCLUDED
9109 ResultBuilder::ResultBuilder(
char const* macroName,
9110 SourceLineInfo
const& lineInfo,
9111 char const* capturedExpression,
9112 ResultDisposition::Flags resultDisposition,
9113 char const* secondArg )
9114 : m_assertionInfo( macroName, lineInfo, capturedExpression, resultDisposition, secondArg ),
9115 m_shouldDebugBreak( false ),
9116 m_shouldThrow( false ),
9117 m_guardException( false ),
9118 m_usedStream( false )
9121 ResultBuilder::~ResultBuilder() {
9122 #if defined(CATCH_CONFIG_FAST_COMPILE)
9123 if ( m_guardException ) {
9124 stream().oss <<
"Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
9125 captureResult( ResultWas::ThrewException );
9126 getCurrentContext().getResultCapture()->exceptionEarlyReported();
9131 ResultBuilder& ResultBuilder::setResultType( ResultWas::OfType result ) {
9132 m_data.resultType = result;
9135 ResultBuilder& ResultBuilder::setResultType(
bool result ) {
9136 m_data.resultType = result ? ResultWas::Ok : ResultWas::ExpressionFailed;
9140 void ResultBuilder::endExpression( DecomposedExpression
const& expr ) {
9142 if( isFalseTest( m_assertionInfo.resultDisposition ) ) {
9143 m_data.negate( expr.isBinaryExpression() );
9146 getResultCapture().assertionRun();
9148 if(getCurrentContext().getConfig()->includeSuccessfulResults() || m_data.resultType != ResultWas::Ok)
9150 AssertionResult result = build( expr );
9151 handleResult( result );
9154 getResultCapture().assertionPassed();
9157 void ResultBuilder::useActiveException( ResultDisposition::Flags resultDisposition ) {
9158 m_assertionInfo.resultDisposition = resultDisposition;
9159 stream().oss << Catch::translateActiveException();
9160 captureResult( ResultWas::ThrewException );
9163 void ResultBuilder::captureResult( ResultWas::OfType resultType ) {
9164 setResultType( resultType );
9165 captureExpression();
9168 void ResultBuilder::captureExpectedException( std::string
const& expectedMessage ) {
9169 if( expectedMessage.empty() )
9170 captureExpectedException( Matchers::Impl::MatchAllOf<std::string>() );
9172 captureExpectedException( Matchers::Equals( expectedMessage ) );
9175 void ResultBuilder::captureExpectedException( Matchers::Impl::MatcherBase<std::string>
const& matcher ) {
9177 assert( !isFalseTest( m_assertionInfo.resultDisposition ) );
9178 AssertionResultData data = m_data;
9179 data.resultType = ResultWas::Ok;
9180 data.reconstructedExpression = capturedExpressionWithSecondArgument(m_assertionInfo.capturedExpression, m_assertionInfo.secondArg);
9182 std::string actualMessage = Catch::translateActiveException();
9183 if( !matcher.match( actualMessage ) ) {
9184 data.resultType = ResultWas::ExpressionFailed;
9185 data.reconstructedExpression = actualMessage;
9187 AssertionResult result( m_assertionInfo, data );
9188 handleResult( result );
9191 void ResultBuilder::captureExpression() {
9192 AssertionResult result = build();
9193 handleResult( result );
9196 void ResultBuilder::handleResult( AssertionResult
const& result )
9198 getResultCapture().assertionEnded( result );
9200 if( !result.isOk() ) {
9201 if( getCurrentContext().getConfig()->shouldDebugBreak() )
9202 m_shouldDebugBreak =
true;
9203 if( getCurrentContext().getRunner()->aborting() || (m_assertionInfo.resultDisposition & ResultDisposition::Normal) )
9204 m_shouldThrow =
true;
9208 void ResultBuilder::react() {
9209 #if defined(CATCH_CONFIG_FAST_COMPILE)
9210 if (m_shouldDebugBreak) {
9219 throw Catch::TestFailureException();
9222 bool ResultBuilder::shouldDebugBreak()
const {
return m_shouldDebugBreak; }
9223 bool ResultBuilder::allowThrows()
const {
return getCurrentContext().getConfig()->allowThrows(); }
9225 AssertionResult ResultBuilder::build()
const
9227 return build( *
this );
9236 AssertionResult ResultBuilder::build( DecomposedExpression
const& expr )
const
9238 assert( m_data.resultType != ResultWas::Unknown );
9239 AssertionResultData data = m_data;
9242 data.message = m_stream().oss.str();
9243 data.decomposedExpression = &expr;
9244 return AssertionResult( m_assertionInfo, data );
9247 void ResultBuilder::reconstructExpression( std::string& dest )
const {
9248 dest = capturedExpressionWithSecondArgument(m_assertionInfo.capturedExpression, m_assertionInfo.secondArg);
9251 void ResultBuilder::setExceptionGuard() {
9252 m_guardException =
true;
9254 void ResultBuilder::unsetExceptionGuard() {
9255 m_guardException =
false;
9261 #define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED
9265 TagAliasRegistry::~TagAliasRegistry() {}
9267 Option<TagAlias> TagAliasRegistry::find( std::string
const& alias )
const {
9268 std::map<std::string, TagAlias>::const_iterator it = m_registry.find( alias );
9269 if( it != m_registry.end() )
9272 return Option<TagAlias>();
9275 std::string TagAliasRegistry::expandAliases( std::string
const& unexpandedTestSpec )
const {
9276 std::string expandedTestSpec = unexpandedTestSpec;
9277 for( std::map<std::string, TagAlias>::const_iterator it = m_registry.begin(), itEnd = m_registry.end();
9280 std::size_t pos = expandedTestSpec.find( it->first );
9281 if( pos != std::string::npos ) {
9282 expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
9284 expandedTestSpec.substr( pos + it->first.size() );
9287 return expandedTestSpec;
9290 void TagAliasRegistry::add( std::string
const& alias, std::string
const& tag, SourceLineInfo
const& lineInfo ) {
9292 if( !startsWith( alias,
"[@" ) || !endsWith( alias,
']' ) ) {
9293 std::ostringstream oss;
9294 oss << Colour( Colour::Red )
9295 <<
"error: tag alias, \"" << alias <<
"\" is not of the form [@alias name].\n"
9296 << Colour( Colour::FileName )
9297 << lineInfo <<
'\n';
9298 throw std::domain_error( oss.str().c_str() );
9300 if( !m_registry.insert( std::make_pair( alias, TagAlias( tag, lineInfo ) ) ).second ) {
9301 std::ostringstream oss;
9302 oss << Colour( Colour::Red )
9303 <<
"error: tag alias, \"" << alias <<
"\" already registered.\n"
9304 <<
"\tFirst seen at "
9305 << Colour( Colour::Red ) << find(alias)->lineInfo <<
'\n'
9306 << Colour( Colour::Red ) <<
"\tRedefined at "
9307 << Colour( Colour::FileName) << lineInfo <<
'\n';
9308 throw std::domain_error( oss.str().c_str() );
9312 ITagAliasRegistry::~ITagAliasRegistry() {}
9315 return getRegistryHub().getTagAliasRegistry();
9318 RegistrarForTagAliases::RegistrarForTagAliases(
char const* alias,
char const* tag, SourceLineInfo
const& lineInfo ) {
9319 getMutableRegistryHub().registerTagAlias( alias, tag, lineInfo );
9327 namespace Matchers {
9329 namespace StdString {
9331 CasedString::CasedString( std::string
const& str, CaseSensitive::Choice caseSensitivity )
9332 : m_caseSensitivity( caseSensitivity ),
9333 m_str( adjustString( str ) )
9335 std::string CasedString::adjustString( std::string
const& str )
const {
9336 return m_caseSensitivity == CaseSensitive::No
9340 std::string CasedString::caseSensitivitySuffix()
const {
9341 return m_caseSensitivity == CaseSensitive::No
9342 ?
" (case insensitive)"
9346 StringMatcherBase::StringMatcherBase( std::string
const& operation, CasedString
const& comparator )
9347 : m_comparator( comparator ),
9348 m_operation( operation ) {
9351 std::string StringMatcherBase::describe()
const {
9352 std::string description;
9353 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
9354 m_comparator.caseSensitivitySuffix().size());
9355 description += m_operation;
9356 description += ": \"";
9357 description += m_comparator.m_str;
9358 description += "\"";
9359 description += m_comparator.caseSensitivitySuffix();
9363 EqualsMatcher::EqualsMatcher( CasedString
const& comparator ) : StringMatcherBase(
"equals", comparator ) {}
9365 bool EqualsMatcher::match( std::string
const& source )
const {
9366 return m_comparator.adjustString( source ) == m_comparator.m_str;
9369 ContainsMatcher::ContainsMatcher( CasedString
const& comparator ) : StringMatcherBase(
"contains", comparator ) {}
9371 bool ContainsMatcher::match( std::string
const& source )
const {
9372 return contains( m_comparator.adjustString( source ), m_comparator.m_str );
9375 StartsWithMatcher::StartsWithMatcher( CasedString
const& comparator ) : StringMatcherBase(
"starts with", comparator ) {}
9377 bool StartsWithMatcher::match( std::string
const& source )
const {
9378 return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
9381 EndsWithMatcher::EndsWithMatcher( CasedString
const& comparator ) : StringMatcherBase(
"ends with", comparator ) {}
9383 bool EndsWithMatcher::match( std::string
const& source )
const {
9384 return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
9389 StdString::EqualsMatcher Equals( std::string
const& str, CaseSensitive::Choice caseSensitivity ) {
9390 return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
9392 StdString::ContainsMatcher Contains( std::string
const& str, CaseSensitive::Choice caseSensitivity ) {
9393 return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
9395 StdString::EndsWithMatcher EndsWith( std::string
const& str, CaseSensitive::Choice caseSensitivity ) {
9396 return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
9398 StdString::StartsWithMatcher StartsWith( std::string
const& str, CaseSensitive::Choice caseSensitivity ) {
9399 return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
9405 #define TWOBLUECUBES_CATCH_REPORTER_MULTI_HPP_INCLUDED
9409 class MultipleReporters :
public SharedImpl<IStreamingReporter> {
9410 typedef std::vector<Ptr<IStreamingReporter> > Reporters;
9411 Reporters m_reporters;
9414 void add( Ptr<IStreamingReporter>
const& reporter ) {
9415 m_reporters.push_back( reporter );
9420 virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE {
9421 return m_reporters[0]->getPreferences();
9424 virtual void noMatchingTestCases( std::string
const& spec ) CATCH_OVERRIDE {
9425 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9428 (*it)->noMatchingTestCases( spec );
9431 virtual void testRunStarting( TestRunInfo
const& testRunInfo ) CATCH_OVERRIDE {
9432 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9435 (*it)->testRunStarting( testRunInfo );
9438 virtual void testGroupStarting( GroupInfo
const& groupInfo ) CATCH_OVERRIDE {
9439 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9442 (*it)->testGroupStarting( groupInfo );
9445 virtual void testCaseStarting( TestCaseInfo
const& testInfo ) CATCH_OVERRIDE {
9446 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9449 (*it)->testCaseStarting( testInfo );
9452 virtual void sectionStarting( SectionInfo
const& sectionInfo ) CATCH_OVERRIDE {
9453 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9456 (*it)->sectionStarting( sectionInfo );
9459 virtual void assertionStarting( AssertionInfo
const& assertionInfo ) CATCH_OVERRIDE {
9460 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9463 (*it)->assertionStarting( assertionInfo );
9467 virtual bool assertionEnded( AssertionStats
const& assertionStats ) CATCH_OVERRIDE {
9468 bool clearBuffer =
false;
9469 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9472 clearBuffer |= (*it)->assertionEnded( assertionStats );
9476 virtual void sectionEnded( SectionStats
const& sectionStats ) CATCH_OVERRIDE {
9477 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9480 (*it)->sectionEnded( sectionStats );
9483 virtual void testCaseEnded( TestCaseStats
const& testCaseStats ) CATCH_OVERRIDE {
9484 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9487 (*it)->testCaseEnded( testCaseStats );
9490 virtual void testGroupEnded( TestGroupStats
const& testGroupStats ) CATCH_OVERRIDE {
9491 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9494 (*it)->testGroupEnded( testGroupStats );
9497 virtual void testRunEnded( TestRunStats
const& testRunStats ) CATCH_OVERRIDE {
9498 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9501 (*it)->testRunEnded( testRunStats );
9504 virtual void skipTest( TestCaseInfo
const& testInfo ) CATCH_OVERRIDE {
9505 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9508 (*it)->skipTest( testInfo );
9511 virtual MultipleReporters* tryAsMulti() CATCH_OVERRIDE {
9517 Ptr<IStreamingReporter> addReporter( Ptr<IStreamingReporter>
const& existingReporter, Ptr<IStreamingReporter>
const& additionalReporter ) {
9518 Ptr<IStreamingReporter> resultingReporter;
9520 if( existingReporter ) {
9521 MultipleReporters* multi = existingReporter->tryAsMulti();
9523 multi =
new MultipleReporters;
9524 resultingReporter = Ptr<IStreamingReporter>( multi );
9525 if( existingReporter )
9526 multi->add( existingReporter );
9529 resultingReporter = existingReporter;
9530 multi->add( additionalReporter );
9533 resultingReporter = additionalReporter;
9535 return resultingReporter;
9541 #define TWOBLUECUBES_CATCH_REPORTER_XML_HPP_INCLUDED
9544 #define TWOBLUECUBES_CATCH_REPORTER_BASES_HPP_INCLUDED
9556 std::string getFormattedDuration(
double duration ) {
9561 const size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
9562 char buffer[maxDoubleSize];
9567 sprintf_s(buffer,
"%.3f", duration);
9569 sprintf(buffer,
"%.3f", duration);
9571 return std::string(buffer);
9575 struct StreamingReporterBase : SharedImpl<IStreamingReporter> {
9577 StreamingReporterBase( ReporterConfig
const& _config )
9578 : m_config( _config.fullConfig() ),
9579 stream( _config.stream() )
9581 m_reporterPrefs.shouldRedirectStdOut =
false;
9584 virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE {
9585 return m_reporterPrefs;
9588 virtual ~StreamingReporterBase() CATCH_OVERRIDE;
9590 virtual
void noMatchingTestCases( std::
string const& ) CATCH_OVERRIDE {}
9592 virtual void testRunStarting( TestRunInfo
const& _testRunInfo ) CATCH_OVERRIDE {
9593 currentTestRunInfo = _testRunInfo;
9595 virtual void testGroupStarting( GroupInfo
const& _groupInfo ) CATCH_OVERRIDE {
9596 currentGroupInfo = _groupInfo;
9599 virtual void testCaseStarting( TestCaseInfo
const& _testInfo ) CATCH_OVERRIDE {
9600 currentTestCaseInfo = _testInfo;
9602 virtual void sectionStarting( SectionInfo
const& _sectionInfo ) CATCH_OVERRIDE {
9603 m_sectionStack.push_back( _sectionInfo );
9606 virtual void sectionEnded( SectionStats
const& ) CATCH_OVERRIDE {
9607 m_sectionStack.pop_back();
9609 virtual void testCaseEnded( TestCaseStats
const& ) CATCH_OVERRIDE {
9610 currentTestCaseInfo.reset();
9612 virtual void testGroupEnded( TestGroupStats
const& ) CATCH_OVERRIDE {
9613 currentGroupInfo.reset();
9615 virtual void testRunEnded( TestRunStats
const& ) CATCH_OVERRIDE {
9616 currentTestCaseInfo.reset();
9617 currentGroupInfo.reset();
9618 currentTestRunInfo.reset();
9621 virtual void skipTest( TestCaseInfo
const& ) CATCH_OVERRIDE {
9626 Ptr<IConfig const> m_config;
9627 std::ostream& stream;
9629 LazyStat<TestRunInfo> currentTestRunInfo;
9630 LazyStat<GroupInfo> currentGroupInfo;
9631 LazyStat<TestCaseInfo> currentTestCaseInfo;
9633 std::vector<SectionInfo> m_sectionStack;
9634 ReporterPreferences m_reporterPrefs;
9637 struct CumulativeReporterBase : SharedImpl<IStreamingReporter> {
9638 template<
typename T,
typename ChildNodeT>
9639 struct Node : SharedImpl<> {
9640 explicit Node( T
const& _value ) : value( _value ) {}
9643 typedef std::vector<Ptr<ChildNodeT> > ChildNodes;
9645 ChildNodes children;
9647 struct SectionNode : SharedImpl<> {
9648 explicit SectionNode( SectionStats
const& _stats ) : stats( _stats ) {}
9649 virtual ~SectionNode();
9651 bool operator == ( SectionNode
const& other )
const {
9652 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
9654 bool operator == ( Ptr<SectionNode>
const& other )
const {
9659 typedef std::vector<Ptr<SectionNode> > ChildSections;
9660 typedef std::vector<AssertionStats> Assertions;
9661 ChildSections childSections;
9662 Assertions assertions;
9667 struct BySectionInfo {
9668 BySectionInfo( SectionInfo
const& other ) : m_other( other ) {}
9669 BySectionInfo( BySectionInfo
const& other ) : m_other( other.m_other ) {}
9670 bool operator() ( Ptr<SectionNode>
const& node )
const {
9671 return ((node->stats.sectionInfo.name == m_other.name) &&
9672 (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
9675 void operator=( BySectionInfo
const& );
9676 SectionInfo
const& m_other;
9679 typedef Node<TestCaseStats, SectionNode> TestCaseNode;
9680 typedef Node<TestGroupStats, TestCaseNode> TestGroupNode;
9681 typedef Node<TestRunStats, TestGroupNode> TestRunNode;
9683 CumulativeReporterBase( ReporterConfig
const& _config )
9684 : m_config( _config.fullConfig() ),
9685 stream( _config.stream() )
9687 m_reporterPrefs.shouldRedirectStdOut =
false;
9689 ~CumulativeReporterBase();
9691 virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE {
9692 return m_reporterPrefs;
9695 virtual void testRunStarting( TestRunInfo
const& ) CATCH_OVERRIDE {}
9696 virtual void testGroupStarting( GroupInfo
const& ) CATCH_OVERRIDE {}
9698 virtual void testCaseStarting( TestCaseInfo
const& ) CATCH_OVERRIDE {}
9700 virtual void sectionStarting( SectionInfo
const& sectionInfo ) CATCH_OVERRIDE {
9701 SectionStats incompleteStats( sectionInfo, Counts(), 0,
false );
9702 Ptr<SectionNode> node;
9703 if( m_sectionStack.empty() ) {
9704 if( !m_rootSection )
9705 m_rootSection =
new SectionNode( incompleteStats );
9706 node = m_rootSection;
9709 SectionNode& parentNode = *m_sectionStack.back();
9710 SectionNode::ChildSections::const_iterator it =
9711 std::find_if( parentNode.childSections.begin(),
9712 parentNode.childSections.end(),
9713 BySectionInfo( sectionInfo ) );
9714 if( it == parentNode.childSections.end() ) {
9715 node =
new SectionNode( incompleteStats );
9716 parentNode.childSections.push_back( node );
9721 m_sectionStack.push_back( node );
9722 m_deepestSection = node;
9725 virtual void assertionStarting( AssertionInfo
const& ) CATCH_OVERRIDE {}
9727 virtual bool assertionEnded( AssertionStats
const& assertionStats ) CATCH_OVERRIDE {
9728 assert( !m_sectionStack.empty() );
9729 SectionNode& sectionNode = *m_sectionStack.back();
9730 sectionNode.assertions.push_back( assertionStats );
9736 prepareExpandedExpression( sectionNode.assertions.back().assertionResult );
9739 virtual void sectionEnded( SectionStats
const& sectionStats ) CATCH_OVERRIDE {
9740 assert( !m_sectionStack.empty() );
9741 SectionNode& node = *m_sectionStack.back();
9742 node.stats = sectionStats;
9743 m_sectionStack.pop_back();
9745 virtual void testCaseEnded( TestCaseStats
const& testCaseStats ) CATCH_OVERRIDE {
9746 Ptr<TestCaseNode> node =
new TestCaseNode( testCaseStats );
9747 assert( m_sectionStack.size() == 0 );
9748 node->children.push_back( m_rootSection );
9749 m_testCases.push_back( node );
9750 m_rootSection.reset();
9752 assert( m_deepestSection );
9753 m_deepestSection->stdOut = testCaseStats.stdOut;
9754 m_deepestSection->stdErr = testCaseStats.stdErr;
9756 virtual void testGroupEnded( TestGroupStats
const& testGroupStats ) CATCH_OVERRIDE {
9757 Ptr<TestGroupNode> node =
new TestGroupNode( testGroupStats );
9758 node->children.swap( m_testCases );
9759 m_testGroups.push_back( node );
9761 virtual void testRunEnded( TestRunStats
const& testRunStats ) CATCH_OVERRIDE {
9762 Ptr<TestRunNode> node =
new TestRunNode( testRunStats );
9763 node->children.swap( m_testGroups );
9764 m_testRuns.push_back( node );
9765 testRunEndedCumulative();
9767 virtual void testRunEndedCumulative() = 0;
9769 virtual void skipTest( TestCaseInfo
const& ) CATCH_OVERRIDE {}
9771 virtual void prepareExpandedExpression( AssertionResult& result )
const {
9773 result.discardDecomposedExpression();
9775 result.expandDecomposedExpression();
9778 Ptr<IConfig const> m_config;
9779 std::ostream& stream;
9780 std::vector<AssertionStats> m_assertions;
9781 std::vector<std::vector<Ptr<SectionNode> > > m_sections;
9782 std::vector<Ptr<TestCaseNode> > m_testCases;
9783 std::vector<Ptr<TestGroupNode> > m_testGroups;
9785 std::vector<Ptr<TestRunNode> > m_testRuns;
9787 Ptr<SectionNode> m_rootSection;
9788 Ptr<SectionNode> m_deepestSection;
9789 std::vector<Ptr<SectionNode> > m_sectionStack;
9790 ReporterPreferences m_reporterPrefs;
9795 char const* getLineOfChars() {
9796 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
9798 std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
9799 line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
9804 struct TestEventListenerBase : StreamingReporterBase {
9805 TestEventListenerBase( ReporterConfig
const& _config )
9806 : StreamingReporterBase( _config )
9809 virtual void assertionStarting( AssertionInfo
const& ) CATCH_OVERRIDE {}
9810 virtual bool assertionEnded( AssertionStats
const& ) CATCH_OVERRIDE {
9818 #define TWOBLUECUBES_CATCH_REPORTER_REGISTRARS_HPP_INCLUDED
9822 template<
typename T>
9823 class LegacyReporterRegistrar {
9825 class ReporterFactory :
public IReporterFactory {
9826 virtual IStreamingReporter* create( ReporterConfig
const& config )
const {
9827 return new LegacyReporterAdapter(
new T( config ) );
9830 virtual std::string getDescription()
const {
9831 return T::getDescription();
9837 LegacyReporterRegistrar( std::string
const& name ) {
9838 getMutableRegistryHub().registerReporter( name,
new ReporterFactory() );
9842 template<
typename T>
9843 class ReporterRegistrar {
9845 class ReporterFactory :
public SharedImpl<IReporterFactory> {
9858 virtual IStreamingReporter* create( ReporterConfig
const& config )
const {
9859 return new T( config );
9862 virtual std::string getDescription()
const {
9863 return T::getDescription();
9869 ReporterRegistrar( std::string
const& name ) {
9870 getMutableRegistryHub().registerReporter( name,
new ReporterFactory() );
9874 template<
typename T>
9875 class ListenerRegistrar {
9877 class ListenerFactory :
public SharedImpl<IReporterFactory> {
9879 virtual IStreamingReporter* create( ReporterConfig
const& config )
const {
9880 return new T( config );
9882 virtual std::string getDescription()
const {
9883 return std::string();
9889 ListenerRegistrar() {
9890 getMutableRegistryHub().registerListener(
new ListenerFactory() );
9895 #define INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) \
9896 namespace{ Catch::LegacyReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); }
9898 #define INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) \
9899 namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); }
9902 #define INTERNAL_CATCH_REGISTER_LISTENER( listenerType ) \
9903 namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; }
9905 #define CATCH_REGISTER_LISTENER( listenerType ) \
9906 namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; }
9909 #define TWOBLUECUBES_CATCH_XMLWRITER_HPP_INCLUDED
9920 enum ForWhat { ForTextNodes, ForAttributes };
9922 XmlEncode( std::string
const& str, ForWhat forWhat = ForTextNodes )
9924 m_forWhat( forWhat )
9927 void encodeTo( std::ostream& os )
const {
9932 for( std::size_t i = 0; i < m_str.size(); ++ i ) {
9935 case '<': os <<
"<";
break;
9936 case '&': os <<
"&";
break;
9940 if( i > 2 && m_str[i-1] ==
']' && m_str[i-2] ==
']' )
9947 if( m_forWhat == ForAttributes )
9956 if ( ( c >= 0 && c <
'\x09' ) || ( c >
'\x0D' && c <
'\x20') || c==
'\x7F' ) {
9958 os <<
"\\x" << std::uppercase << std::hex << std::setfill(
'0') << std::setw(2)
9959 <<
static_cast<int>( c );
9967 friend std::ostream& operator << ( std::ostream& os, XmlEncode
const& xmlEncode ) {
9968 xmlEncode.encodeTo( os );
9980 class ScopedElement {
9982 ScopedElement( XmlWriter* writer )
9983 : m_writer( writer )
9986 ScopedElement( ScopedElement
const& other )
9987 : m_writer( other.m_writer ){
9993 m_writer->endElement();
9996 ScopedElement& writeText( std::string
const& text,
bool indent =
true ) {
9997 m_writer->writeText( text, indent );
10001 template<
typename T>
10002 ScopedElement& writeAttribute( std::string
const& name, T
const& attribute ) {
10003 m_writer->writeAttribute( name, attribute );
10008 mutable XmlWriter* m_writer;
10012 : m_tagIsOpen( false ),
10013 m_needsNewline( false ),
10014 m_os( Catch::cout() )
10016 writeDeclaration();
10019 XmlWriter( std::ostream& os )
10020 : m_tagIsOpen( false ),
10021 m_needsNewline( false ),
10024 writeDeclaration();
10028 while( !m_tags.empty() )
10032 XmlWriter& startElement( std::string
const& name ) {
10034 newlineIfNecessary();
10035 m_os << m_indent <<
'<' << name;
10036 m_tags.push_back( name );
10038 m_tagIsOpen =
true;
10042 ScopedElement scopedElement( std::string
const& name ) {
10043 ScopedElement scoped(
this );
10044 startElement( name );
10048 XmlWriter& endElement() {
10049 newlineIfNecessary();
10050 m_indent = m_indent.substr( 0, m_indent.size()-2 );
10051 if( m_tagIsOpen ) {
10053 m_tagIsOpen =
false;
10056 m_os << m_indent <<
"</" << m_tags.back() <<
">";
10063 XmlWriter& writeAttribute( std::string
const& name, std::string
const& attribute ) {
10064 if( !name.empty() && !attribute.empty() )
10065 m_os <<
' ' << name <<
"=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) <<
'"';
10069 XmlWriter& writeAttribute( std::string
const& name,
bool attribute ) {
10070 m_os <<
' ' << name <<
"=\"" << ( attribute ?
"true" :
"false" ) <<
'"';
10074 template<
typename T>
10075 XmlWriter& writeAttribute( std::string
const& name, T
const& attribute ) {
10076 std::ostringstream oss;
10078 return writeAttribute( name, oss.str() );
10081 XmlWriter& writeText( std::string
const& text,
bool indent =
true ) {
10082 if( !text.empty() ){
10083 bool tagWasOpen = m_tagIsOpen;
10085 if( tagWasOpen && indent )
10087 m_os << XmlEncode( text );
10088 m_needsNewline =
true;
10093 XmlWriter& writeComment( std::string
const& text ) {
10095 m_os << m_indent <<
"<!--" << text <<
"-->";
10096 m_needsNewline =
true;
10100 void writeStylesheetRef( std::string
const& url ) {
10101 m_os <<
"<?xml-stylesheet type=\"text/xsl\" href=\"" << url <<
"\"?>\n";
10104 XmlWriter& writeBlankLine() {
10110 void ensureTagClosed() {
10111 if( m_tagIsOpen ) {
10112 m_os <<
">" << std::endl;
10113 m_tagIsOpen =
false;
10118 XmlWriter( XmlWriter
const& );
10119 void operator=( XmlWriter
const& );
10121 void writeDeclaration() {
10122 m_os <<
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
10125 void newlineIfNecessary() {
10126 if( m_needsNewline ) {
10128 m_needsNewline =
false;
10133 bool m_needsNewline;
10134 std::vector<std::string> m_tags;
10135 std::string m_indent;
10136 std::ostream& m_os;
10142 class XmlReporter :
public StreamingReporterBase {
10144 XmlReporter( ReporterConfig
const& _config )
10145 : StreamingReporterBase( _config ),
10146 m_xml(_config.stream()),
10147 m_sectionDepth( 0 )
10149 m_reporterPrefs.shouldRedirectStdOut =
true;
10152 virtual ~XmlReporter() CATCH_OVERRIDE;
10154 static std::
string getDescription() {
10155 return "Reports test results as an XML document";
10158 virtual std::string getStylesheetRef()
const {
10159 return std::string();
10162 void writeSourceInfo( SourceLineInfo
const& sourceInfo ) {
10164 .writeAttribute(
"filename", sourceInfo.file )
10165 .writeAttribute(
"line", sourceInfo.line );
10170 virtual void noMatchingTestCases( std::string
const& s ) CATCH_OVERRIDE {
10171 StreamingReporterBase::noMatchingTestCases( s );
10174 virtual void testRunStarting( TestRunInfo
const& testInfo ) CATCH_OVERRIDE {
10175 StreamingReporterBase::testRunStarting( testInfo );
10176 std::string stylesheetRef = getStylesheetRef();
10177 if( !stylesheetRef.empty() )
10178 m_xml.writeStylesheetRef( stylesheetRef );
10179 m_xml.startElement(
"Catch" );
10180 if( !m_config->name().empty() )
10181 m_xml.writeAttribute(
"name", m_config->name() );
10184 virtual void testGroupStarting( GroupInfo
const& groupInfo ) CATCH_OVERRIDE {
10185 StreamingReporterBase::testGroupStarting( groupInfo );
10186 m_xml.startElement(
"Group" )
10187 .writeAttribute(
"name", groupInfo.name );
10190 virtual void testCaseStarting( TestCaseInfo
const& testInfo ) CATCH_OVERRIDE {
10191 StreamingReporterBase::testCaseStarting(testInfo);
10192 m_xml.startElement(
"TestCase" )
10193 .writeAttribute(
"name", trim( testInfo.name ) )
10194 .writeAttribute(
"description", testInfo.description )
10195 .writeAttribute(
"tags", testInfo.tagsAsString );
10197 writeSourceInfo( testInfo.lineInfo );
10199 if ( m_config->showDurations() == ShowDurations::Always )
10200 m_testCaseTimer.start();
10201 m_xml.ensureTagClosed();
10204 virtual void sectionStarting( SectionInfo
const& sectionInfo ) CATCH_OVERRIDE {
10205 StreamingReporterBase::sectionStarting( sectionInfo );
10206 if( m_sectionDepth++ > 0 ) {
10207 m_xml.startElement(
"Section" )
10208 .writeAttribute(
"name", trim( sectionInfo.name ) )
10209 .writeAttribute(
"description", sectionInfo.description );
10210 writeSourceInfo( sectionInfo.lineInfo );
10211 m_xml.ensureTagClosed();
10215 virtual void assertionStarting( AssertionInfo
const& ) CATCH_OVERRIDE { }
10217 virtual bool assertionEnded( AssertionStats
const& assertionStats ) CATCH_OVERRIDE {
10219 AssertionResult
const& result = assertionStats.assertionResult;
10221 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
10223 if( includeResults ) {
10225 for( std::vector<MessageInfo>::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end();
10228 if( it->type == ResultWas::Info ) {
10229 m_xml.scopedElement(
"Info" )
10230 .writeText( it->message );
10231 }
else if ( it->type == ResultWas::Warning ) {
10232 m_xml.scopedElement(
"Warning" )
10233 .writeText( it->message );
10239 if( !includeResults && result.getResultType() != ResultWas::Warning )
10243 if( result.hasExpression() ) {
10244 m_xml.startElement(
"Expression" )
10245 .writeAttribute(
"success", result.succeeded() )
10246 .writeAttribute(
"type", result.getTestMacroName() );
10248 writeSourceInfo( result.getSourceInfo() );
10250 m_xml.scopedElement(
"Original" )
10251 .writeText( result.getExpression() );
10252 m_xml.scopedElement(
"Expanded" )
10253 .writeText( result.getExpandedExpression() );
10257 switch( result.getResultType() ) {
10258 case ResultWas::ThrewException:
10259 m_xml.startElement(
"Exception" );
10260 writeSourceInfo( result.getSourceInfo() );
10261 m_xml.writeText( result.getMessage() );
10262 m_xml.endElement();
10264 case ResultWas::FatalErrorCondition:
10265 m_xml.startElement(
"FatalErrorCondition" );
10266 writeSourceInfo( result.getSourceInfo() );
10267 m_xml.writeText( result.getMessage() );
10268 m_xml.endElement();
10270 case ResultWas::Info:
10271 m_xml.scopedElement(
"Info" )
10272 .writeText( result.getMessage() );
10274 case ResultWas::Warning:
10277 case ResultWas::ExplicitFailure:
10278 m_xml.startElement(
"Failure" );
10279 writeSourceInfo( result.getSourceInfo() );
10280 m_xml.writeText( result.getMessage() );
10281 m_xml.endElement();
10287 if( result.hasExpression() )
10288 m_xml.endElement();
10293 virtual void sectionEnded( SectionStats
const& sectionStats ) CATCH_OVERRIDE {
10294 StreamingReporterBase::sectionEnded( sectionStats );
10295 if( --m_sectionDepth > 0 ) {
10296 XmlWriter::ScopedElement e = m_xml.scopedElement(
"OverallResults" );
10297 e.writeAttribute(
"successes", sectionStats.assertions.passed );
10298 e.writeAttribute(
"failures", sectionStats.assertions.failed );
10299 e.writeAttribute(
"expectedFailures", sectionStats.assertions.failedButOk );
10301 if ( m_config->showDurations() == ShowDurations::Always )
10302 e.writeAttribute(
"durationInSeconds", sectionStats.durationInSeconds );
10304 m_xml.endElement();
10308 virtual void testCaseEnded( TestCaseStats
const& testCaseStats ) CATCH_OVERRIDE {
10309 StreamingReporterBase::testCaseEnded( testCaseStats );
10310 XmlWriter::ScopedElement e = m_xml.scopedElement(
"OverallResult" );
10311 e.writeAttribute(
"success", testCaseStats.totals.assertions.allOk() );
10313 if ( m_config->showDurations() == ShowDurations::Always )
10314 e.writeAttribute(
"durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
10316 if( !testCaseStats.stdOut.empty() )
10317 m_xml.scopedElement(
"StdOut" ).writeText( trim( testCaseStats.stdOut ),
false );
10318 if( !testCaseStats.stdErr.empty() )
10319 m_xml.scopedElement(
"StdErr" ).writeText( trim( testCaseStats.stdErr ),
false );
10321 m_xml.endElement();
10324 virtual void testGroupEnded( TestGroupStats
const& testGroupStats ) CATCH_OVERRIDE {
10325 StreamingReporterBase::testGroupEnded( testGroupStats );
10327 m_xml.scopedElement(
"OverallResults" )
10328 .writeAttribute(
"successes", testGroupStats.totals.assertions.passed )
10329 .writeAttribute(
"failures", testGroupStats.totals.assertions.failed )
10330 .writeAttribute(
"expectedFailures", testGroupStats.totals.assertions.failedButOk );
10331 m_xml.endElement();
10334 virtual void testRunEnded( TestRunStats
const& testRunStats ) CATCH_OVERRIDE {
10335 StreamingReporterBase::testRunEnded( testRunStats );
10336 m_xml.scopedElement(
"OverallResults" )
10337 .writeAttribute(
"successes", testRunStats.totals.assertions.passed )
10338 .writeAttribute(
"failures", testRunStats.totals.assertions.failed )
10339 .writeAttribute(
"expectedFailures", testRunStats.totals.assertions.failedButOk );
10340 m_xml.endElement();
10344 Timer m_testCaseTimer;
10346 int m_sectionDepth;
10349 INTERNAL_CATCH_REGISTER_REPORTER(
"xml", XmlReporter )
10354 #define TWOBLUECUBES_CATCH_REPORTER_JUNIT_HPP_INCLUDED
10356 #include <assert.h>
10361 std::string getCurrentTimestamp() {
10365 std::time(&rawtime);
10366 const size_t timeStampSize =
sizeof(
"2017-01-16T17:06:45Z");
10369 std::tm timeInfo = {};
10370 gmtime_s(&timeInfo, &rawtime);
10373 timeInfo = std::gmtime(&rawtime);
10376 char timeStamp[timeStampSize];
10377 const char *
const fmt =
"%Y-%m-%dT%H:%M:%SZ";
10380 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
10382 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
10384 return std::string(timeStamp);
10389 class JunitReporter :
public CumulativeReporterBase {
10391 JunitReporter( ReporterConfig
const& _config )
10392 : CumulativeReporterBase( _config ),
10393 xml( _config.stream() ),
10394 unexpectedExceptions( 0 ),
10395 m_okToFail( false )
10397 m_reporterPrefs.shouldRedirectStdOut =
true;
10400 virtual ~JunitReporter() CATCH_OVERRIDE;
10402 static std::
string getDescription() {
10403 return "Reports test results in an XML format that looks like Ant's junitreport target";
10406 virtual void noMatchingTestCases( std::string
const& ) CATCH_OVERRIDE {}
10408 virtual void testRunStarting( TestRunInfo
const& runInfo ) CATCH_OVERRIDE {
10409 CumulativeReporterBase::testRunStarting( runInfo );
10410 xml.startElement(
"testsuites" );
10413 virtual void testGroupStarting( GroupInfo
const& groupInfo ) CATCH_OVERRIDE {
10414 suiteTimer.start();
10415 stdOutForSuite.str(
"");
10416 stdErrForSuite.str(
"");
10417 unexpectedExceptions = 0;
10418 CumulativeReporterBase::testGroupStarting( groupInfo );
10421 virtual void testCaseStarting( TestCaseInfo
const& testCaseInfo ) CATCH_OVERRIDE {
10422 m_okToFail = testCaseInfo.okToFail();
10424 virtual bool assertionEnded( AssertionStats
const& assertionStats ) CATCH_OVERRIDE {
10425 if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
10426 unexpectedExceptions++;
10427 return CumulativeReporterBase::assertionEnded( assertionStats );
10430 virtual void testCaseEnded( TestCaseStats
const& testCaseStats ) CATCH_OVERRIDE {
10431 stdOutForSuite << testCaseStats.stdOut;
10432 stdErrForSuite << testCaseStats.stdErr;
10433 CumulativeReporterBase::testCaseEnded( testCaseStats );
10436 virtual void testGroupEnded( TestGroupStats
const& testGroupStats ) CATCH_OVERRIDE {
10437 double suiteTime = suiteTimer.getElapsedSeconds();
10438 CumulativeReporterBase::testGroupEnded( testGroupStats );
10439 writeGroup( *m_testGroups.back(), suiteTime );
10442 virtual void testRunEndedCumulative() CATCH_OVERRIDE {
10446 void writeGroup( TestGroupNode
const& groupNode,
double suiteTime ) {
10447 XmlWriter::ScopedElement e = xml.scopedElement(
"testsuite" );
10448 TestGroupStats
const& stats = groupNode.value;
10449 xml.writeAttribute(
"name", stats.groupInfo.name );
10450 xml.writeAttribute(
"errors", unexpectedExceptions );
10451 xml.writeAttribute(
"failures", stats.totals.assertions.failed-unexpectedExceptions );
10452 xml.writeAttribute(
"tests", stats.totals.assertions.total() );
10453 xml.writeAttribute(
"hostname",
"tbd" );
10454 if( m_config->showDurations() == ShowDurations::Never )
10455 xml.writeAttribute(
"time",
"" );
10457 xml.writeAttribute(
"time", suiteTime );
10458 xml.writeAttribute(
"timestamp", getCurrentTimestamp() );
10461 for( TestGroupNode::ChildNodes::const_iterator
10462 it = groupNode.children.begin(), itEnd = groupNode.children.end();
10465 writeTestCase( **it );
10467 xml.scopedElement(
"system-out" ).writeText( trim( stdOutForSuite.str() ),
false );
10468 xml.scopedElement(
"system-err" ).writeText( trim( stdErrForSuite.str() ),
false );
10471 void writeTestCase( TestCaseNode
const& testCaseNode ) {
10472 TestCaseStats
const& stats = testCaseNode.value;
10476 assert( testCaseNode.children.size() == 1 );
10477 SectionNode
const& rootSection = *testCaseNode.children.front();
10479 std::string className = stats.testInfo.className;
10481 if( className.empty() ) {
10482 if( rootSection.childSections.empty() )
10483 className =
"global";
10485 writeSection( className,
"", rootSection );
10488 void writeSection( std::string
const& className,
10489 std::string
const& rootName,
10490 SectionNode
const& sectionNode ) {
10491 std::string name = trim( sectionNode.stats.sectionInfo.name );
10492 if( !rootName.empty() )
10493 name = rootName +
'/' + name;
10495 if( !sectionNode.assertions.empty() ||
10496 !sectionNode.stdOut.empty() ||
10497 !sectionNode.stdErr.empty() ) {
10498 XmlWriter::ScopedElement e = xml.scopedElement(
"testcase" );
10499 if( className.empty() ) {
10500 xml.writeAttribute(
"classname", name );
10501 xml.writeAttribute(
"name",
"root" );
10504 xml.writeAttribute(
"classname", className );
10505 xml.writeAttribute(
"name", name );
10507 xml.writeAttribute(
"time", Catch::toString( sectionNode.stats.durationInSeconds ) );
10509 writeAssertions( sectionNode );
10511 if( !sectionNode.stdOut.empty() )
10512 xml.scopedElement(
"system-out" ).writeText( trim( sectionNode.stdOut ),
false );
10513 if( !sectionNode.stdErr.empty() )
10514 xml.scopedElement(
"system-err" ).writeText( trim( sectionNode.stdErr ),
false );
10516 for( SectionNode::ChildSections::const_iterator
10517 it = sectionNode.childSections.begin(),
10518 itEnd = sectionNode.childSections.end();
10521 if( className.empty() )
10522 writeSection( name, "", **it );
10524 writeSection( className, name, **it );
10527 void writeAssertions( SectionNode
const& sectionNode ) {
10528 for( SectionNode::Assertions::const_iterator
10529 it = sectionNode.assertions.begin(), itEnd = sectionNode.assertions.end();
10532 writeAssertion( *it );
10534 void writeAssertion( AssertionStats
const& stats ) {
10535 AssertionResult
const& result = stats.assertionResult;
10536 if( !result.isOk() ) {
10537 std::string elementName;
10538 switch( result.getResultType() ) {
10539 case ResultWas::ThrewException:
10540 case ResultWas::FatalErrorCondition:
10541 elementName =
"error";
10543 case ResultWas::ExplicitFailure:
10544 elementName =
"failure";
10546 case ResultWas::ExpressionFailed:
10547 elementName =
"failure";
10549 case ResultWas::DidntThrowException:
10550 elementName =
"failure";
10554 case ResultWas::Info:
10555 case ResultWas::Warning:
10556 case ResultWas::Ok:
10557 case ResultWas::Unknown:
10558 case ResultWas::FailureBit:
10559 case ResultWas::Exception:
10560 elementName =
"internalError";
10564 XmlWriter::ScopedElement e = xml.scopedElement( elementName );
10566 xml.writeAttribute(
"message", result.getExpandedExpression() );
10567 xml.writeAttribute(
"type", result.getTestMacroName() );
10569 std::ostringstream oss;
10570 if( !result.getMessage().empty() )
10571 oss << result.getMessage() <<
'\n';
10572 for( std::vector<MessageInfo>::const_iterator
10573 it = stats.infoMessages.begin(),
10574 itEnd = stats.infoMessages.end();
10577 if( it->type == ResultWas::Info )
10578 oss << it->message << '\n';
10580 oss <<
"at " << result.getSourceInfo();
10581 xml.writeText( oss.str(), false );
10587 std::ostringstream stdOutForSuite;
10588 std::ostringstream stdErrForSuite;
10589 unsigned int unexpectedExceptions;
10593 INTERNAL_CATCH_REGISTER_REPORTER(
"junit", JunitReporter )
10598 #define TWOBLUECUBES_CATCH_REPORTER_CONSOLE_HPP_INCLUDED
10605 struct ConsoleReporter : StreamingReporterBase {
10606 ConsoleReporter( ReporterConfig
const& _config )
10607 : StreamingReporterBase( _config ),
10608 m_headerPrinted( false )
10611 virtual ~ConsoleReporter() CATCH_OVERRIDE;
10612 static std::
string getDescription() {
10613 return "Reports test results as plain lines of text";
10616 virtual void noMatchingTestCases( std::string
const& spec ) CATCH_OVERRIDE {
10617 stream <<
"No test cases matched '" << spec <<
'\'' << std::endl;
10620 virtual void assertionStarting( AssertionInfo
const& ) CATCH_OVERRIDE {
10623 virtual bool assertionEnded( AssertionStats
const& _assertionStats ) CATCH_OVERRIDE {
10624 AssertionResult
const& result = _assertionStats.assertionResult;
10626 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
10629 if( !includeResults && result.getResultType() != ResultWas::Warning )
10634 AssertionPrinter printer( stream, _assertionStats, includeResults );
10636 stream << std::endl;
10640 virtual void sectionStarting( SectionInfo
const& _sectionInfo ) CATCH_OVERRIDE {
10641 m_headerPrinted =
false;
10642 StreamingReporterBase::sectionStarting( _sectionInfo );
10644 virtual void sectionEnded( SectionStats
const& _sectionStats ) CATCH_OVERRIDE {
10645 if( _sectionStats.missingAssertions ) {
10647 Colour colour( Colour::ResultError );
10648 if( m_sectionStack.size() > 1 )
10649 stream <<
"\nNo assertions in section";
10651 stream <<
"\nNo assertions in test case";
10652 stream <<
" '" << _sectionStats.sectionInfo.name <<
"'\n" << std::endl;
10654 if( m_config->showDurations() == ShowDurations::Always ) {
10655 stream << getFormattedDuration(_sectionStats.durationInSeconds) <<
" s: " << _sectionStats.sectionInfo.name << std::endl;
10657 if( m_headerPrinted ) {
10658 m_headerPrinted =
false;
10660 StreamingReporterBase::sectionEnded( _sectionStats );
10663 virtual void testCaseEnded( TestCaseStats
const& _testCaseStats ) CATCH_OVERRIDE {
10664 StreamingReporterBase::testCaseEnded( _testCaseStats );
10665 m_headerPrinted =
false;
10667 virtual void testGroupEnded( TestGroupStats
const& _testGroupStats ) CATCH_OVERRIDE {
10668 if( currentGroupInfo.used ) {
10669 printSummaryDivider();
10670 stream <<
"Summary for group '" << _testGroupStats.groupInfo.name <<
"':\n";
10671 printTotals( _testGroupStats.totals );
10672 stream <<
'\n' << std::endl;
10674 StreamingReporterBase::testGroupEnded( _testGroupStats );
10676 virtual void testRunEnded( TestRunStats
const& _testRunStats ) CATCH_OVERRIDE {
10677 printTotalsDivider( _testRunStats.totals );
10678 printTotals( _testRunStats.totals );
10679 stream << std::endl;
10680 StreamingReporterBase::testRunEnded( _testRunStats );
10685 class AssertionPrinter {
10686 void operator= ( AssertionPrinter
const& );
10688 AssertionPrinter( std::ostream& _stream, AssertionStats
const& _stats,
bool _printInfoMessages )
10689 : stream( _stream ),
10691 result( _stats.assertionResult ),
10692 colour( Colour::None ),
10693 message( result.getMessage() ),
10694 messages( _stats.infoMessages ),
10695 printInfoMessages( _printInfoMessages )
10697 switch( result.getResultType() ) {
10698 case ResultWas::Ok:
10699 colour = Colour::Success;
10700 passOrFail =
"PASSED";
10702 if( _stats.infoMessages.size() == 1 )
10703 messageLabel =
"with message";
10704 if( _stats.infoMessages.size() > 1 )
10705 messageLabel =
"with messages";
10707 case ResultWas::ExpressionFailed:
10708 if( result.isOk() ) {
10709 colour = Colour::Success;
10710 passOrFail =
"FAILED - but was ok";
10713 colour = Colour::Error;
10714 passOrFail =
"FAILED";
10716 if( _stats.infoMessages.size() == 1 )
10717 messageLabel =
"with message";
10718 if( _stats.infoMessages.size() > 1 )
10719 messageLabel =
"with messages";
10721 case ResultWas::ThrewException:
10722 colour = Colour::Error;
10723 passOrFail =
"FAILED";
10724 messageLabel =
"due to unexpected exception with ";
10725 if (_stats.infoMessages.size() == 1)
10726 messageLabel +=
"message";
10727 if (_stats.infoMessages.size() > 1)
10728 messageLabel +=
"messages";
10730 case ResultWas::FatalErrorCondition:
10731 colour = Colour::Error;
10732 passOrFail =
"FAILED";
10733 messageLabel =
"due to a fatal error condition";
10735 case ResultWas::DidntThrowException:
10736 colour = Colour::Error;
10737 passOrFail =
"FAILED";
10738 messageLabel =
"because no exception was thrown where one was expected";
10740 case ResultWas::Info:
10741 messageLabel =
"info";
10743 case ResultWas::Warning:
10744 messageLabel =
"warning";
10746 case ResultWas::ExplicitFailure:
10747 passOrFail =
"FAILED";
10748 colour = Colour::Error;
10749 if( _stats.infoMessages.size() == 1 )
10750 messageLabel =
"explicitly with message";
10751 if( _stats.infoMessages.size() > 1 )
10752 messageLabel =
"explicitly with messages";
10755 case ResultWas::Unknown:
10756 case ResultWas::FailureBit:
10757 case ResultWas::Exception:
10758 passOrFail =
"** internal error **";
10759 colour = Colour::Error;
10764 void print()
const {
10766 if( stats.totals.assertions.total() > 0 ) {
10767 if( result.isOk() )
10770 printOriginalExpression();
10771 printReconstructedExpression();
10780 void printResultType()
const {
10781 if( !passOrFail.empty() ) {
10782 Colour colourGuard( colour );
10783 stream << passOrFail <<
":\n";
10786 void printOriginalExpression()
const {
10787 if( result.hasExpression() ) {
10788 Colour colourGuard( Colour::OriginalExpression );
10790 stream << result.getExpressionInMacro();
10794 void printReconstructedExpression()
const {
10795 if( result.hasExpandedExpression() ) {
10796 stream <<
"with expansion:\n";
10797 Colour colourGuard( Colour::ReconstructedExpression );
10798 stream << Text( result.getExpandedExpression(), TextAttributes().setIndent(2) ) <<
'\n';
10801 void printMessage()
const {
10802 if( !messageLabel.empty() )
10803 stream << messageLabel <<
':' <<
'\n';
10804 for( std::vector<MessageInfo>::const_iterator it = messages.begin(), itEnd = messages.end();
10808 if( printInfoMessages || it->type != ResultWas::Info )
10809 stream << Text( it->message, TextAttributes().setIndent(2) ) <<
'\n';
10812 void printSourceInfo()
const {
10813 Colour colourGuard( Colour::FileName );
10814 stream << result.getSourceInfo() <<
": ";
10817 std::ostream& stream;
10818 AssertionStats
const& stats;
10819 AssertionResult
const& result;
10820 Colour::Code colour;
10821 std::string passOrFail;
10822 std::string messageLabel;
10823 std::string message;
10824 std::vector<MessageInfo> messages;
10825 bool printInfoMessages;
10830 if( !currentTestRunInfo.used )
10831 lazyPrintRunInfo();
10832 if( !currentGroupInfo.used )
10833 lazyPrintGroupInfo();
10835 if( !m_headerPrinted ) {
10836 printTestCaseAndSectionHeader();
10837 m_headerPrinted =
true;
10840 void lazyPrintRunInfo() {
10841 stream << '\n' << getLineOfChars<'~'>() <<
'\n';
10842 Colour colour( Colour::SecondaryText );
10843 stream << currentTestRunInfo->name
10844 <<
" is a Catch v" << libraryVersion() <<
" host application.\n"
10845 <<
"Run with -? for options\n\n";
10847 if( m_config->rngSeed() != 0 )
10848 stream <<
"Randomness seeded to: " << m_config->rngSeed() <<
"\n\n";
10850 currentTestRunInfo.used =
true;
10852 void lazyPrintGroupInfo() {
10853 if( !currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1 ) {
10854 printClosedHeader(
"Group: " + currentGroupInfo->name );
10855 currentGroupInfo.used =
true;
10858 void printTestCaseAndSectionHeader() {
10859 assert( !m_sectionStack.empty() );
10860 printOpenHeader( currentTestCaseInfo->name );
10862 if( m_sectionStack.size() > 1 ) {
10863 Colour colourGuard( Colour::Headers );
10865 std::vector<SectionInfo>::const_iterator
10866 it = m_sectionStack.begin()+1,
10867 itEnd = m_sectionStack.end();
10868 for( ; it != itEnd; ++it )
10869 printHeaderString( it->name, 2 );
10872 SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
10874 if( !lineInfo.empty() ){
10875 stream << getLineOfChars<
'-'>() <<
'\n';
10876 Colour colourGuard( Colour::FileName );
10877 stream << lineInfo <<
'\n';
10879 stream << getLineOfChars<
'.'>() <<
'\n' << std::endl;
10882 void printClosedHeader( std::string
const& _name ) {
10883 printOpenHeader( _name );
10884 stream << getLineOfChars<
'.'>() <<
'\n';
10886 void printOpenHeader( std::string
const& _name ) {
10887 stream << getLineOfChars<
'-'>() <<
'\n';
10889 Colour colourGuard( Colour::Headers );
10890 printHeaderString( _name );
10896 void printHeaderString( std::string
const& _string, std::size_t indent = 0 ) {
10897 std::size_t i = _string.find(
": " );
10898 if( i != std::string::npos )
10902 stream << Text( _string, TextAttributes()
10903 .setIndent( indent+i)
10904 .setInitialIndent( indent ) ) <<
'\n';
10907 struct SummaryColumn {
10909 SummaryColumn( std::string
const& _label, Colour::Code _colour )
10913 SummaryColumn addRow( std::size_t count ) {
10914 std::ostringstream oss;
10916 std::string row = oss.str();
10917 for( std::vector<std::string>::iterator it = rows.begin(); it != rows.end(); ++it ) {
10918 while( it->size() < row.size() )
10920 while( it->size() > row.size() )
10923 rows.push_back( row );
10928 Colour::Code colour;
10929 std::vector<std::string> rows;
10933 void printTotals( Totals
const& totals ) {
10934 if( totals.testCases.total() == 0 ) {
10935 stream << Colour( Colour::Warning ) <<
"No tests ran\n";
10937 else if( totals.assertions.total() > 0 && totals.testCases.allPassed() ) {
10938 stream << Colour( Colour::ResultSuccess ) <<
"All tests passed";
10940 << pluralise( totals.assertions.passed,
"assertion" ) <<
" in "
10941 << pluralise( totals.testCases.passed,
"test case" ) <<
')'
10946 std::vector<SummaryColumn> columns;
10947 columns.push_back( SummaryColumn(
"", Colour::None )
10948 .addRow( totals.testCases.total() )
10949 .addRow( totals.assertions.total() ) );
10950 columns.push_back( SummaryColumn(
"passed", Colour::Success )
10951 .addRow( totals.testCases.passed )
10952 .addRow( totals.assertions.passed ) );
10953 columns.push_back( SummaryColumn(
"failed", Colour::ResultError )
10954 .addRow( totals.testCases.failed )
10955 .addRow( totals.assertions.failed ) );
10956 columns.push_back( SummaryColumn(
"failed as expected", Colour::ResultExpectedFailure )
10957 .addRow( totals.testCases.failedButOk )
10958 .addRow( totals.assertions.failedButOk ) );
10960 printSummaryRow(
"test cases", columns, 0 );
10961 printSummaryRow(
"assertions", columns, 1 );
10964 void printSummaryRow( std::string
const& label, std::vector<SummaryColumn>
const& cols, std::size_t row ) {
10965 for( std::vector<SummaryColumn>::const_iterator it = cols.begin(); it != cols.end(); ++it ) {
10966 std::string value = it->rows[row];
10967 if( it->label.empty() ) {
10968 stream << label <<
": ";
10972 stream << Colour( Colour::Warning ) <<
"- none -";
10974 else if( value !=
"0" ) {
10975 stream << Colour( Colour::LightGrey ) <<
" | ";
10976 stream << Colour( it->colour )
10977 << value <<
' ' << it->label;
10983 static std::size_t makeRatio( std::size_t number, std::size_t total ) {
10984 std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number/ total : 0;
10985 return ( ratio == 0 && number > 0 ) ? 1 : ratio;
10987 static std::size_t& findMax( std::size_t& i, std::size_t& j, std::size_t& k ) {
10988 if( i > j && i > k )
10996 void printTotalsDivider( Totals
const& totals ) {
10997 if( totals.testCases.total() > 0 ) {
10998 std::size_t failedRatio = makeRatio( totals.testCases.failed, totals.testCases.total() );
10999 std::size_t failedButOkRatio = makeRatio( totals.testCases.failedButOk, totals.testCases.total() );
11000 std::size_t passedRatio = makeRatio( totals.testCases.passed, totals.testCases.total() );
11001 while( failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH-1 )
11002 findMax( failedRatio, failedButOkRatio, passedRatio )++;
11003 while( failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH-1 )
11004 findMax( failedRatio, failedButOkRatio, passedRatio )--;
11006 stream << Colour( Colour::Error ) << std::string( failedRatio,
'=' );
11007 stream << Colour( Colour::ResultExpectedFailure ) << std::string( failedButOkRatio,
'=' );
11008 if( totals.testCases.allPassed() )
11009 stream << Colour( Colour::ResultSuccess ) << std::string( passedRatio,
'=' );
11011 stream << Colour( Colour::Success ) << std::string( passedRatio,
'=' );
11014 stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH-1,
'=' );
11018 void printSummaryDivider() {
11019 stream << getLineOfChars<
'-'>() <<
'\n';
11023 bool m_headerPrinted;
11026 INTERNAL_CATCH_REGISTER_REPORTER(
"console", ConsoleReporter )
11031 #define TWOBLUECUBES_CATCH_REPORTER_COMPACT_HPP_INCLUDED
11035 struct CompactReporter : StreamingReporterBase {
11037 CompactReporter( ReporterConfig
const& _config )
11038 : StreamingReporterBase( _config )
11041 virtual ~CompactReporter();
11043 static std::string getDescription() {
11044 return "Reports test results on a single line, suitable for IDEs";
11047 virtual ReporterPreferences getPreferences()
const {
11048 ReporterPreferences prefs;
11049 prefs.shouldRedirectStdOut =
false;
11053 virtual void noMatchingTestCases( std::string
const& spec ) {
11054 stream <<
"No test cases matched '" << spec <<
'\'' << std::endl;
11057 virtual void assertionStarting( AssertionInfo
const& ) {}
11059 virtual bool assertionEnded( AssertionStats
const& _assertionStats ) {
11060 AssertionResult
const& result = _assertionStats.assertionResult;
11062 bool printInfoMessages =
true;
11065 if( !m_config->includeSuccessfulResults() && result.isOk() ) {
11066 if( result.getResultType() != ResultWas::Warning )
11068 printInfoMessages =
false;
11071 AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
11074 stream << std::endl;
11078 virtual void sectionEnded(SectionStats
const& _sectionStats) CATCH_OVERRIDE {
11079 if (m_config->showDurations() == ShowDurations::Always) {
11080 stream << getFormattedDuration(_sectionStats.durationInSeconds) <<
" s: " << _sectionStats.sectionInfo.name << std::endl;
11084 virtual void testRunEnded( TestRunStats
const& _testRunStats ) {
11085 printTotals( _testRunStats.totals );
11086 stream <<
'\n' << std::endl;
11087 StreamingReporterBase::testRunEnded( _testRunStats );
11091 class AssertionPrinter {
11092 void operator= ( AssertionPrinter
const& );
11094 AssertionPrinter( std::ostream& _stream, AssertionStats
const& _stats,
bool _printInfoMessages )
11095 : stream( _stream )
11097 , result( _stats.assertionResult )
11098 , messages( _stats.infoMessages )
11099 , itMessage( _stats.infoMessages.begin() )
11100 , printInfoMessages( _printInfoMessages )
11106 itMessage = messages.begin();
11108 switch( result.getResultType() ) {
11109 case ResultWas::Ok:
11110 printResultType( Colour::ResultSuccess, passedString() );
11111 printOriginalExpression();
11112 printReconstructedExpression();
11113 if ( ! result.hasExpression() )
11114 printRemainingMessages( Colour::None );
11116 printRemainingMessages();
11118 case ResultWas::ExpressionFailed:
11119 if( result.isOk() )
11120 printResultType( Colour::ResultSuccess, failedString() + std::string( " - but was ok" ) );
11122 printResultType( Colour::Error, failedString() );
11123 printOriginalExpression();
11124 printReconstructedExpression();
11125 printRemainingMessages();
11127 case ResultWas::ThrewException:
11128 printResultType( Colour::Error, failedString() );
11129 printIssue(
"unexpected exception with message:" );
11131 printExpressionWas();
11132 printRemainingMessages();
11134 case ResultWas::FatalErrorCondition:
11135 printResultType( Colour::Error, failedString() );
11136 printIssue(
"fatal error condition with message:" );
11138 printExpressionWas();
11139 printRemainingMessages();
11141 case ResultWas::DidntThrowException:
11142 printResultType( Colour::Error, failedString() );
11143 printIssue(
"expected exception, got none" );
11144 printExpressionWas();
11145 printRemainingMessages();
11147 case ResultWas::Info:
11148 printResultType( Colour::None,
"info" );
11150 printRemainingMessages();
11152 case ResultWas::Warning:
11153 printResultType( Colour::None,
"warning" );
11155 printRemainingMessages();
11157 case ResultWas::ExplicitFailure:
11158 printResultType( Colour::Error, failedString() );
11159 printIssue(
"explicitly" );
11160 printRemainingMessages( Colour::None );
11163 case ResultWas::Unknown:
11164 case ResultWas::FailureBit:
11165 case ResultWas::Exception:
11166 printResultType( Colour::Error,
"** internal error **" );
11174 static Colour::Code dimColour() {
return Colour::FileName; }
11176 #ifdef CATCH_PLATFORM_MAC
11177 static const char* failedString() {
return "FAILED"; }
11178 static const char* passedString() {
return "PASSED"; }
11180 static const char* failedString() {
return "failed"; }
11181 static const char* passedString() {
return "passed"; }
11184 void printSourceInfo()
const {
11185 Colour colourGuard( Colour::FileName );
11186 stream << result.getSourceInfo() <<
':';
11189 void printResultType( Colour::Code colour, std::string
const& passOrFail )
const {
11190 if( !passOrFail.empty() ) {
11192 Colour colourGuard( colour );
11193 stream <<
' ' << passOrFail;
11199 void printIssue( std::string
const& issue )
const {
11200 stream <<
' ' << issue;
11203 void printExpressionWas() {
11204 if( result.hasExpression() ) {
11207 Colour colour( dimColour() );
11208 stream <<
" expression was:";
11210 printOriginalExpression();
11214 void printOriginalExpression()
const {
11215 if( result.hasExpression() ) {
11216 stream <<
' ' << result.getExpression();
11220 void printReconstructedExpression()
const {
11221 if( result.hasExpandedExpression() ) {
11223 Colour colour( dimColour() );
11224 stream <<
" for: ";
11226 stream << result.getExpandedExpression();
11230 void printMessage() {
11231 if ( itMessage != messages.end() ) {
11232 stream <<
" '" << itMessage->message <<
'\'';
11237 void printRemainingMessages( Colour::Code colour = dimColour() ) {
11238 if ( itMessage == messages.end() )
11242 std::vector<MessageInfo>::const_iterator itEnd = messages.end();
11243 const std::size_t N =
static_cast<std::size_t
>( std::distance( itMessage, itEnd ) );
11246 Colour colourGuard( colour );
11247 stream <<
" with " << pluralise( N,
"message" ) <<
':';
11250 for(; itMessage != itEnd; ) {
11252 if( printInfoMessages || itMessage->type != ResultWas::Info ) {
11253 stream <<
" '" << itMessage->message <<
'\'';
11254 if ( ++itMessage != itEnd ) {
11255 Colour colourGuard( dimColour() );
11263 std::ostream& stream;
11264 AssertionStats
const& stats;
11265 AssertionResult
const& result;
11266 std::vector<MessageInfo> messages;
11267 std::vector<MessageInfo>::const_iterator itMessage;
11268 bool printInfoMessages;
11278 std::string bothOrAll( std::size_t count )
const {
11279 return count == 1 ? std::string() : count == 2 ?
"both " :
"all " ;
11282 void printTotals(
const Totals& totals )
const {
11283 if( totals.testCases.total() == 0 ) {
11284 stream <<
"No tests ran.";
11286 else if( totals.testCases.failed == totals.testCases.total() ) {
11287 Colour colour( Colour::ResultError );
11288 const std::string qualify_assertions_failed =
11289 totals.assertions.failed == totals.assertions.total() ?
11290 bothOrAll( totals.assertions.failed ) : std::string();
11292 "Failed " << bothOrAll( totals.testCases.failed )
11293 << pluralise( totals.testCases.failed,
"test case" ) <<
", "
11294 "failed " << qualify_assertions_failed <<
11295 pluralise( totals.assertions.failed,
"assertion" ) <<
'.';
11297 else if( totals.assertions.total() == 0 ) {
11299 "Passed " << bothOrAll( totals.testCases.total() )
11300 << pluralise( totals.testCases.total(),
"test case" )
11301 <<
" (no assertions).";
11303 else if( totals.assertions.failed ) {
11304 Colour colour( Colour::ResultError );
11306 "Failed " << pluralise( totals.testCases.failed,
"test case" ) <<
", "
11307 "failed " << pluralise( totals.assertions.failed,
"assertion" ) <<
'.';
11310 Colour colour( Colour::ResultSuccess );
11312 "Passed " << bothOrAll( totals.testCases.passed )
11313 << pluralise( totals.testCases.passed,
"test case" ) <<
11314 " with " << pluralise( totals.assertions.passed,
"assertion" ) <<
'.';
11319 INTERNAL_CATCH_REGISTER_REPORTER(
"compact", CompactReporter )
11326 NonCopyable::~NonCopyable() {}
11327 IShared::~IShared() {}
11328 IStream::~IStream() CATCH_NOEXCEPT {}
11329 FileStream::~FileStream() CATCH_NOEXCEPT {}
11330 CoutStream::~CoutStream() CATCH_NOEXCEPT {}
11331 DebugOutStream::~DebugOutStream() CATCH_NOEXCEPT {}
11332 StreamBufBase::~StreamBufBase() CATCH_NOEXCEPT {}
11333 IContext::~IContext() {}
11334 IResultCapture::~IResultCapture() {}
11335 ITestCase::~ITestCase() {}
11336 ITestCaseRegistry::~ITestCaseRegistry() {}
11337 IRegistryHub::~IRegistryHub() {}
11338 IMutableRegistryHub::~IMutableRegistryHub() {}
11339 IExceptionTranslator::~IExceptionTranslator() {}
11340 IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() {}
11341 IReporter::~IReporter() {}
11342 IReporterFactory::~IReporterFactory() {}
11343 IReporterRegistry::~IReporterRegistry() {}
11344 IStreamingReporter::~IStreamingReporter() {}
11345 AssertionStats::~AssertionStats() {}
11346 SectionStats::~SectionStats() {}
11347 TestCaseStats::~TestCaseStats() {}
11348 TestGroupStats::~TestGroupStats() {}
11349 TestRunStats::~TestRunStats() {}
11350 CumulativeReporterBase::SectionNode::~SectionNode() {}
11351 CumulativeReporterBase::~CumulativeReporterBase() {}
11353 StreamingReporterBase::~StreamingReporterBase() {}
11354 ConsoleReporter::~ConsoleReporter() {}
11355 CompactReporter::~CompactReporter() {}
11356 IRunner::~IRunner() {}
11357 IMutableContext::~IMutableContext() {}
11358 IConfig::~IConfig() {}
11359 XmlReporter::~XmlReporter() {}
11360 JunitReporter::~JunitReporter() {}
11361 TestRegistry::~TestRegistry() {}
11362 FreeFunctionTestCase::~FreeFunctionTestCase() {}
11363 IGeneratorInfo::~IGeneratorInfo() {}
11364 IGeneratorsForTest::~IGeneratorsForTest() {}
11365 WildcardPattern::~WildcardPattern() {}
11366 TestSpec::Pattern::~Pattern() {}
11367 TestSpec::NamePattern::~NamePattern() {}
11368 TestSpec::TagPattern::~TagPattern() {}
11369 TestSpec::ExcludedPattern::~ExcludedPattern() {}
11370 Matchers::Impl::MatcherUntypedBase::~MatcherUntypedBase() {}
11372 void Config::dummy() {}
11374 namespace TestCaseTracking {
11375 ITracker::~ITracker() {}
11376 TrackerBase::~TrackerBase() {}
11377 SectionTracker::~SectionTracker() {}
11378 IndexTracker::~IndexTracker() {}
11383 #pragma clang diagnostic pop
11388 #ifdef CATCH_CONFIG_MAIN
11390 #define TWOBLUECUBES_CATCH_DEFAULT_MAIN_HPP_INCLUDED
11394 #if defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
11396 extern "C" int wmain (
int argc,
wchar_t * argv[],
wchar_t * []) {
11399 int main (
int argc,
char * argv[]) {
11402 int result = Catch::Session().run( argc, argv );
11403 return ( result < 0xff ? result : 0xff );
11409 int main (
int argc,
char *
const argv[]) {
11410 #if !CATCH_ARC_ENABLED
11411 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
11414 Catch::registerTestMethods();
11415 int result = Catch::Session().run( argc, (
char*
const*)argv );
11417 #if !CATCH_ARC_ENABLED
11421 return ( result < 0xff ? result : 0xff );
11428 #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
11429 # undef CLARA_CONFIG_MAIN
11435 #ifdef CATCH_CONFIG_PREFIX_ALL
11437 #if defined(CATCH_CONFIG_FAST_COMPILE)
11438 #define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, expr )
11439 #define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr )
11441 #define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, expr )
11442 #define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr )
11445 #define CATCH_REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", expr )
11446 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
11447 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
11448 #define CATCH_REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, expr )
11450 #define CATCH_CHECK( expr ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, expr )
11451 #define CATCH_CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, expr )
11452 #define CATCH_CHECKED_IF( expr ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, expr )
11453 #define CATCH_CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, expr )
11454 #define CATCH_CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, expr )
11456 #define CATCH_CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", expr )
11457 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
11458 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
11459 #define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, expr )
11461 #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
11463 #if defined(CATCH_CONFIG_FAST_COMPILE)
11464 #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT_NO_TRY( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
11466 #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
11469 #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
11470 #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
11471 #define CATCH_SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
11472 #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << Catch::toString(msg) )
11473 #define CATCH_SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << Catch::toString(msg) )
11475 #ifdef CATCH_CONFIG_VARIADIC_MACROS
11476 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
11477 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
11478 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
11479 #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
11480 #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
11481 #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
11482 #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
11483 #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
11485 #define CATCH_TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description )
11486 #define CATCH_TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description )
11487 #define CATCH_METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description )
11488 #define CATCH_REGISTER_TEST_CASE( function, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( function, name, description )
11489 #define CATCH_SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description )
11490 #define CATCH_FAIL( msg ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, msg )
11491 #define CATCH_FAIL_CHECK( msg ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, msg )
11492 #define CATCH_SUCCEED( msg ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, msg )
11494 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" )
11496 #define CATCH_REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType )
11497 #define CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType )
11499 #define CATCH_GENERATE( expr) INTERNAL_CATCH_GENERATE( expr )
11502 #ifdef CATCH_CONFIG_VARIADIC_MACROS
11503 #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
11504 #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
11506 #define CATCH_SCENARIO( name, tags ) CATCH_TEST_CASE( "Scenario: " name, tags )
11507 #define CATCH_SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags )
11509 #define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( "Given: ") + desc, "" )
11510 #define CATCH_WHEN( desc ) CATCH_SECTION( std::string( " When: ") + desc, "" )
11511 #define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( " And: ") + desc, "" )
11512 #define CATCH_THEN( desc ) CATCH_SECTION( std::string( " Then: ") + desc, "" )
11513 #define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( " And: ") + desc, "" )
11518 #if defined(CATCH_CONFIG_FAST_COMPILE)
11519 #define REQUIRE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "REQUIRE", Catch::ResultDisposition::Normal, expr )
11520 #define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr )
11523 #define REQUIRE( expr ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, expr )
11524 #define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr )
11527 #define REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", expr )
11528 #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
11529 #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
11530 #define REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, expr )
11532 #define CHECK( expr ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, expr )
11533 #define CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, expr )
11534 #define CHECKED_IF( expr ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, expr )
11535 #define CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, expr )
11536 #define CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, expr )
11538 #define CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", expr )
11539 #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
11540 #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
11541 #define CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, expr )
11543 #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
11545 #if defined(CATCH_CONFIG_FAST_COMPILE)
11546 #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT_NO_TRY( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
11548 #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
11551 #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
11552 #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
11553 #define SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
11554 #define CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << Catch::toString(msg) )
11555 #define SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << Catch::toString(msg) )
11557 #ifdef CATCH_CONFIG_VARIADIC_MACROS
11558 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
11559 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
11560 #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
11561 #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
11562 #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
11563 #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
11564 #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
11565 #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
11567 #define TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description )
11568 #define TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description )
11569 #define METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description )
11570 #define REGISTER_TEST_CASE( method, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( method, name, description )
11571 #define SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description )
11572 #define FAIL( msg ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, msg )
11573 #define FAIL_CHECK( msg ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, msg )
11574 #define SUCCEED( msg ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, msg )
11576 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" )
11578 #define REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType )
11579 #define REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType )
11581 #define GENERATE( expr) INTERNAL_CATCH_GENERATE( expr )
11585 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
11588 #ifdef CATCH_CONFIG_VARIADIC_MACROS
11589 #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
11590 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
11592 #define SCENARIO( name, tags ) TEST_CASE( "Scenario: " name, tags )
11593 #define SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags )
11595 #define GIVEN( desc ) SECTION( std::string(" Given: ") + desc, "" )
11596 #define WHEN( desc ) SECTION( std::string(" When: ") + desc, "" )
11597 #define AND_WHEN( desc ) SECTION( std::string("And when: ") + desc, "" )
11598 #define THEN( desc ) SECTION( std::string(" Then: ") + desc, "" )
11599 #define AND_THEN( desc ) SECTION( std::string(" And: ") + desc, "" )
11601 using Catch::Detail::Approx;
11605 #define TWOBLUECUBES_CATCH_REENABLE_WARNINGS_H_INCLUDED
11608 # ifdef __ICC // icpc defines the __clang__ macro
11609 # pragma warning(pop)
11611 # pragma clang diagnostic pop
11613 #elif defined __GNUC__
11614 # pragma GCC diagnostic pop
11617 #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
constexpr bool operator>=(tagged_tuple< LTags...> const &lhs, tagged_tuple< RTags...> const &rhs) noexcept(noexcept(lhs< rhs))
Definition: tagged_tuple.hpp:710
#define CATCH_AUTO_PTR(T)
Definition: catch.hpp:368
#define CATCH_BREAK_INTO_DEBUGGER()
Definition: catch.hpp:2154
#define CATCH_INTERNAL_ERROR(msg)
Definition: catch.hpp:501
#define CATCH_NULL
Definition: catch.hpp:354
constexpr bool operator<=(tagged_tuple< LTags...> const &lhs, tagged_tuple< RTags...> const &rhs) noexcept(noexcept(rhs< lhs))
Definition: tagged_tuple.hpp:701
#define CATCH_NOEXCEPT
Definition: catch.hpp:346
#define CATCH_OVERRIDE
Definition: catch.hpp:361
#define CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS
Definition: catch.hpp:337
#define CATCH_INTERNAL_LINEINFO
Definition: catch.hpp:500
constexpr bool operator==(tagged_tuple< LTags...> const &lhs, tagged_tuple< RTags...> const &rhs) noexcept(noexcept(tuples_detail::tuple_equal_impl(lhs, rhs)))
Definition: tagged_tuple.hpp:631
constexpr bool operator>(tagged_tuple< LTags...> const &lhs, tagged_tuple< RTags...> const &rhs) noexcept(noexcept(rhs< lhs))
Definition: tagged_tuple.hpp:692
constexpr bool operator<(tagged_tuple< LTags...> const &lhs, tagged_tuple< RTags...> const &rhs) noexcept(noexcept(tuples_detail::tuple_less_impl(lhs, rhs)))
Definition: tagged_tuple.hpp:682
#define CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS
Definition: catch.hpp:338
constexpr bool operator!=(tagged_tuple< LTags...> const &lhs, tagged_tuple< RTags...> const &rhs) noexcept(noexcept(lhs==rhs))
Definition: tagged_tuple.hpp:641
constexpr const Tag::type & get(const tagged_tuple< Tags...> &t) noexcept
Retrieve the element with tag Tag from the tagged_tuple t
Definition: tagged_tuple.hpp:582