Debian Codegraph @

testsuite/unittests/catch/catch.hpp

raw
1 /*
2 * CATCH v1.0 build 43 (master branch)
3 * Generated: 2014-05-04 09:22:51.466832
4 * ----------------------------------------------------------
5 * This file has been merged from multiple headers. Please don't edit it directly
6 * Copyright (c) 2012 Two Blue Cubes Ltd. All rights reserved.
7 *
8 * Distributed under the Boost Software License, Version 1.0. (See accompanying
9 * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
10 */
11 #ifndef TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
12 #define TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
13
14 #define TWOBLUECUBES_CATCH_HPP_INCLUDED
15
16 #ifdef __clang__
17 #pragma clang diagnostic ignored "-Wglobal-constructors"
18 #pragma clang diagnostic ignored "-Wvariadic-macros"
19 #pragma clang diagnostic ignored "-Wc99-extensions"
20 #pragma clang diagnostic push
21 #pragma clang diagnostic ignored "-Wpadded"
22 #pragma clang diagnostic ignored "-Wc++98-compat"
23 #pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
24 #endif
25
26 #ifdef CATCH_CONFIG_MAIN
27 # define CATCH_CONFIG_RUNNER
28 #endif
29
30 #ifdef CATCH_CONFIG_RUNNER
31 # ifndef CLARA_CONFIG_MAIN
32 # define CLARA_CONFIG_MAIN_NOT_DEFINED
33 # define CLARA_CONFIG_MAIN
34 # endif
35 #endif
36
37 // #included from: internal/catch_notimplemented_exception.h
38 #define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_H_INCLUDED
39
40 // #included from: catch_common.h
41 #define TWOBLUECUBES_CATCH_COMMON_H_INCLUDED
42
43 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
44 #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
45 #define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
46
47 #define INTERNAL_CATCH_STRINGIFY2( expr ) #expr
48 #define INTERNAL_CATCH_STRINGIFY( expr ) INTERNAL_CATCH_STRINGIFY2( expr )
49
50 #include <sstream>
51 #include <stdexcept>
52 #include <algorithm>
53
54 // #included from: catch_compiler_capabilities.h
55 #define TWOBLUECUBES_CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED
56
57 // Much of the following code is based on Boost (1.53)
58
59 #ifdef __clang__
60
61 # if __has_feature(cxx_nullptr)
62 # define CATCH_CONFIG_CPP11_NULLPTR
63 # endif
64
65 # if __has_feature(cxx_noexcept)
66 # define CATCH_CONFIG_CPP11_NOEXCEPT
67 # endif
68
69 #endif // __clang__
70
71 ////////////////////////////////////////////////////////////////////////////////
72 // Borland
73 #ifdef __BORLANDC__
74
75 #if (__BORLANDC__ > 0x582 )
76 //#define CATCH_CONFIG_SFINAE // Not confirmed
77 #endif
78
79 #endif // __BORLANDC__
80
81 ////////////////////////////////////////////////////////////////////////////////
82 // EDG
83 #ifdef __EDG_VERSION__
84
85 #if (__EDG_VERSION__ > 238 )
86 //#define CATCH_CONFIG_SFINAE // Not confirmed
87 #endif
88
89 #endif // __EDG_VERSION__
90
91 ////////////////////////////////////////////////////////////////////////////////
92 // Digital Mars
93 #ifdef __DMC__
94
95 #if (__DMC__ > 0x840 )
96 //#define CATCH_CONFIG_SFINAE // Not confirmed
97 #endif
98
99 #endif // __DMC__
100
101 ////////////////////////////////////////////////////////////////////////////////
102 // GCC
103 #ifdef __GNUC__
104
105 #if __GNUC__ < 3
106
107 #if (__GNUC_MINOR__ >= 96 )
108 //#define CATCH_CONFIG_SFINAE
109 #endif
110
111 #elif __GNUC__ >= 3
112
113 // #define CATCH_CONFIG_SFINAE // Taking this out completely for now
114
115 #endif // __GNUC__ < 3
116
117 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__) )
118
119 //#define CATCH_CONFIG_CPP11_NULLPTR
120 #endif
121
122 #endif // __GNUC__
123
124 ////////////////////////////////////////////////////////////////////////////////
125 // Visual C++
126 #ifdef _MSC_VER
127
128 #if (_MSC_VER >= 1310 ) // (VC++ 7.0+)
129 //#define CATCH_CONFIG_SFINAE // Not confirmed
130 #endif
131
132 #endif // _MSC_VER
133
134 // Use variadic macros if the compiler supports them
135 #if ( defined _MSC_VER && _MSC_VER > 1400 && !defined __EDGE__) || \
136 ( defined __WAVE__ && __WAVE_HAS_VARIADICS ) || \
137 ( defined __GNUC__ && __GNUC__ >= 3 ) || \
138 ( !defined __cplusplus && __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L )
139
140 #ifndef CATCH_CONFIG_NO_VARIADIC_MACROS
141 #define CATCH_CONFIG_VARIADIC_MACROS
142 #endif
143
144 #endif
145
146 ////////////////////////////////////////////////////////////////////////////////
147 // C++ language feature support
148
149 // detect language version:
150 #if (__cplusplus == 201103L)
151 # define CATCH_CPP11
152 # define CATCH_CPP11_OR_GREATER
153 #elif (__cplusplus >= 201103L)
154 # define CATCH_CPP11_OR_GREATER
155 #endif
156
157 // noexcept support:
158 #if defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_NOEXCEPT)
159 # define CATCH_NOEXCEPT noexcept
160 # define CATCH_NOEXCEPT_IS(x) noexcept(x)
161 #else
162 # define CATCH_NOEXCEPT throw()
163 # define CATCH_NOEXCEPT_IS(x)
164 #endif
165
166 namespace Catch {
167
168 class NonCopyable {
169 NonCopyable( NonCopyable const& );
170 void operator = ( NonCopyable const& );
171 protected:
172 NonCopyable() {}
173 virtual ~NonCopyable();
174 };
175
176 class SafeBool {
177 public:
178 typedef void (SafeBool::*type)() const;
179
180 static type makeSafe( bool value ) {
181 return value ? &SafeBool::trueValue : 0;
182 }
183 private:
184 void trueValue() const {}
185 };
186
187 template<typename ContainerT>
188 inline void deleteAll( ContainerT& container ) {
189 typename ContainerT::const_iterator it = container.begin();
190 typename ContainerT::const_iterator itEnd = container.end();
191 for(; it != itEnd; ++it )
192 delete *it;
193 }
194 template<typename AssociativeContainerT>
195 inline void deleteAllValues( AssociativeContainerT& container ) {
196 typename AssociativeContainerT::const_iterator it = container.begin();
197 typename AssociativeContainerT::const_iterator itEnd = container.end();
198 for(; it != itEnd; ++it )
199 delete it->second;
200 }
201
202 bool startsWith( std::string const& s, std::string const& prefix );
203 bool endsWith( std::string const& s, std::string const& suffix );
204 bool contains( std::string const& s, std::string const& infix );
205 void toLowerInPlace( std::string& s );
206 std::string toLower( std::string const& s );
207 std::string trim( std::string const& str );
208
209 struct pluralise {
210 pluralise( std::size_t count, std::string const& label );
211
212 friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
213
214 std::size_t m_count;
215 std::string m_label;
216 };
217
218 struct SourceLineInfo {
219
220 SourceLineInfo();
221 SourceLineInfo( char const* _file, std::size_t _line );
222 SourceLineInfo( SourceLineInfo const& other );
223 # ifdef CATCH_CPP11_OR_GREATER
224 SourceLineInfo( SourceLineInfo && ) = default;
225 SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
226 SourceLineInfo& operator = ( SourceLineInfo && ) = default;
227 # endif
228 bool empty() const;
229 bool operator == ( SourceLineInfo const& other ) const;
230
231 std::string file;
232 std::size_t line;
233 };
234
235 std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
236
237 // This is just here to avoid compiler warnings with macro constants and boolean literals
238 inline bool isTrue( bool value ){ return value; }
239
240 void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo );
241
242 // Use this in variadic streaming macros to allow
243 // >> +StreamEndStop
244 // as well as
245 // >> stuff +StreamEndStop
246 struct StreamEndStop {
247 std::string operator+() {
248 return std::string();
249 }
250 };
251 template<typename T>
252 T const& operator + ( T const& value, StreamEndStop ) {
253 return value;
254 }
255 }
256
257 #define CATCH_INTERNAL_LINEINFO ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
258 #define CATCH_INTERNAL_ERROR( msg ) ::Catch::throwLogicError( msg, CATCH_INTERNAL_LINEINFO );
259
260 #include <ostream>
261
262 namespace Catch {
263
264 class NotImplementedException : public std::exception
265 {
266 public:
267 NotImplementedException( SourceLineInfo const& lineInfo );
268
269 virtual ~NotImplementedException() CATCH_NOEXCEPT {}
270
271 virtual const char* what() const CATCH_NOEXCEPT;
272
273 private:
274 std::string m_what;
275 SourceLineInfo m_lineInfo;
276 };
277
278 } // end namespace Catch
279
280 ///////////////////////////////////////////////////////////////////////////////
281 #define CATCH_NOT_IMPLEMENTED throw Catch::NotImplementedException( CATCH_INTERNAL_LINEINFO )
282
283 // #included from: internal/catch_context.h
284 #define TWOBLUECUBES_CATCH_CONTEXT_H_INCLUDED
285
286 // #included from: catch_interfaces_generators.h
287 #define TWOBLUECUBES_CATCH_INTERFACES_GENERATORS_H_INCLUDED
288
289 #include <string>
290
291 namespace Catch {
292
293 struct IGeneratorInfo {
294 virtual ~IGeneratorInfo();
295 virtual bool moveNext() = 0;
296 virtual std::size_t getCurrentIndex() const = 0;
297 };
298
299 struct IGeneratorsForTest {
300 virtual ~IGeneratorsForTest();
301
302 virtual IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) = 0;
303 virtual bool moveNext() = 0;
304 };
305
306 IGeneratorsForTest* createGeneratorsForTest();
307
308 } // end namespace Catch
309
310 // #included from: catch_ptr.hpp
311 #define TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED
312
313 #ifdef __clang__
314 #pragma clang diagnostic push
315 #pragma clang diagnostic ignored "-Wpadded"
316 #endif
317
318 namespace Catch {
319
320 // An intrusive reference counting smart pointer.
321 // T must implement addRef() and release() methods
322 // typically implementing the IShared interface
323 template<typename T>
324 class Ptr {
325 public:
326 Ptr() : m_p( NULL ){}
327 Ptr( T* p ) : m_p( p ){
328 if( m_p )
329 m_p->addRef();
330 }
331 Ptr( Ptr const& other ) : m_p( other.m_p ){
332 if( m_p )
333 m_p->addRef();
334 }
335 ~Ptr(){
336 if( m_p )
337 m_p->release();
338 }
339 void reset() {
340 if( m_p )
341 m_p->release();
342 m_p = NULL;
343 }
344 Ptr& operator = ( T* p ){
345 Ptr temp( p );
346 swap( temp );
347 return *this;
348 }
349 Ptr& operator = ( Ptr const& other ){
350 Ptr temp( other );
351 swap( temp );
352 return *this;
353 }
354 void swap( Ptr& other ) { std::swap( m_p, other.m_p ); }
355 T* get() { return m_p; }
356 const T* get() const{ return m_p; }
357 T& operator*() const { return *m_p; }
358 T* operator->() const { return m_p; }
359 bool operator !() const { return m_p == NULL; }
360 operator SafeBool::type() const { return SafeBool::makeSafe( m_p != NULL ); }
361
362 private:
363 T* m_p;
364 };
365
366 struct IShared : NonCopyable {
367 virtual ~IShared();
368 virtual void addRef() const = 0;
369 virtual void release() const = 0;
370 };
371
372 template<typename T = IShared>
373 struct SharedImpl : T {
374
375 SharedImpl() : m_rc( 0 ){}
376
377 virtual void addRef() const {
378 ++m_rc;
379 }
380 virtual void release() const {
381 if( --m_rc == 0 )
382 delete this;
383 }
384
385 mutable unsigned int m_rc;
386 };
387
388 } // end namespace Catch
389
390 #ifdef __clang__
391 #pragma clang diagnostic pop
392 #endif
393
394 #include <memory>
395 #include <vector>
396 #include <stdlib.h>
397
398 namespace Catch {
399
400 class TestCase;
401 class Stream;
402 struct IResultCapture;
403 struct IRunner;
404 struct IGeneratorsForTest;
405 struct IConfig;
406
407 struct IContext
408 {
409 virtual ~IContext();
410
411 virtual IResultCapture& getResultCapture() = 0;
412 virtual IRunner& getRunner() = 0;
413 virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) = 0;
414 virtual bool advanceGeneratorsForCurrentTest() = 0;
415 virtual Ptr<IConfig const> getConfig() const = 0;
416 };
417
418 struct IMutableContext : IContext
419 {
420 virtual ~IMutableContext();
421 virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
422 virtual void setRunner( IRunner* runner ) = 0;
423 virtual void setConfig( Ptr<IConfig const> const& config ) = 0;
424 };
425
426 IContext& getCurrentContext();
427 IMutableContext& getCurrentMutableContext();
428 void cleanUpContext();
429 Stream createStream( std::string const& streamName );
430
431 }
432
433 // #included from: internal/catch_test_registry.hpp
434 #define TWOBLUECUBES_CATCH_TEST_REGISTRY_HPP_INCLUDED
435
436 // #included from: catch_interfaces_testcase.h
437 #define TWOBLUECUBES_CATCH_INTERFACES_TESTCASE_H_INCLUDED
438
439 #include <vector>
440
441 namespace Catch {
442
443 class TestCaseFilters;
444
445 struct ITestCase : IShared {
446 virtual void invoke () const = 0;
447 protected:
448 virtual ~ITestCase();
449 };
450
451 class TestCase;
452 struct IConfig;
453
454 struct ITestCaseRegistry {
455 virtual ~ITestCaseRegistry();
456 virtual std::vector<TestCase> const& getAllTests() const = 0;
457 virtual void getFilteredTests( TestCaseFilters const& filters, IConfig const& config, std::vector<TestCase>& matchingTestCases ) const = 0;
458 virtual void getFilteredTests( IConfig const& config, std::vector<TestCase>& matchingTestCases ) const = 0;
459
460 };
461 }
462
463 namespace Catch {
464
465 template<typename C>
466 class MethodTestCase : public SharedImpl<ITestCase> {
467
468 public:
469 MethodTestCase( void (C::*method)() ) : m_method( method ) {}
470
471 virtual void invoke() const {
472 C obj;
473 (obj.*m_method)();
474 }
475
476 private:
477 virtual ~MethodTestCase() {}
478
479 void (C::*m_method)();
480 };
481
482 typedef void(*TestFunction)();
483
484 struct NameAndDesc {
485 NameAndDesc( const char* _name = "", const char* _description= "" )
486 : name( _name ), description( _description )
487 {}
488
489 const char* name;
490 const char* description;
491 };
492
493 struct AutoReg {
494
495 AutoReg( TestFunction function,
496 SourceLineInfo const& lineInfo,
497 NameAndDesc const& nameAndDesc );
498
499 template<typename C>
500 AutoReg( void (C::*method)(),
501 char const* className,
502 NameAndDesc const& nameAndDesc,
503 SourceLineInfo const& lineInfo ) {
504 registerTestCase( new MethodTestCase<C>( method ),
505 className,
506 nameAndDesc,
507 lineInfo );
508 }
509
510 void registerTestCase( ITestCase* testCase,
511 char const* className,
512 NameAndDesc const& nameAndDesc,
513 SourceLineInfo const& lineInfo );
514
515 ~AutoReg();
516
517 private:
518 AutoReg( AutoReg const& );
519 void operator= ( AutoReg const& );
520 };
521
522 } // end namespace Catch
523
524 #ifdef CATCH_CONFIG_VARIADIC_MACROS
525 ///////////////////////////////////////////////////////////////////////////////
526 #define INTERNAL_CATCH_TESTCASE( ... ) \
527 static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )(); \
528 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); }\
529 static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )()
530
531 ///////////////////////////////////////////////////////////////////////////////
532 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
533 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); }
534
535 ///////////////////////////////////////////////////////////////////////////////
536 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... )\
537 namespace{ \
538 struct INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) : ClassName{ \
539 void test(); \
540 }; \
541 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test, #ClassName, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); \
542 } \
543 void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test()
544
545 #else
546 ///////////////////////////////////////////////////////////////////////////////
547 #define INTERNAL_CATCH_TESTCASE( Name, Desc ) \
548 static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )(); \
549 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); }\
550 static void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )()
551
552 ///////////////////////////////////////////////////////////////////////////////
553 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, Name, Desc ) \
554 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( Name, Desc ), CATCH_INTERNAL_LINEINFO ); }
555
556 ///////////////////////////////////////////////////////////////////////////////
557 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, TestName, Desc )\
558 namespace{ \
559 struct INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) : ClassName{ \
560 void test(); \
561 }; \
562 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test, #ClassName, Catch::NameAndDesc( TestName, Desc ), CATCH_INTERNAL_LINEINFO ); \
563 } \
564 void INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ )::test()
565
566 #endif
567
568 // #included from: internal/catch_capture.hpp
569 #define TWOBLUECUBES_CATCH_CAPTURE_HPP_INCLUDED
570
571 // #included from: catch_expression_decomposer.hpp
572 #define TWOBLUECUBES_CATCH_EXPRESSION_DECOMPOSER_HPP_INCLUDED
573
574 // #included from: catch_expression_lhs.hpp
575 #define TWOBLUECUBES_CATCH_EXPRESSION_LHS_HPP_INCLUDED
576
577 // #included from: catch_expressionresult_builder.h
578 #define TWOBLUECUBES_CATCH_ASSERTIONRESULT_BUILDER_H_INCLUDED
579
580 // #included from: catch_tostring.h
581 #define TWOBLUECUBES_CATCH_TOSTRING_H_INCLUDED
582
583 // #included from: catch_sfinae.hpp
584 #define TWOBLUECUBES_CATCH_SFINAE_HPP_INCLUDED
585
586 // Try to detect if the current compiler supports SFINAE
587
588 namespace Catch {
589
590 struct TrueType {
591 static const bool value = true;
592 typedef void Enable;
593 char sizer[1];
594 };
595 struct FalseType {
596 static const bool value = false;
597 typedef void Disable;
598 char sizer[2];
599 };
600
601 #ifdef CATCH_CONFIG_SFINAE
602
603 template<bool> struct NotABooleanExpression;
604
605 template<bool c> struct If : NotABooleanExpression<c> {};
606 template<> struct If<true> : TrueType {};
607 template<> struct If<false> : FalseType {};
608
609 template<int size> struct SizedIf;
610 template<> struct SizedIf<sizeof(TrueType)> : TrueType {};
611 template<> struct SizedIf<sizeof(FalseType)> : FalseType {};
612
613 #endif // CATCH_CONFIG_SFINAE
614
615 } // end namespace Catch
616
617 #include <sstream>
618 #include <iomanip>
619 #include <limits>
620 #include <vector>
621 #include <cstddef>
622
623 #ifdef __OBJC__
624 // #included from: catch_objc_arc.hpp
625 #define TWOBLUECUBES_CATCH_OBJC_ARC_HPP_INCLUDED
626
627 #import <Foundation/Foundation.h>
628
629 #ifdef __has_feature
630 #define CATCH_ARC_ENABLED __has_feature(objc_arc)
631 #else
632 #define CATCH_ARC_ENABLED 0
633 #endif
634
635 void arcSafeRelease( NSObject* obj );
636 id performOptionalSelector( id obj, SEL sel );
637
638 #if !CATCH_ARC_ENABLED
639 inline void arcSafeRelease( NSObject* obj ) {
640 [obj release];
641 }
642 inline id performOptionalSelector( id obj, SEL sel ) {
643 if( [obj respondsToSelector: sel] )
644 return [obj performSelector: sel];
645 return nil;
646 }
647 #define CATCH_UNSAFE_UNRETAINED
648 #define CATCH_ARC_STRONG
649 #else
650 inline void arcSafeRelease( NSObject* ){}
651 inline id performOptionalSelector( id obj, SEL sel ) {
652 #ifdef __clang__
653 #pragma clang diagnostic push
654 #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
655 #endif
656 if( [obj respondsToSelector: sel] )
657 return [obj performSelector: sel];
658 #ifdef __clang__
659 #pragma clang diagnostic pop
660 #endif
661 return nil;
662 }
663 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
664 #define CATCH_ARC_STRONG __strong
665 #endif
666
667 #endif
668
669 namespace Catch {
670 namespace Detail {
671
672 // SFINAE is currently disabled by default for all compilers.
673 // If the non SFINAE version of IsStreamInsertable is ambiguous for you
674 // and your compiler supports SFINAE, try #defining CATCH_CONFIG_SFINAE
675 #ifdef CATCH_CONFIG_SFINAE
676
677 template<typename T>
678 class IsStreamInsertableHelper {
679 template<int N> struct TrueIfSizeable : TrueType {};
680
681 template<typename T2>
682 static TrueIfSizeable<sizeof((*(std::ostream*)0) << *((T2 const*)0))> dummy(T2*);
683 static FalseType dummy(...);
684
685 public:
686 typedef SizedIf<sizeof(dummy((T*)0))> type;
687 };
688
689 template<typename T>
690 struct IsStreamInsertable : IsStreamInsertableHelper<T>::type {};
691
692 #else
693
694 struct BorgType {
695 template<typename T> BorgType( T const& );
696 };
697
698 TrueType& testStreamable( std::ostream& );
699 FalseType testStreamable( FalseType );
700
701 FalseType operator<<( std::ostream const&, BorgType const& );
702
703 template<typename T>
704 struct IsStreamInsertable {
705 static std::ostream &s;
706 static T const&t;
707 enum { value = sizeof( testStreamable(s << t) ) == sizeof( TrueType ) };
708 };
709
710 #endif
711
712 template<bool C>
713 struct StringMakerBase {
714 template<typename T>
715 static std::string convert( T const& ) { return "{?}"; }
716 };
717
718 template<>
719 struct StringMakerBase<true> {
720 template<typename T>
721 static std::string convert( T const& _value ) {
722 std::ostringstream oss;
723 oss << _value;
724 return oss.str();
725 }
726 };
727
728 struct Endianness {
729 enum Arch { Big, Little };
730
731 static Arch which() {
732 union {
733 int asInt;
734 char asChar[sizeof (int)];
735 };
736
737 asInt = 1;
738 return ( asChar[sizeof(int)-1] == 1 ) ? Big : Little;
739 }
740 };
741
742 // Writes the raw memory into a string, considering endianness
743 template<typename T>
744 std::string rawMemoryToString( T value ) {
745 union {
746 T typedValue;
747 unsigned char bytes[sizeof(T)];
748 };
749
750 typedValue = value;
751
752 std::ostringstream oss;
753 oss << "0x";
754
755 int i = 0, end = sizeof(T), inc = 1;
756 if( Endianness::which() == Endianness::Little ) {
757 i = end-1;
758 end = inc = -1;
759 }
760 for( ; i != end; i += inc )
761 oss << std::hex << std::setw(2) << std::setfill('0') << (unsigned int)bytes[i];
762 return oss.str();
763 }
764
765 } // end namespace Detail
766
767 template<typename T>
768 std::string toString( T const& value );
769
770 template<typename T>
771 struct StringMaker :
772 Detail::StringMakerBase<Detail::IsStreamInsertable<T>::value> {};
773
774 template<typename T>
775 struct StringMaker<T*> {
776 template<typename U>
777 static std::string convert( U* p ) {
778 if( !p )
779 return INTERNAL_CATCH_STRINGIFY( NULL );
780 else
781 return Detail::rawMemoryToString( p );
782 }
783 };
784
785 template<typename R, typename C>
786 struct StringMaker<R C::*> {
787 static std::string convert( R C::* p ) {
788 if( !p )
789 return INTERNAL_CATCH_STRINGIFY( NULL );
790 else
791 return Detail::rawMemoryToString( p );
792 }
793 };
794
795 namespace Detail {
796 template<typename InputIterator>
797 std::string rangeToString( InputIterator first, InputIterator last );
798 }
799
800 template<typename T, typename Allocator>
801 struct StringMaker<std::vector<T, Allocator> > {
802 static std::string convert( std::vector<T,Allocator> const& v ) {
803 return Detail::rangeToString( v.begin(), v.end() );
804 }
805 };
806
807 namespace Detail {
808 template<typename T>
809 std::string makeString( T const& value ) {
810 return StringMaker<T>::convert( value );
811 }
812 } // end namespace Detail
813
814 /// \brief converts any type to a string
815 ///
816 /// The default template forwards on to ostringstream - except when an
817 /// ostringstream overload does not exist - in which case it attempts to detect
818 /// that and writes {?}.
819 /// Overload (not specialise) this template for custom typs that you don't want
820 /// to provide an ostream overload for.
821 template<typename T>
822 std::string toString( T const& value ) {
823 return StringMaker<T>::convert( value );
824 }
825
826 // Built in overloads
827
828 std::string toString( std::string const& value );
829 std::string toString( std::wstring const& value );
830 std::string toString( const char* const value );
831 std::string toString( char* const value );
832 std::string toString( int value );
833 std::string toString( unsigned long value );
834 std::string toString( unsigned int value );
835 std::string toString( const double value );
836 std::string toString( bool value );
837 std::string toString( char value );
838 std::string toString( signed char value );
839 std::string toString( unsigned char value );
840
841 #ifdef CATCH_CONFIG_CPP11_NULLPTR
842 std::string toString( std::nullptr_t );
843 #endif
844
845 #ifdef __OBJC__
846 std::string toString( NSString const * const& nsstring );
847 std::string toString( NSString * CATCH_ARC_STRONG const& nsstring );
848 std::string toString( NSObject* const& nsObject );
849 #endif
850
851 namespace Detail {
852 template<typename InputIterator>
853 std::string rangeToString( InputIterator first, InputIterator last ) {
854 std::ostringstream oss;
855 oss << "{ ";
856 if( first != last ) {
857 oss << toString( *first );
858 for( ++first ; first != last ; ++first ) {
859 oss << ", " << toString( *first );
860 }
861 }
862 oss << " }";
863 return oss.str();
864 }
865 }
866
867 } // end namespace Catch
868
869 // #included from: catch_assertionresult.h
870 #define TWOBLUECUBES_CATCH_ASSERTIONRESULT_H_INCLUDED
871
872 #include <string>
873 // #included from: catch_result_type.h
874 #define TWOBLUECUBES_CATCH_RESULT_TYPE_H_INCLUDED
875
876 namespace Catch {
877
878 // ResultWas::OfType enum
879 struct ResultWas { enum OfType {
880 Unknown = -1,
881 Ok = 0,
882 Info = 1,
883 Warning = 2,
884
885 FailureBit = 0x10,
886
887 ExpressionFailed = FailureBit | 1,
888 ExplicitFailure = FailureBit | 2,
889
890 Exception = 0x100 | FailureBit,
891
892 ThrewException = Exception | 1,
893 DidntThrowException = Exception | 2
894
895 }; };
896
897 inline bool isOk( ResultWas::OfType resultType ) {
898 return ( resultType & ResultWas::FailureBit ) == 0;
899 }
900 inline bool isJustInfo( int flags ) {
901 return flags == ResultWas::Info;
902 }
903
904 // ResultAction::Value enum
905 struct ResultAction { enum Value {
906 None,
907 Failed = 1, // Failure - but no debug break if Debug bit not set
908 Debug = 2, // If this bit is set, invoke the debugger
909 Abort = 4 // Test run should abort
910 }; };
911
912 // ResultDisposition::Flags enum
913 struct ResultDisposition { enum Flags {
914 Normal = 0x00,
915
916 ContinueOnFailure = 0x01, // Failures fail test, but execution continues
917 NegateResult = 0x02, // Prefix expressiom with !
918 SuppressFail = 0x04 // Failures are reported but do not fail the test
919 }; };
920
921 inline ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
922 return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
923 }
924
925 inline bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
926 inline bool shouldNegate( int flags ) { return ( flags & ResultDisposition::NegateResult ) != 0; }
927 inline bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
928
929 } // end namespace Catch
930
931
932 namespace Catch {
933
934 struct AssertionInfo
935 {
936 AssertionInfo() {}
937 AssertionInfo( std::string const& _macroName,
938 SourceLineInfo const& _lineInfo,
939 std::string const& _capturedExpression,
940 ResultDisposition::Flags _resultDisposition );
941
942 std::string macroName;
943 SourceLineInfo lineInfo;
944 std::string capturedExpression;
945 ResultDisposition::Flags resultDisposition;
946 };
947
948 struct AssertionResultData
949 {
950 AssertionResultData() : resultType( ResultWas::Unknown ) {}
951
952 std::string reconstructedExpression;
953 std::string message;
954 ResultWas::OfType resultType;
955 };
956
957 class AssertionResult {
958 public:
959 AssertionResult();
960 AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
961 ~AssertionResult();
962 # ifdef CATCH_CPP11_OR_GREATER
963 AssertionResult( AssertionResult const& ) = default;
964 AssertionResult( AssertionResult && ) = default;
965 AssertionResult& operator = ( AssertionResult const& ) = default;
966 AssertionResult& operator = ( AssertionResult && ) = default;
967 # endif
968
969 bool isOk() const;
970 bool succeeded() const;
971 ResultWas::OfType getResultType() const;
972 bool hasExpression() const;
973 bool hasMessage() const;
974 std::string getExpression() const;
975 std::string getExpressionInMacro() const;
976 bool hasExpandedExpression() const;
977 std::string getExpandedExpression() const;
978 std::string getMessage() const;
979 SourceLineInfo getSourceInfo() const;
980 std::string getTestMacroName() const;
981
982 protected:
983 AssertionInfo m_info;
984 AssertionResultData m_resultData;
985 };
986
987 } // end namespace Catch
988
989 // #included from: catch_evaluate.hpp
990 #define TWOBLUECUBES_CATCH_EVALUATE_HPP_INCLUDED
991
992 #ifdef _MSC_VER
993 #pragma warning(push)
994 #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
995 #endif
996
997 #include <cstddef>
998
999 namespace Catch {
1000 namespace Internal {
1001
1002 enum Operator {
1003 IsEqualTo,
1004 IsNotEqualTo,
1005 IsLessThan,
1006 IsGreaterThan,
1007 IsLessThanOrEqualTo,
1008 IsGreaterThanOrEqualTo
1009 };
1010
1011 template<Operator Op> struct OperatorTraits { static const char* getName(){ return "*error*"; } };
1012 template<> struct OperatorTraits<IsEqualTo> { static const char* getName(){ return "=="; } };
1013 template<> struct OperatorTraits<IsNotEqualTo> { static const char* getName(){ return "!="; } };
1014 template<> struct OperatorTraits<IsLessThan> { static const char* getName(){ return "<"; } };
1015 template<> struct OperatorTraits<IsGreaterThan> { static const char* getName(){ return ">"; } };
1016 template<> struct OperatorTraits<IsLessThanOrEqualTo> { static const char* getName(){ return "<="; } };
1017 template<> struct OperatorTraits<IsGreaterThanOrEqualTo>{ static const char* getName(){ return ">="; } };
1018
1019 template<typename T>
1020 inline T& opCast(T const& t) { return const_cast<T&>(t); }
1021
1022 // nullptr_t support based on pull request #154 from Konstantin Baumann
1023 #ifdef CATCH_CONFIG_CPP11_NULLPTR
1024 inline std::nullptr_t opCast(std::nullptr_t) { return nullptr; }
1025 #endif // CATCH_CONFIG_CPP11_NULLPTR
1026
1027 // So the compare overloads can be operator agnostic we convey the operator as a template
1028 // enum, which is used to specialise an Evaluator for doing the comparison.
1029 template<typename T1, typename T2, Operator Op>
1030 class Evaluator{};
1031
1032 template<typename T1, typename T2>
1033 struct Evaluator<T1, T2, IsEqualTo> {
1034 static bool evaluate( T1 const& lhs, T2 const& rhs) {
1035 return opCast( lhs ) == opCast( rhs );
1036 }
1037 };
1038 template<typename T1, typename T2>
1039 struct Evaluator<T1, T2, IsNotEqualTo> {
1040 static bool evaluate( T1 const& lhs, T2 const& rhs ) {
1041 return opCast( lhs ) != opCast( rhs );
1042 }
1043 };
1044 template<typename T1, typename T2>
1045 struct Evaluator<T1, T2, IsLessThan> {
1046 static bool evaluate( T1 const& lhs, T2 const& rhs ) {
1047 return opCast( lhs ) < opCast( rhs );
1048 }
1049 };
1050 template<typename T1, typename T2>
1051 struct Evaluator<T1, T2, IsGreaterThan> {
1052 static bool evaluate( T1 const& lhs, T2 const& rhs ) {
1053 return opCast( lhs ) > opCast( rhs );
1054 }
1055 };
1056 template<typename T1, typename T2>
1057 struct Evaluator<T1, T2, IsGreaterThanOrEqualTo> {
1058 static bool evaluate( T1 const& lhs, T2 const& rhs ) {
1059 return opCast( lhs ) >= opCast( rhs );
1060 }
1061 };
1062 template<typename T1, typename T2>
1063 struct Evaluator<T1, T2, IsLessThanOrEqualTo> {
1064 static bool evaluate( T1 const& lhs, T2 const& rhs ) {
1065 return opCast( lhs ) <= opCast( rhs );
1066 }
1067 };
1068
1069 template<Operator Op, typename T1, typename T2>
1070 bool applyEvaluator( T1 const& lhs, T2 const& rhs ) {
1071 return Evaluator<T1, T2, Op>::evaluate( lhs, rhs );
1072 }
1073
1074 // This level of indirection allows us to specialise for integer types
1075 // to avoid signed/ unsigned warnings
1076
1077 // "base" overload
1078 template<Operator Op, typename T1, typename T2>
1079 bool compare( T1 const& lhs, T2 const& rhs ) {
1080 return Evaluator<T1, T2, Op>::evaluate( lhs, rhs );
1081 }
1082
1083 // unsigned X to int
1084 template<Operator Op> bool compare( unsigned int lhs, int rhs ) {
1085 return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) );
1086 }
1087 template<Operator Op> bool compare( unsigned long lhs, int rhs ) {
1088 return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) );
1089 }
1090 template<Operator Op> bool compare( unsigned char lhs, int rhs ) {
1091 return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) );
1092 }
1093
1094 // unsigned X to long
1095 template<Operator Op> bool compare( unsigned int lhs, long rhs ) {
1096 return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) );
1097 }
1098 template<Operator Op> bool compare( unsigned long lhs, long rhs ) {
1099 return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) );
1100 }
1101 template<Operator Op> bool compare( unsigned char lhs, long rhs ) {
1102 return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) );
1103 }
1104
1105 // int to unsigned X
1106 template<Operator Op> bool compare( int lhs, unsigned int rhs ) {
1107 return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs );
1108 }
1109 template<Operator Op> bool compare( int lhs, unsigned long rhs ) {
1110 return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs );
1111 }
1112 template<Operator Op> bool compare( int lhs, unsigned char rhs ) {
1113 return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs );
1114 }
1115
1116 // long to unsigned X
1117 template<Operator Op> bool compare( long lhs, unsigned int rhs ) {
1118 return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
1119 }
1120 template<Operator Op> bool compare( long lhs, unsigned long rhs ) {
1121 return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
1122 }
1123 template<Operator Op> bool compare( long lhs, unsigned char rhs ) {
1124 return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
1125 }
1126
1127 // pointer to long (when comparing against NULL)
1128 template<Operator Op, typename T> bool compare( long lhs, T* rhs ) {
1129 return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs );
1130 }
1131 template<Operator Op, typename T> bool compare( T* lhs, long rhs ) {
1132 return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) );
1133 }
1134
1135 // pointer to int (when comparing against NULL)
1136 template<Operator Op, typename T> bool compare( int lhs, T* rhs ) {
1137 return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs );
1138 }
1139 template<Operator Op, typename T> bool compare( T* lhs, int rhs ) {
1140 return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) );
1141 }
1142
1143 #ifdef CATCH_CONFIG_CPP11_NULLPTR
1144 // pointer to nullptr_t (when comparing against nullptr)
1145 template<Operator Op, typename T> bool compare( std::nullptr_t, T* rhs ) {
1146 return Evaluator<T*, T*, Op>::evaluate( NULL, rhs );
1147 }
1148 template<Operator Op, typename T> bool compare( T* lhs, std::nullptr_t ) {
1149 return Evaluator<T*, T*, Op>::evaluate( lhs, NULL );
1150 }
1151 #endif // CATCH_CONFIG_CPP11_NULLPTR
1152
1153 } // end of namespace Internal
1154 } // end of namespace Catch
1155
1156 #ifdef _MSC_VER
1157 #pragma warning(pop)
1158 #endif
1159
1160 namespace Catch {
1161
1162 struct STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison;
1163
1164 // Wraps the (stringised versions of) the lhs, operator and rhs of an expression - as well as
1165 // the result of evaluating it. This is used to build an AssertionResult object
1166 class ExpressionResultBuilder {
1167 public:
1168
1169 ExpressionResultBuilder( ResultWas::OfType resultType = ResultWas::Unknown );
1170 ExpressionResultBuilder( ExpressionResultBuilder const& other );
1171 ExpressionResultBuilder& operator=(ExpressionResultBuilder const& other );
1172
1173 ExpressionResultBuilder& setResultType( ResultWas::OfType result );
1174 ExpressionResultBuilder& setResultType( bool result );
1175 ExpressionResultBuilder& setLhs( std::string const& lhs );
1176 ExpressionResultBuilder& setRhs( std::string const& rhs );
1177 ExpressionResultBuilder& setOp( std::string const& op );
1178
1179 ExpressionResultBuilder& endExpression( ResultDisposition::Flags resultDisposition );
1180
1181 template<typename T>
1182 ExpressionResultBuilder& operator << ( T const& value ) {
1183 m_stream << value;
1184 return *this;
1185 }
1186
1187 std::string reconstructExpression( AssertionInfo const& info ) const;
1188
1189 AssertionResult buildResult( AssertionInfo const& info ) const;
1190
1191 template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& );
1192 template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& );
1193
1194 private:
1195 AssertionResultData m_data;
1196 struct ExprComponents {
1197 ExprComponents() : shouldNegate( false ) {}
1198 bool shouldNegate;
1199 std::string lhs, rhs, op;
1200 } m_exprComponents;
1201 std::ostringstream m_stream;
1202 };
1203
1204 } // end namespace Catch
1205
1206 namespace Catch {
1207
1208 // Wraps the LHS of an expression and captures the operator and RHS (if any) -
1209 // wrapping them all in an ExpressionResultBuilder object
1210 template<typename T>
1211 class ExpressionLhs {
1212 ExpressionLhs& operator = ( ExpressionLhs const& );
1213 # ifdef CATCH_CPP11_OR_GREATER
1214 ExpressionLhs& operator = ( ExpressionLhs && ) = delete;
1215 # endif
1216
1217 public:
1218 ExpressionLhs( T lhs ) : m_lhs( lhs ) {}
1219 # ifdef CATCH_CPP11_OR_GREATER
1220 ExpressionLhs( ExpressionLhs const& ) = default;
1221 ExpressionLhs( ExpressionLhs && ) = default;
1222 # endif
1223
1224 template<typename RhsT>
1225 ExpressionResultBuilder& operator == ( RhsT const& rhs ) {
1226 return captureExpression<Internal::IsEqualTo>( rhs );
1227 }
1228
1229 template<typename RhsT>
1230 ExpressionResultBuilder& operator != ( RhsT const& rhs ) {
1231 return captureExpression<Internal::IsNotEqualTo>( rhs );
1232 }
1233
1234 template<typename RhsT>
1235 ExpressionResultBuilder& operator < ( RhsT const& rhs ) {
1236 return captureExpression<Internal::IsLessThan>( rhs );
1237 }
1238
1239 template<typename RhsT>
1240 ExpressionResultBuilder& operator > ( RhsT const& rhs ) {
1241 return captureExpression<Internal::IsGreaterThan>( rhs );
1242 }
1243
1244 template<typename RhsT>
1245 ExpressionResultBuilder& operator <= ( RhsT const& rhs ) {
1246 return captureExpression<Internal::IsLessThanOrEqualTo>( rhs );
1247 }
1248
1249 template<typename RhsT>
1250 ExpressionResultBuilder& operator >= ( RhsT const& rhs ) {
1251 return captureExpression<Internal::IsGreaterThanOrEqualTo>( rhs );
1252 }
1253
1254 ExpressionResultBuilder& operator == ( bool rhs ) {
1255 return captureExpression<Internal::IsEqualTo>( rhs );
1256 }
1257
1258 ExpressionResultBuilder& operator != ( bool rhs ) {
1259 return captureExpression<Internal::IsNotEqualTo>( rhs );
1260 }
1261
1262 ExpressionResultBuilder& endExpression( ResultDisposition::Flags resultDisposition ) {
1263 bool value = m_lhs ? true : false;
1264 return m_result
1265 .setLhs( Catch::toString( value ) )
1266 .setResultType( value )
1267 .endExpression( resultDisposition );
1268 }
1269
1270 // Only simple binary expressions are allowed on the LHS.
1271 // If more complex compositions are required then place the sub expression in parentheses
1272 template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator + ( RhsT const& );
1273 template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator - ( RhsT const& );
1274 template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator / ( RhsT const& );
1275 template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator * ( RhsT const& );
1276 template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& );
1277 template<typename RhsT> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& );
1278
1279 private:
1280 template<Internal::Operator Op, typename RhsT>
1281 ExpressionResultBuilder& captureExpression( RhsT const& rhs ) {
1282 return m_result
1283 .setResultType( Internal::compare<Op>( m_lhs, rhs ) )
1284 .setLhs( Catch::toString( m_lhs ) )
1285 .setRhs( Catch::toString( rhs ) )
1286 .setOp( Internal::OperatorTraits<Op>::getName() );
1287 }
1288
1289 private:
1290 ExpressionResultBuilder m_result;
1291 T m_lhs;
1292 };
1293
1294 } // end namespace Catch
1295
1296 namespace Catch {
1297
1298 // Captures the LHS of the expression and wraps it in an Expression Lhs object
1299 class ExpressionDecomposer {
1300 public:
1301
1302 template<typename T>
1303 ExpressionLhs<T const&> operator->* ( T const& operand ) {
1304 return ExpressionLhs<T const&>( operand );
1305 }
1306
1307 ExpressionLhs<bool> operator->* ( bool value ) {
1308 return ExpressionLhs<bool>( value );
1309 }
1310 };
1311
1312 } // end namespace Catch
1313
1314 // #included from: catch_message.h
1315 #define TWOBLUECUBES_CATCH_MESSAGE_H_INCLUDED
1316
1317 #include <string>
1318
1319 namespace Catch {
1320
1321 struct MessageInfo {
1322 MessageInfo( std::string const& _macroName,
1323 SourceLineInfo const& _lineInfo,
1324 ResultWas::OfType _type );
1325
1326 std::string macroName;
1327 SourceLineInfo lineInfo;
1328 ResultWas::OfType type;
1329 std::string message;
1330 unsigned int sequence;
1331
1332 bool operator == ( MessageInfo const& other ) const {
1333 return sequence == other.sequence;
1334 }
1335 bool operator < ( MessageInfo const& other ) const {
1336 return sequence < other.sequence;
1337 }
1338 private:
1339 static unsigned int globalCount;
1340 };
1341
1342 struct MessageBuilder {
1343 MessageBuilder( std::string const& macroName,
1344 SourceLineInfo const& lineInfo,
1345 ResultWas::OfType type )
1346 : m_info( macroName, lineInfo, type )
1347 {}
1348
1349 template<typename T>
1350 MessageBuilder& operator << ( T const& value ) {
1351 m_stream << value;
1352 return *this;
1353 }
1354
1355 MessageInfo m_info;
1356 std::ostringstream m_stream;
1357 };
1358
1359 class ScopedMessage {
1360 public:
1361 ScopedMessage( MessageBuilder const& builder );
1362 ~ScopedMessage();
1363
1364 MessageInfo m_info;
1365 };
1366
1367 } // end namespace Catch
1368
1369 // #included from: catch_interfaces_capture.h
1370 #define TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED
1371
1372 #include <string>
1373
1374 namespace Catch {
1375
1376 class TestCase;
1377 class ExpressionResultBuilder;
1378 class AssertionResult;
1379 struct AssertionInfo;
1380 struct SectionInfo;
1381 struct MessageInfo;
1382 class ScopedMessageBuilder;
1383 struct Counts;
1384
1385 struct IResultCapture {
1386
1387 virtual ~IResultCapture();
1388
1389 virtual void assertionEnded( AssertionResult const& result ) = 0;
1390 virtual bool sectionStarted( SectionInfo const& sectionInfo,
1391 Counts& assertions ) = 0;
1392 virtual void sectionEnded( SectionInfo const& name, Counts const& assertions, double _durationInSeconds ) = 0;
1393 virtual void pushScopedMessage( MessageInfo const& message ) = 0;
1394 virtual void popScopedMessage( MessageInfo const& message ) = 0;
1395
1396 virtual bool shouldDebugBreak() const = 0;
1397
1398 virtual ResultAction::Value acceptExpression( ExpressionResultBuilder const& assertionResult, AssertionInfo const& assertionInfo ) = 0;
1399
1400 virtual std::string getCurrentTestName() const = 0;
1401 virtual const AssertionResult* getLastResult() const = 0;
1402 };
1403 }
1404
1405 // #included from: catch_debugger.h
1406 #define TWOBLUECUBES_CATCH_DEBUGGER_H_INCLUDED
1407
1408 // #included from: catch_platform.h
1409 #define TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED
1410
1411 #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
1412 #define CATCH_PLATFORM_MAC
1413 #elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
1414 #define CATCH_PLATFORM_IPHONE
1415 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
1416 #define CATCH_PLATFORM_WINDOWS
1417 #endif
1418
1419 #include <string>
1420
1421 namespace Catch{
1422
1423 bool isDebuggerActive();
1424 void writeToDebugConsole( std::string const& text );
1425 }
1426
1427 #ifdef CATCH_PLATFORM_MAC
1428
1429 // The following code snippet based on:
1430 // http://cocoawithlove.com/2008/03/break-into-debugger.html
1431 #ifdef DEBUG
1432 #if defined(__ppc64__) || defined(__ppc__)
1433 #define CATCH_BREAK_INTO_DEBUGGER() \
1434 if( Catch::isDebuggerActive() ) { \
1435 __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \
1436 : : : "memory","r0","r3","r4" ); \
1437 }
1438 #else
1439 #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) {__asm__("int $3\n" : : );}
1440 #endif
1441 #endif
1442
1443 #elif defined(_MSC_VER)
1444 #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { __debugbreak(); }
1445 #elif defined(__MINGW32__)
1446 extern "C" __declspec(dllimport) void __stdcall DebugBreak();
1447 #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { DebugBreak(); }
1448 #endif
1449
1450 #ifndef CATCH_BREAK_INTO_DEBUGGER
1451 #define CATCH_BREAK_INTO_DEBUGGER() Catch::isTrue( true );
1452 #endif
1453
1454 // #included from: catch_interfaces_registry_hub.h
1455 #define TWOBLUECUBES_CATCH_INTERFACES_REGISTRY_HUB_H_INCLUDED
1456
1457 #include <string>
1458
1459 namespace Catch {
1460
1461 class TestCase;
1462 struct ITestCaseRegistry;
1463 struct IExceptionTranslatorRegistry;
1464 struct IExceptionTranslator;
1465 struct IReporterRegistry;
1466 struct IReporterFactory;
1467
1468 struct IRegistryHub {
1469 virtual ~IRegistryHub();
1470
1471 virtual IReporterRegistry const& getReporterRegistry() const = 0;
1472 virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
1473 virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0;
1474 };
1475
1476 struct IMutableRegistryHub {
1477 virtual ~IMutableRegistryHub();
1478 virtual void registerReporter( std::string const& name, IReporterFactory* factory ) = 0;
1479 virtual void registerTest( TestCase const& testInfo ) = 0;
1480 virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
1481 };
1482
1483 IRegistryHub& getRegistryHub();
1484 IMutableRegistryHub& getMutableRegistryHub();
1485 void cleanUp();
1486 std::string translateActiveException();
1487
1488 }
1489
1490 // #included from: catch_interfaces_config.h
1491 #define TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED
1492
1493 #include <iostream>
1494 #include <string>
1495 #include <vector>
1496
1497 namespace Catch {
1498
1499 struct Verbosity { enum Level {
1500 NoOutput = 0,
1501 Quiet,
1502 Normal
1503 }; };
1504
1505 struct WarnAbout { enum What {
1506 Nothing = 0x00,
1507 NoAssertions = 0x01
1508 }; };
1509
1510 struct ShowDurations { enum OrNot {
1511 DefaultForReporter,
1512 Always,
1513 Never
1514 }; };
1515
1516 class TestCaseFilters;
1517
1518 struct IConfig : IShared {
1519
1520 virtual ~IConfig();
1521
1522 virtual bool allowThrows() const = 0;
1523 virtual std::ostream& stream() const = 0;
1524 virtual std::string name() const = 0;
1525 virtual bool includeSuccessfulResults() const = 0;
1526 virtual bool shouldDebugBreak() const = 0;
1527 virtual bool warnAboutMissingAssertions() const = 0;
1528 virtual int abortAfter() const = 0;
1529 virtual bool showInvisibles() const = 0;
1530 virtual ShowDurations::OrNot showDurations() const = 0;
1531 virtual std::vector<TestCaseFilters> const& filters() const = 0;
1532 };
1533 }
1534
1535 #include <ostream>
1536
1537 namespace Catch {
1538
1539 inline IResultCapture& getResultCapture() {
1540 return getCurrentContext().getResultCapture();
1541 }
1542
1543 template<typename MatcherT>
1544 ExpressionResultBuilder expressionResultBuilderFromMatcher( MatcherT const& matcher,
1545 std::string const& matcherCallAsString ) {
1546 std::string matcherAsString = matcher.toString();
1547 if( matcherAsString == "{?}" )
1548 matcherAsString = matcherCallAsString;
1549 return ExpressionResultBuilder()
1550 .setRhs( matcherAsString )
1551 .setOp( "matches" );
1552 }
1553
1554 template<typename MatcherT, typename ArgT>
1555 ExpressionResultBuilder expressionResultBuilderFromMatcher( MatcherT const& matcher,
1556 ArgT const& arg,
1557 std::string const& matcherCallAsString ) {
1558 return expressionResultBuilderFromMatcher( matcher, matcherCallAsString )
1559 .setLhs( Catch::toString( arg ) )
1560 .setResultType( matcher.match( arg ) );
1561 }
1562
1563 template<typename MatcherT, typename ArgT>
1564 ExpressionResultBuilder expressionResultBuilderFromMatcher( MatcherT const& matcher,
1565 ArgT* arg,
1566 std::string const& matcherCallAsString ) {
1567 return expressionResultBuilderFromMatcher( matcher, matcherCallAsString )
1568 .setLhs( Catch::toString( arg ) )
1569 .setResultType( matcher.match( arg ) );
1570 }
1571
1572 struct TestFailureException{};
1573
1574 } // end namespace Catch
1575
1576 ///////////////////////////////////////////////////////////////////////////////
1577 #define INTERNAL_CATCH_ACCEPT_EXPR( evaluatedExpr, resultDisposition, originalExpr ) \
1578 if( Catch::ResultAction::Value internal_catch_action = Catch::getResultCapture().acceptExpression( evaluatedExpr, __assertionInfo ) ) { \
1579 if( internal_catch_action & Catch::ResultAction::Debug ) CATCH_BREAK_INTO_DEBUGGER(); \
1580 if( internal_catch_action & Catch::ResultAction::Abort ) throw Catch::TestFailureException(); \
1581 if( !Catch::shouldContinueOnFailure( resultDisposition ) ) throw Catch::TestFailureException(); \
1582 Catch::isTrue( false && originalExpr ); \
1583 }
1584
1585 ///////////////////////////////////////////////////////////////////////////////
1586 #define INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ) \
1587 do { \
1588 Catch::AssertionInfo __assertionInfo( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
1589 try { \
1590 INTERNAL_CATCH_ACCEPT_EXPR( ( Catch::ExpressionDecomposer()->*expr ).endExpression( resultDisposition ), resultDisposition, expr ); \
1591 } catch( Catch::TestFailureException& ) { \
1592 throw; \
1593 } catch( ... ) { \
1594 INTERNAL_CATCH_ACCEPT_EXPR( Catch::ExpressionResultBuilder( Catch::ResultWas::ThrewException ) << Catch::translateActiveException(), \
1595 Catch::ResultDisposition::Normal, expr ); \
1596 } \
1597 } while( Catch::isTrue( false ) )
1598
1599 ///////////////////////////////////////////////////////////////////////////////
1600 #define INTERNAL_CATCH_IF( expr, resultDisposition, macroName ) \
1601 INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ); \
1602 if( Catch::getResultCapture().getLastResult()->succeeded() )
1603
1604 ///////////////////////////////////////////////////////////////////////////////
1605 #define INTERNAL_CATCH_ELSE( expr, resultDisposition, macroName ) \
1606 INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ); \
1607 if( !Catch::getResultCapture().getLastResult()->succeeded() )
1608
1609 ///////////////////////////////////////////////////////////////////////////////
1610 #define INTERNAL_CATCH_NO_THROW( expr, resultDisposition, macroName ) \
1611 do { \
1612 Catch::AssertionInfo __assertionInfo( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
1613 try { \
1614 expr; \
1615 INTERNAL_CATCH_ACCEPT_EXPR( Catch::ExpressionResultBuilder( Catch::ResultWas::Ok ), resultDisposition, false ); \
1616 } \
1617 catch( ... ) { \
1618 INTERNAL_CATCH_ACCEPT_EXPR( Catch::ExpressionResultBuilder( Catch::ResultWas::ThrewException ) << Catch::translateActiveException(), resultDisposition, false ); \
1619 } \
1620 } while( Catch::isTrue( false ) )
1621
1622 ///////////////////////////////////////////////////////////////////////////////
1623 #define INTERNAL_CATCH_THROWS_IMPL( expr, exceptionType, resultDisposition ) \
1624 try { \
1625 if( Catch::getCurrentContext().getConfig()->allowThrows() ) { \
1626 expr; \
1627 INTERNAL_CATCH_ACCEPT_EXPR( Catch::ExpressionResultBuilder( Catch::ResultWas::DidntThrowException ), resultDisposition, false ); \
1628 } \
1629 } \
1630 catch( Catch::TestFailureException& ) { \
1631 throw; \
1632 } \
1633 catch( exceptionType ) { \
1634 INTERNAL_CATCH_ACCEPT_EXPR( Catch::ExpressionResultBuilder( Catch::ResultWas::Ok ), resultDisposition, false ); \
1635 }
1636
1637 ///////////////////////////////////////////////////////////////////////////////
1638 #define INTERNAL_CATCH_THROWS( expr, exceptionType, resultDisposition, macroName ) \
1639 do { \
1640 Catch::AssertionInfo __assertionInfo( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
1641 INTERNAL_CATCH_THROWS_IMPL( expr, exceptionType, resultDisposition ) \
1642 } while( Catch::isTrue( false ) )
1643
1644 ///////////////////////////////////////////////////////////////////////////////
1645 #define INTERNAL_CATCH_THROWS_AS( expr, exceptionType, resultDisposition, macroName ) \
1646 do { \
1647 Catch::AssertionInfo __assertionInfo( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
1648 INTERNAL_CATCH_THROWS_IMPL( expr, exceptionType, resultDisposition ) \
1649 catch( ... ) { \
1650 INTERNAL_CATCH_ACCEPT_EXPR( ( Catch::ExpressionResultBuilder( Catch::ResultWas::ThrewException ) << Catch::translateActiveException() ), \
1651 resultDisposition | Catch::ResultDisposition::ContinueOnFailure, false ); \
1652 } \
1653 } while( Catch::isTrue( false ) )
1654
1655 ///////////////////////////////////////////////////////////////////////////////
1656 #ifdef CATCH_CONFIG_VARIADIC_MACROS
1657 #define INTERNAL_CATCH_MSG( messageType, resultDisposition, macroName, ... ) \
1658 do { \
1659 Catch::AssertionInfo __assertionInfo( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
1660 INTERNAL_CATCH_ACCEPT_EXPR( Catch::ExpressionResultBuilder( messageType ) << __VA_ARGS__ +::Catch::StreamEndStop(), resultDisposition, true ) \
1661 } while( Catch::isTrue( false ) )
1662 #else
1663 #define INTERNAL_CATCH_MSG( messageType, resultDisposition, macroName, log ) \
1664 do { \
1665 Catch::AssertionInfo __assertionInfo( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
1666 INTERNAL_CATCH_ACCEPT_EXPR( Catch::ExpressionResultBuilder( messageType ) << log, resultDisposition, true ) \
1667 } while( Catch::isTrue( false ) )
1668 #endif
1669
1670 ///////////////////////////////////////////////////////////////////////////////
1671 #define INTERNAL_CATCH_INFO( log, macroName ) \
1672 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage ) = Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log;
1673
1674 ///////////////////////////////////////////////////////////////////////////////
1675 #define INTERNAL_CHECK_THAT( arg, matcher, resultDisposition, macroName ) \
1676 do { \
1677 Catch::AssertionInfo __assertionInfo( macroName, CATCH_INTERNAL_LINEINFO, #arg " " #matcher, resultDisposition ); \
1678 try { \
1679 INTERNAL_CATCH_ACCEPT_EXPR( ( Catch::expressionResultBuilderFromMatcher( ::Catch::Matchers::matcher, arg, #matcher ) ), resultDisposition, false ); \
1680 } catch( Catch::TestFailureException& ) { \
1681 throw; \
1682 } catch( ... ) { \
1683 INTERNAL_CATCH_ACCEPT_EXPR( ( Catch::ExpressionResultBuilder( Catch::ResultWas::ThrewException ) << Catch::translateActiveException() ), \
1684 resultDisposition | Catch::ResultDisposition::ContinueOnFailure, false ); \
1685 } \
1686 } while( Catch::isTrue( false ) )
1687
1688 // #included from: internal/catch_section.h
1689 #define TWOBLUECUBES_CATCH_SECTION_H_INCLUDED
1690
1691 // #included from: catch_section_info.h
1692 #define TWOBLUECUBES_CATCH_SECTION_INFO_H_INCLUDED
1693
1694 namespace Catch {
1695
1696 struct SectionInfo {
1697 SectionInfo( std::string const& _name,
1698 std::string const& _description,
1699 SourceLineInfo const& _lineInfo )
1700 : name( _name ),
1701 description( _description ),
1702 lineInfo( _lineInfo )
1703 {}
1704
1705 std::string name;
1706 std::string description;
1707 SourceLineInfo lineInfo;
1708 };
1709
1710 } // end namespace Catch
1711
1712 // #included from: catch_totals.hpp
1713 #define TWOBLUECUBES_CATCH_TOTALS_HPP_INCLUDED
1714
1715 #include <cstddef>
1716
1717 namespace Catch {
1718
1719 struct Counts {
1720 Counts() : passed( 0 ), failed( 0 ) {}
1721
1722 Counts operator - ( Counts const& other ) const {
1723 Counts diff;
1724 diff.passed = passed - other.passed;
1725 diff.failed = failed - other.failed;
1726 return diff;
1727 }
1728 Counts& operator += ( Counts const& other ) {
1729 passed += other.passed;
1730 failed += other.failed;
1731 return *this;
1732 }
1733
1734 std::size_t total() const {
1735 return passed + failed;
1736 }
1737
1738 std::size_t passed;
1739 std::size_t failed;
1740 };
1741
1742 struct Totals {
1743
1744 Totals operator - ( Totals const& other ) const {
1745 Totals diff;
1746 diff.assertions = assertions - other.assertions;
1747 diff.testCases = testCases - other.testCases;
1748 return diff;
1749 }
1750
1751 Totals delta( Totals const& prevTotals ) const {
1752 Totals diff = *this - prevTotals;
1753 if( diff.assertions.failed > 0 )
1754 ++diff.testCases.failed;
1755 else
1756 ++diff.testCases.passed;
1757 return diff;
1758 }
1759
1760 Totals& operator += ( Totals const& other ) {
1761 assertions += other.assertions;
1762 testCases += other.testCases;
1763 return *this;
1764 }
1765
1766 Counts assertions;
1767 Counts testCases;
1768 };
1769 }
1770
1771 // #included from: catch_timer.h
1772 #define TWOBLUECUBES_CATCH_TIMER_H_INCLUDED
1773
1774 #ifdef CATCH_PLATFORM_WINDOWS
1775 typedef unsigned long long uint64_t;
1776 #else
1777 #include <stdint.h>
1778 #endif
1779
1780 namespace Catch {
1781
1782 class Timer {
1783 public:
1784 Timer() : m_ticks( 0 ) {}
1785 void start();
1786 unsigned int getElapsedNanoseconds() const;
1787 unsigned int getElapsedMilliseconds() const;
1788 double getElapsedSeconds() const;
1789
1790 private:
1791 uint64_t m_ticks;
1792 };
1793
1794 } // namespace Catch
1795
1796 #include <string>
1797
1798 namespace Catch {
1799
1800 class Section {
1801 public:
1802 Section( SourceLineInfo const& lineInfo,
1803 std::string const& name,
1804 std::string const& description = "" );
1805 ~Section();
1806 # ifdef CATCH_CPP11_OR_GREATER
1807 Section( Section const& ) = default;
1808 Section( Section && ) = default;
1809 Section& operator = ( Section const& ) = default;
1810 Section& operator = ( Section && ) = default;
1811 # endif
1812
1813 // This indicates whether the section should be executed or not
1814 operator bool();
1815
1816 private:
1817
1818 SectionInfo m_info;
1819
1820 std::string m_name;
1821 Counts m_assertions;
1822 bool m_sectionIncluded;
1823 Timer m_timer;
1824 };
1825
1826 } // end namespace Catch
1827
1828 #ifdef CATCH_CONFIG_VARIADIC_MACROS
1829 #define INTERNAL_CATCH_SECTION( ... ) \
1830 if( Catch::Section INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::Section( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) )
1831 #else
1832 #define INTERNAL_CATCH_SECTION( name, desc ) \
1833 if( Catch::Section INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::Section( CATCH_INTERNAL_LINEINFO, name, desc ) )
1834 #endif
1835
1836 // #included from: internal/catch_generators.hpp
1837 #define TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED
1838
1839 #include <iterator>
1840 #include <vector>
1841 #include <string>
1842 #include <stdlib.h>
1843
1844 namespace Catch {
1845
1846 template<typename T>
1847 struct IGenerator {
1848 virtual ~IGenerator() {}
1849 virtual T getValue( std::size_t index ) const = 0;
1850 virtual std::size_t size () const = 0;
1851 };
1852
1853 template<typename T>
1854 class BetweenGenerator : public IGenerator<T> {
1855 public:
1856 BetweenGenerator( T from, T to ) : m_from( from ), m_to( to ){}
1857
1858 virtual T getValue( std::size_t index ) const {
1859 return m_from+static_cast<int>( index );
1860 }
1861
1862 virtual std::size_t size() const {
1863 return static_cast<std::size_t>( 1+m_to-m_from );
1864 }
1865
1866 private:
1867
1868 T m_from;
1869 T m_to;
1870 };
1871
1872 template<typename T>
1873 class ValuesGenerator : public IGenerator<T> {
1874 public:
1875 ValuesGenerator(){}
1876
1877 void add( T value ) {
1878 m_values.push_back( value );
1879 }
1880
1881 virtual T getValue( std::size_t index ) const {
1882 return m_values[index];
1883 }
1884
1885 virtual std::size_t size() const {
1886 return m_values.size();
1887 }
1888
1889 private:
1890 std::vector<T> m_values;
1891 };
1892
1893 template<typename T>
1894 class CompositeGenerator {
1895 public:
1896 CompositeGenerator() : m_totalSize( 0 ) {}
1897
1898 // *** Move semantics, similar to auto_ptr ***
1899 CompositeGenerator( CompositeGenerator& other )
1900 : m_fileInfo( other.m_fileInfo ),
1901 m_totalSize( 0 )
1902 {
1903 move( other );
1904 }
1905
1906 CompositeGenerator& setFileInfo( const char* fileInfo ) {
1907 m_fileInfo = fileInfo;
1908 return *this;
1909 }
1910
1911 ~CompositeGenerator() {
1912 deleteAll( m_composed );
1913 }
1914
1915 operator T () const {
1916 size_t overallIndex = getCurrentContext().getGeneratorIndex( m_fileInfo, m_totalSize );
1917
1918 typename std::vector<const IGenerator<T>*>::const_iterator it = m_composed.begin();
1919 typename std::vector<const IGenerator<T>*>::const_iterator itEnd = m_composed.end();
1920 for( size_t index = 0; it != itEnd; ++it )
1921 {
1922 const IGenerator<T>* generator = *it;
1923 if( overallIndex >= index && overallIndex < index + generator->size() )
1924 {
1925 return generator->getValue( overallIndex-index );
1926 }
1927 index += generator->size();
1928 }
1929 CATCH_INTERNAL_ERROR( "Indexed past end of generated range" );
1930 return T(); // Suppress spurious "not all control paths return a value" warning in Visual Studio - if you know how to fix this please do so
1931 }
1932
1933 void add( const IGenerator<T>* generator ) {
1934 m_totalSize += generator->size();
1935 m_composed.push_back( generator );
1936 }
1937
1938 CompositeGenerator& then( CompositeGenerator& other ) {
1939 move( other );
1940 return *this;
1941 }
1942
1943 CompositeGenerator& then( T value ) {
1944 ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>();
1945 valuesGen->add( value );
1946 add( valuesGen );
1947 return *this;
1948 }
1949
1950 private:
1951
1952 void move( CompositeGenerator& other ) {
1953 std::copy( other.m_composed.begin(), other.m_composed.end(), std::back_inserter( m_composed ) );
1954 m_totalSize += other.m_totalSize;
1955 other.m_composed.clear();
1956 }
1957
1958 std::vector<const IGenerator<T>*> m_composed;
1959 std::string m_fileInfo;
1960 size_t m_totalSize;
1961 };
1962
1963 namespace Generators
1964 {
1965 template<typename T>
1966 CompositeGenerator<T> between( T from, T to ) {
1967 CompositeGenerator<T> generators;
1968 generators.add( new BetweenGenerator<T>( from, to ) );
1969 return generators;
1970 }
1971
1972 template<typename T>
1973 CompositeGenerator<T> values( T val1, T val2 ) {
1974 CompositeGenerator<T> generators;
1975 ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>();
1976 valuesGen->add( val1 );
1977 valuesGen->add( val2 );
1978 generators.add( valuesGen );
1979 return generators;
1980 }
1981
1982 template<typename T>
1983 CompositeGenerator<T> values( T val1, T val2, T val3 ){
1984 CompositeGenerator<T> generators;
1985 ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>();
1986 valuesGen->add( val1 );
1987 valuesGen->add( val2 );
1988 valuesGen->add( val3 );
1989 generators.add( valuesGen );
1990 return generators;
1991 }
1992
1993 template<typename T>
1994 CompositeGenerator<T> values( T val1, T val2, T val3, T val4 ) {
1995 CompositeGenerator<T> generators;
1996 ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>();
1997 valuesGen->add( val1 );
1998 valuesGen->add( val2 );
1999 valuesGen->add( val3 );
2000 valuesGen->add( val4 );
2001 generators.add( valuesGen );
2002 return generators;
2003 }
2004
2005 } // end namespace Generators
2006
2007 using namespace Generators;
2008
2009 } // end namespace Catch
2010
2011 #define INTERNAL_CATCH_LINESTR2( line ) #line
2012 #define INTERNAL_CATCH_LINESTR( line ) INTERNAL_CATCH_LINESTR2( line )
2013
2014 #define INTERNAL_CATCH_GENERATE( expr ) expr.setFileInfo( __FILE__ "(" INTERNAL_CATCH_LINESTR( __LINE__ ) ")" )
2015
2016 // #included from: internal/catch_interfaces_exception.h
2017 #define TWOBLUECUBES_CATCH_INTERFACES_EXCEPTION_H_INCLUDED
2018
2019 #include <string>
2020
2021 namespace Catch {
2022
2023 typedef std::string(*exceptionTranslateFunction)();
2024
2025 struct IExceptionTranslator {
2026 virtual ~IExceptionTranslator();
2027 virtual std::string translate() const = 0;
2028 };
2029
2030 struct IExceptionTranslatorRegistry {
2031 virtual ~IExceptionTranslatorRegistry();
2032
2033 virtual std::string translateActiveException() const = 0;
2034 };
2035
2036 class ExceptionTranslatorRegistrar {
2037 template<typename T>
2038 class ExceptionTranslator : public IExceptionTranslator {
2039 public:
2040
2041 ExceptionTranslator( std::string(*translateFunction)( T& ) )
2042 : m_translateFunction( translateFunction )
2043 {}
2044
2045 virtual std::string translate() const {
2046 try {
2047 throw;
2048 }
2049 catch( T& ex ) {
2050 return m_translateFunction( ex );
2051 }
2052 }
2053
2054 protected:
2055 std::string(*m_translateFunction)( T& );
2056 };
2057
2058 public:
2059 template<typename T>
2060 ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
2061 getMutableRegistryHub().registerTranslator
2062 ( new ExceptionTranslator<T>( translateFunction ) );
2063 }
2064 };
2065 }
2066
2067 ///////////////////////////////////////////////////////////////////////////////
2068 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) \
2069 static std::string INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator )( signature ); \
2070 namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ) ); }\
2071 static std::string INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator )( signature )
2072
2073 // #included from: internal/catch_approx.hpp
2074 #define TWOBLUECUBES_CATCH_APPROX_HPP_INCLUDED
2075
2076 #include <cmath>
2077 #include <limits>
2078
2079 namespace Catch {
2080 namespace Detail {
2081
2082 class Approx {
2083 public:
2084 explicit Approx ( double value )
2085 : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
2086 m_scale( 1.0 ),
2087 m_value( value )
2088 {}
2089
2090 Approx( Approx const& other )
2091 : m_epsilon( other.m_epsilon ),
2092 m_scale( other.m_scale ),
2093 m_value( other.m_value )
2094 {}
2095
2096 static Approx custom() {
2097 return Approx( 0 );
2098 }
2099
2100 Approx operator()( double value ) {
2101 Approx approx( value );
2102 approx.epsilon( m_epsilon );
2103 approx.scale( m_scale );
2104 return approx;
2105 }
2106
2107 friend bool operator == ( double lhs, Approx const& rhs ) {
2108 // Thanks to Richard Harris for his help refining this formula
2109 return fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( fabs(lhs), fabs(rhs.m_value) ) );
2110 }
2111
2112 friend bool operator == ( Approx const& lhs, double rhs ) {
2113 return operator==( rhs, lhs );
2114 }
2115
2116 friend bool operator != ( double lhs, Approx const& rhs ) {
2117 return !operator==( lhs, rhs );
2118 }
2119
2120 friend bool operator != ( Approx const& lhs, double rhs ) {
2121 return !operator==( rhs, lhs );
2122 }
2123
2124 Approx& epsilon( double newEpsilon ) {
2125 m_epsilon = newEpsilon;
2126 return *this;
2127 }
2128
2129 Approx& scale( double newScale ) {
2130 m_scale = newScale;
2131 return *this;
2132 }
2133
2134 std::string toString() const {
2135 std::ostringstream oss;
2136 oss << "Approx( " << Catch::toString( m_value ) << " )";
2137 return oss.str();
2138 }
2139
2140 private:
2141 double m_epsilon;
2142 double m_scale;
2143 double m_value;
2144 };
2145 }
2146
2147 template<>
2148 inline std::string toString<Detail::Approx>( Detail::Approx const& value ) {
2149 return value.toString();
2150 }
2151
2152 } // end namespace Catch
2153
2154 // #included from: internal/catch_matchers.hpp
2155 #define TWOBLUECUBES_CATCH_MATCHERS_HPP_INCLUDED
2156
2157 namespace Catch {
2158 namespace Matchers {
2159 namespace Impl {
2160
2161 template<typename ExpressionT>
2162 struct Matcher : SharedImpl<IShared>
2163 {
2164 typedef ExpressionT ExpressionType;
2165
2166 virtual ~Matcher() {}
2167 virtual Ptr<Matcher> clone() const = 0;
2168 virtual bool match( ExpressionT const& expr ) const = 0;
2169 virtual std::string toString() const = 0;
2170 };
2171
2172 template<typename DerivedT, typename ExpressionT>
2173 struct MatcherImpl : Matcher<ExpressionT> {
2174
2175 virtual Ptr<Matcher<ExpressionT> > clone() const {
2176 return Ptr<Matcher<ExpressionT> >( new DerivedT( static_cast<DerivedT const&>( *this ) ) );
2177 }
2178 };
2179
2180 namespace Generic {
2181
2182 template<typename ExpressionT>
2183 class AllOf : public MatcherImpl<AllOf<ExpressionT>, ExpressionT> {
2184 public:
2185
2186 AllOf() {}
2187 AllOf( AllOf const& other ) : m_matchers( other.m_matchers ) {}
2188
2189 AllOf& add( Matcher<ExpressionT> const& matcher ) {
2190 m_matchers.push_back( matcher.clone() );
2191 return *this;
2192 }
2193 virtual bool match( ExpressionT const& expr ) const
2194 {
2195 for( std::size_t i = 0; i < m_matchers.size(); ++i )
2196 if( !m_matchers[i]->match( expr ) )
2197 return false;
2198 return true;
2199 }
2200 virtual std::string toString() const {
2201 std::ostringstream oss;
2202 oss << "( ";
2203 for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
2204 if( i != 0 )
2205 oss << " and ";
2206 oss << m_matchers[i]->toString();
2207 }
2208 oss << " )";
2209 return oss.str();
2210 }
2211
2212 private:
2213 std::vector<Ptr<Matcher<ExpressionT> > > m_matchers;
2214 };
2215
2216 template<typename ExpressionT>
2217 class AnyOf : public MatcherImpl<AnyOf<ExpressionT>, ExpressionT> {
2218 public:
2219
2220 AnyOf() {}
2221 AnyOf( AnyOf const& other ) : m_matchers( other.m_matchers ) {}
2222
2223 AnyOf& add( Matcher<ExpressionT> const& matcher ) {
2224 m_matchers.push_back( matcher.clone() );
2225 return *this;
2226 }
2227 virtual bool match( ExpressionT const& expr ) const
2228 {
2229 for( std::size_t i = 0; i < m_matchers.size(); ++i )
2230 if( m_matchers[i]->match( expr ) )
2231 return true;
2232 return false;
2233 }
2234 virtual std::string toString() const {
2235 std::ostringstream oss;
2236 oss << "( ";
2237 for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
2238 if( i != 0 )
2239 oss << " or ";
2240 oss << m_matchers[i]->toString();
2241 }
2242 oss << " )";
2243 return oss.str();
2244 }
2245
2246 private:
2247 std::vector<Ptr<Matcher<ExpressionT> > > m_matchers;
2248 };
2249
2250 }
2251
2252 namespace StdString {
2253
2254 inline std::string makeString( std::string const& str ) { return str; }
2255 inline std::string makeString( const char* str ) { return str ? std::string( str ) : std::string(); }
2256
2257 struct Equals : MatcherImpl<Equals, std::string> {
2258 Equals( std::string const& str ) : m_str( str ){}
2259 Equals( Equals const& other ) : m_str( other.m_str ){}
2260
2261 virtual ~Equals();
2262
2263 virtual bool match( std::string const& expr ) const {
2264 return m_str == expr;
2265 }
2266 virtual std::string toString() const {
2267 return "equals: \"" + m_str + "\"";
2268 }
2269
2270 std::string m_str;
2271 };
2272
2273 struct Contains : MatcherImpl<Contains, std::string> {
2274 Contains( std::string const& substr ) : m_substr( substr ){}
2275 Contains( Contains const& other ) : m_substr( other.m_substr ){}
2276
2277 virtual ~Contains();
2278
2279 virtual bool match( std::string const& expr ) const {
2280 return expr.find( m_substr ) != std::string::npos;
2281 }
2282 virtual std::string toString() const {
2283 return "contains: \"" + m_substr + "\"";
2284 }
2285
2286 std::string m_substr;
2287 };
2288
2289 struct StartsWith : MatcherImpl<StartsWith, std::string> {
2290 StartsWith( std::string const& substr ) : m_substr( substr ){}
2291 StartsWith( StartsWith const& other ) : m_substr( other.m_substr ){}
2292
2293 virtual ~StartsWith();
2294
2295 virtual bool match( std::string const& expr ) const {
2296 return expr.find( m_substr ) == 0;
2297 }
2298 virtual std::string toString() const {
2299 return "starts with: \"" + m_substr + "\"";
2300 }
2301
2302 std::string m_substr;
2303 };
2304
2305 struct EndsWith : MatcherImpl<EndsWith, std::string> {
2306 EndsWith( std::string const& substr ) : m_substr( substr ){}
2307 EndsWith( EndsWith const& other ) : m_substr( other.m_substr ){}
2308
2309 virtual ~EndsWith();
2310
2311 virtual bool match( std::string const& expr ) const {
2312 return expr.find( m_substr ) == expr.size() - m_substr.size();
2313 }
2314 virtual std::string toString() const {
2315 return "ends with: \"" + m_substr + "\"";
2316 }
2317
2318 std::string m_substr;
2319 };
2320 } // namespace StdString
2321 } // namespace Impl
2322
2323 // The following functions create the actual matcher objects.
2324 // This allows the types to be inferred
2325 template<typename ExpressionT>
2326 inline Impl::Generic::AllOf<ExpressionT> AllOf( Impl::Matcher<ExpressionT> const& m1,
2327 Impl::Matcher<ExpressionT> const& m2 ) {
2328 return Impl::Generic::AllOf<ExpressionT>().add( m1 ).add( m2 );
2329 }
2330 template<typename ExpressionT>
2331 inline Impl::Generic::AllOf<ExpressionT> AllOf( Impl::Matcher<ExpressionT> const& m1,
2332 Impl::Matcher<ExpressionT> const& m2,
2333 Impl::Matcher<ExpressionT> const& m3 ) {
2334 return Impl::Generic::AllOf<ExpressionT>().add( m1 ).add( m2 ).add( m3 );
2335 }
2336 template<typename ExpressionT>
2337 inline Impl::Generic::AnyOf<ExpressionT> AnyOf( Impl::Matcher<ExpressionT> const& m1,
2338 Impl::Matcher<ExpressionT> const& m2 ) {
2339 return Impl::Generic::AnyOf<ExpressionT>().add( m1 ).add( m2 );
2340 }
2341 template<typename ExpressionT>
2342 inline Impl::Generic::AnyOf<ExpressionT> AnyOf( Impl::Matcher<ExpressionT> const& m1,
2343 Impl::Matcher<ExpressionT> const& m2,
2344 Impl::Matcher<ExpressionT> const& m3 ) {
2345 return Impl::Generic::AnyOf<ExpressionT>().add( m1 ).add( m2 ).add( m3 );
2346 }
2347
2348 inline Impl::StdString::Equals Equals( std::string const& str ) {
2349 return Impl::StdString::Equals( str );
2350 }
2351 inline Impl::StdString::Equals Equals( const char* str ) {
2352 return Impl::StdString::Equals( Impl::StdString::makeString( str ) );
2353 }
2354 inline Impl::StdString::Contains Contains( std::string const& substr ) {
2355 return Impl::StdString::Contains( substr );
2356 }
2357 inline Impl::StdString::Contains Contains( const char* substr ) {
2358 return Impl::StdString::Contains( Impl::StdString::makeString( substr ) );
2359 }
2360 inline Impl::StdString::StartsWith StartsWith( std::string const& substr ) {
2361 return Impl::StdString::StartsWith( substr );
2362 }
2363 inline Impl::StdString::StartsWith StartsWith( const char* substr ) {
2364 return Impl::StdString::StartsWith( Impl::StdString::makeString( substr ) );
2365 }
2366 inline Impl::StdString::EndsWith EndsWith( std::string const& substr ) {
2367 return Impl::StdString::EndsWith( substr );
2368 }
2369 inline Impl::StdString::EndsWith EndsWith( const char* substr ) {
2370 return Impl::StdString::EndsWith( Impl::StdString::makeString( substr ) );
2371 }
2372
2373 } // namespace Matchers
2374
2375 using namespace Matchers;
2376
2377 } // namespace Catch
2378
2379 // These files are included here so the single_include script doesn't put them
2380 // in the conditionally compiled sections
2381 // #included from: internal/catch_test_case_info.h
2382 #define TWOBLUECUBES_CATCH_TEST_CASE_INFO_H_INCLUDED
2383
2384 #include <string>
2385 #include <set>
2386
2387 #ifdef __clang__
2388 #pragma clang diagnostic push
2389 #pragma clang diagnostic ignored "-Wpadded"
2390 #endif
2391
2392 namespace Catch {
2393
2394 struct ITestCase;
2395
2396 struct TestCaseInfo {
2397 TestCaseInfo( std::string const& _name,
2398 std::string const& _className,
2399 std::string const& _description,
2400 std::set<std::string> const& _tags,
2401 bool _isHidden,
2402 SourceLineInfo const& _lineInfo );
2403
2404 TestCaseInfo( TestCaseInfo const& other );
2405
2406 std::string name;
2407 std::string className;
2408 std::string description;
2409 std::set<std::string> tags;
2410 std::string tagsAsString;
2411 SourceLineInfo lineInfo;
2412 bool isHidden;
2413 bool throws;
2414 };
2415
2416 class TestCase : protected TestCaseInfo {
2417 public:
2418
2419 TestCase( ITestCase* testCase, TestCaseInfo const& info );
2420 TestCase( TestCase const& other );
2421
2422 TestCase withName( std::string const& _newName ) const;
2423
2424 void invoke() const;
2425
2426 TestCaseInfo const& getTestCaseInfo() const;
2427
2428 bool isHidden() const;
2429 bool throws() const;
2430 bool hasTag( std::string const& tag ) const;
2431 bool matchesTags( std::string const& tagPattern ) const;
2432 std::set<std::string> const& getTags() const;
2433
2434 void swap( TestCase& other );
2435 bool operator == ( TestCase const& other ) const;
2436 bool operator < ( TestCase const& other ) const;
2437 TestCase& operator = ( TestCase const& other );
2438
2439 private:
2440 Ptr<ITestCase> test;
2441 };
2442
2443 TestCase makeTestCase( ITestCase* testCase,
2444 std::string const& className,
2445 std::string const& name,
2446 std::string const& description,
2447 SourceLineInfo const& lineInfo );
2448 }
2449
2450 #ifdef __clang__
2451 #pragma clang diagnostic pop
2452 #endif
2453
2454 // #included from: internal/catch_interfaces_runner.h
2455 #define TWOBLUECUBES_CATCH_INTERFACES_RUNNER_H_INCLUDED
2456
2457 namespace Catch {
2458 class TestCase;
2459
2460 struct IRunner {
2461 virtual ~IRunner();
2462 };
2463 }
2464
2465
2466 #ifdef __OBJC__
2467 // #included from: internal/catch_objc.hpp
2468 #define TWOBLUECUBES_CATCH_OBJC_HPP_INCLUDED
2469
2470 #import <objc/runtime.h>
2471
2472 #include <string>
2473
2474 // NB. Any general catch headers included here must be included
2475 // in catch.hpp first to make sure they are included by the single
2476 // header for non obj-usage
2477
2478 ///////////////////////////////////////////////////////////////////////////////
2479 // This protocol is really only here for (self) documenting purposes, since
2480 // all its methods are optional.
2481 @protocol OcFixture
2482
2483 @optional
2484
2485 -(void) setUp;
2486 -(void) tearDown;
2487
2488 @end
2489
2490 namespace Catch {
2491
2492 class OcMethod : public SharedImpl<ITestCase> {
2493
2494 public:
2495 OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
2496
2497 virtual void invoke() const {
2498 id obj = [[m_cls alloc] init];
2499
2500 performOptionalSelector( obj, @selector(setUp) );
2501 performOptionalSelector( obj, m_sel );
2502 performOptionalSelector( obj, @selector(tearDown) );
2503
2504 arcSafeRelease( obj );
2505 }
2506 private:
2507 virtual ~OcMethod() {}
2508
2509 Class m_cls;
2510 SEL m_sel;
2511 };
2512
2513 namespace Detail{
2514
2515 inline std::string getAnnotation( Class cls,
2516 std::string const& annotationName,
2517 std::string const& testCaseName ) {
2518 NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
2519 SEL sel = NSSelectorFromString( selStr );
2520 arcSafeRelease( selStr );
2521 id value = performOptionalSelector( cls, sel );
2522 if( value )
2523 return [(NSString*)value UTF8String];
2524 return "";
2525 }
2526 }
2527
2528 inline size_t registerTestMethods() {
2529 size_t noTestMethods = 0;
2530 int noClasses = objc_getClassList( NULL, 0 );
2531
2532 Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
2533 objc_getClassList( classes, noClasses );
2534
2535 for( int c = 0; c < noClasses; c++ ) {
2536 Class cls = classes[c];
2537 {
2538 u_int count;
2539 Method* methods = class_copyMethodList( cls, &count );
2540 for( u_int m = 0; m < count ; m++ ) {
2541 SEL selector = method_getName(methods[m]);
2542 std::string methodName = sel_getName(selector);
2543 if( startsWith( methodName, "Catch_TestCase_" ) ) {
2544 std::string testCaseName = methodName.substr( 15 );
2545 std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
2546 std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
2547 const char* className = class_getName( cls );
2548
2549 getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo() ) );
2550 noTestMethods++;
2551 }
2552 }
2553 free(methods);
2554 }
2555 }
2556 return noTestMethods;
2557 }
2558
2559 namespace Matchers {
2560 namespace Impl {
2561 namespace NSStringMatchers {
2562
2563 template<typename MatcherT>
2564 struct StringHolder : MatcherImpl<MatcherT, NSString*>{
2565 StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
2566 StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
2567 StringHolder() {
2568 arcSafeRelease( m_substr );
2569 }
2570
2571 NSString* m_substr;
2572 };
2573
2574 struct Equals : StringHolder<Equals> {
2575 Equals( NSString* substr ) : StringHolder( substr ){}
2576
2577 virtual bool match( ExpressionType const& str ) const {
2578 return (str != nil || m_substr == nil ) &&
2579 [str isEqualToString:m_substr];
2580 }
2581
2582 virtual std::string toString() const {
2583 return "equals string: \"" + Catch::toString( m_substr ) + "\"";
2584 }
2585 };
2586
2587 struct Contains : StringHolder<Contains> {
2588 Contains( NSString* substr ) : StringHolder( substr ){}
2589
2590 virtual bool match( ExpressionType const& str ) const {
2591 return (str != nil || m_substr == nil ) &&
2592 [str rangeOfString:m_substr].location != NSNotFound;
2593 }
2594
2595 virtual std::string toString() const {
2596 return "contains string: \"" + Catch::toString( m_substr ) + "\"";
2597 }
2598 };
2599
2600 struct StartsWith : StringHolder<StartsWith> {
2601 StartsWith( NSString* substr ) : StringHolder( substr ){}
2602
2603 virtual bool match( ExpressionType const& str ) const {
2604 return (str != nil || m_substr == nil ) &&
2605 [str rangeOfString:m_substr].location == 0;
2606 }
2607
2608 virtual std::string toString() const {
2609 return "starts with: \"" + Catch::toString( m_substr ) + "\"";
2610 }
2611 };
2612 struct EndsWith : StringHolder<EndsWith> {
2613 EndsWith( NSString* substr ) : StringHolder( substr ){}
2614
2615 virtual bool match( ExpressionType const& str ) const {
2616 return (str != nil || m_substr == nil ) &&
2617 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
2618 }
2619
2620 virtual std::string toString() const {
2621 return "ends with: \"" + Catch::toString( m_substr ) + "\"";
2622 }
2623 };
2624
2625 } // namespace NSStringMatchers
2626 } // namespace Impl
2627
2628 inline Impl::NSStringMatchers::Equals
2629 Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
2630
2631 inline Impl::NSStringMatchers::Contains
2632 Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
2633
2634 inline Impl::NSStringMatchers::StartsWith
2635 StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
2636
2637 inline Impl::NSStringMatchers::EndsWith
2638 EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
2639
2640 } // namespace Matchers
2641
2642 using namespace Matchers;
2643
2644 } // namespace Catch
2645
2646 ///////////////////////////////////////////////////////////////////////////////
2647 #define OC_TEST_CASE( name, desc )\
2648 +(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Name_test ) \
2649 {\
2650 return @ name; \
2651 }\
2652 +(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Description_test ) \
2653 { \
2654 return @ desc; \
2655 } \
2656 -(void) INTERNAL_CATCH_UNIQUE_NAME( Catch_TestCase_test )
2657
2658 #endif
2659
2660 #ifdef CATCH_CONFIG_RUNNER
2661 // #included from: internal/catch_impl.hpp
2662 #define TWOBLUECUBES_CATCH_IMPL_HPP_INCLUDED
2663
2664 // Collect all the implementation files together here
2665 // These are the equivalent of what would usually be cpp files
2666
2667 #ifdef __clang__
2668 #pragma clang diagnostic push
2669 #pragma clang diagnostic ignored "-Wweak-vtables"
2670 #endif
2671
2672 // #included from: catch_runner.hpp
2673 #define TWOBLUECUBES_CATCH_RUNNER_HPP_INCLUDED
2674
2675 // #included from: internal/catch_commandline.hpp
2676 #define TWOBLUECUBES_CATCH_COMMANDLINE_HPP_INCLUDED
2677
2678 // #included from: catch_config.hpp
2679 #define TWOBLUECUBES_CATCH_CONFIG_HPP_INCLUDED
2680
2681 // #included from: catch_test_spec.h
2682 #define TWOBLUECUBES_CATCH_TEST_SPEC_H_INCLUDED
2683
2684 // #included from: catch_tags.h
2685 #define TWOBLUECUBES_CATCH_TAGS_H_INCLUDED
2686
2687 #include <string>
2688 #include <set>
2689 #include <map>
2690 #include <vector>
2691
2692 #ifdef __clang__
2693 #pragma clang diagnostic ignored "-Wpadded"
2694 #endif
2695
2696 namespace Catch {
2697 class TagParser {
2698 public:
2699 virtual ~TagParser();
2700
2701 void parse( std::string const& str );
2702
2703 protected:
2704 virtual void acceptTag( std::string const& tag ) = 0;
2705 virtual void acceptChar( char c ) = 0;
2706 virtual void endParse() {}
2707
2708 private:
2709 };
2710
2711 class TagExtracter : public TagParser {
2712 public:
2713
2714 TagExtracter( std::set<std::string>& tags );
2715 virtual ~TagExtracter();
2716
2717 void parse( std::string& description );
2718
2719 private:
2720 virtual void acceptTag( std::string const& tag );
2721 virtual void acceptChar( char c );
2722
2723 TagExtracter& operator=(TagExtracter const&);
2724
2725 std::set<std::string>& m_tags;
2726 std::string m_remainder;
2727 };
2728
2729 class Tag {
2730 public:
2731 Tag();
2732 Tag( std::string const& name, bool isNegated );
2733 std::string getName() const;
2734 bool isNegated() const;
2735 bool operator ! () const;
2736
2737 private:
2738 std::string m_name;
2739 bool m_isNegated;
2740 };
2741
2742 class TagSet {
2743 typedef std::map<std::string, Tag> TagMap;
2744 public:
2745 void add( Tag const& tag );
2746 bool empty() const;
2747 bool matches( std::set<std::string> const& tags ) const;
2748
2749 private:
2750 TagMap m_tags;
2751 };
2752
2753 class TagExpression {
2754 public:
2755 bool matches( std::set<std::string> const& tags ) const;
2756
2757 private:
2758 friend class TagExpressionParser;
2759
2760 std::vector<TagSet> m_tagSets;
2761 };
2762
2763 class TagExpressionParser : public TagParser {
2764 public:
2765 TagExpressionParser( TagExpression& exp );
2766 ~TagExpressionParser();
2767
2768 private:
2769 virtual void acceptTag( std::string const& tag );
2770 virtual void acceptChar( char c );
2771 virtual void endParse();
2772
2773 TagExpressionParser& operator=(TagExpressionParser const&);
2774
2775 bool m_isNegated;
2776 TagSet m_currentTagSet;
2777 TagExpression& m_exp;
2778 };
2779
2780 } // end namespace Catch
2781
2782 #include <string>
2783 #include <vector>
2784
2785 namespace Catch {
2786
2787 class TestCase;
2788
2789 struct IfFilterMatches{ enum DoWhat {
2790 AutoDetectBehaviour,
2791 IncludeTests,
2792 ExcludeTests
2793 }; };
2794
2795 class TestCaseFilter {
2796 enum WildcardPosition {
2797 NoWildcard = 0,
2798 WildcardAtStart = 1,
2799 WildcardAtEnd = 2,
2800 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
2801 };
2802
2803 public:
2804 TestCaseFilter( std::string const& testSpec, IfFilterMatches::DoWhat matchBehaviour = IfFilterMatches::AutoDetectBehaviour );
2805
2806 IfFilterMatches::DoWhat getFilterType() const;
2807 bool shouldInclude( TestCase const& testCase ) const;
2808
2809 private:
2810 bool isMatch( TestCase const& testCase ) const;
2811
2812 std::string m_stringToMatch;
2813 IfFilterMatches::DoWhat m_filterType;
2814 WildcardPosition m_wildcardPosition;
2815 };
2816
2817 class TestCaseFilters {
2818 public:
2819 TestCaseFilters( std::string const& name );
2820 std::string getName() const;
2821 void addFilter( TestCaseFilter const& filter );
2822 void addTags( std::string const& tagPattern );
2823 bool shouldInclude( TestCase const& testCase ) const;
2824
2825 private:
2826 std::vector<TagExpression> m_tagExpressions;
2827 std::vector<TestCaseFilter> m_inclusionFilters;
2828 std::vector<TestCaseFilter> m_exclusionFilters;
2829 std::string m_name;
2830 };
2831
2832 }
2833
2834 // #included from: catch_stream.h
2835 #define TWOBLUECUBES_CATCH_STREAM_H_INCLUDED
2836
2837 #include <streambuf>
2838
2839 #ifdef __clang__
2840 #pragma clang diagnostic ignored "-Wpadded"
2841 #endif
2842
2843 namespace Catch {
2844
2845 class Stream {
2846 public:
2847 Stream();
2848 Stream( std::streambuf* _streamBuf, bool _isOwned );
2849 void release();
2850
2851 std::streambuf* streamBuf;
2852
2853 private:
2854 bool isOwned;
2855 };
2856 }
2857
2858 #include <memory>
2859 #include <vector>
2860 #include <string>
2861 #include <iostream>
2862
2863 #ifndef CATCH_CONFIG_CONSOLE_WIDTH
2864 #define CATCH_CONFIG_CONSOLE_WIDTH 80
2865 #endif
2866
2867 namespace Catch {
2868
2869 struct ConfigData {
2870
2871 ConfigData()
2872 : listTests( false ),
2873 listTags( false ),
2874 listReporters( false ),
2875 listTestNamesOnly( false ),
2876 showSuccessfulTests( false ),
2877 shouldDebugBreak( false ),
2878 noThrow( false ),
2879 showHelp( false ),
2880 showInvisibles( false ),
2881 abortAfter( -1 ),
2882 verbosity( Verbosity::Normal ),
2883 warnings( WarnAbout::Nothing ),
2884 showDurations( ShowDurations::DefaultForReporter )
2885 {}
2886
2887 bool listTests;
2888 bool listTags;
2889 bool listReporters;
2890 bool listTestNamesOnly;
2891
2892 bool showSuccessfulTests;
2893 bool shouldDebugBreak;
2894 bool noThrow;
2895 bool showHelp;
2896 bool showInvisibles;
2897
2898 int abortAfter;
2899
2900 Verbosity::Level verbosity;
2901 WarnAbout::What warnings;
2902 ShowDurations::OrNot showDurations;
2903
2904 std::string reporterName;
2905 std::string outputFilename;
2906 std::string name;
2907 std::string processName;
2908
2909 std::vector<std::string> testsOrTags;
2910 };
2911
2912 class Config : public SharedImpl<IConfig> {
2913 private:
2914 Config( Config const& other );
2915 Config& operator = ( Config const& other );
2916 virtual void dummy();
2917 public:
2918
2919 Config()
2920 : m_os( std::cout.rdbuf() )
2921 {}
2922
2923 Config( ConfigData const& data )
2924 : m_data( data ),
2925 m_os( std::cout.rdbuf() )
2926 {
2927 if( !data.testsOrTags.empty() ) {
2928 std::string groupName;
2929 for( std::size_t i = 0; i < data.testsOrTags.size(); ++i ) {
2930 if( i != 0 )
2931 groupName += " ";
2932 groupName += data.testsOrTags[i];
2933 }
2934 TestCaseFilters filters( groupName );
2935 for( std::size_t i = 0; i < data.testsOrTags.size(); ++i ) {
2936 std::string filter = data.testsOrTags[i];
2937 if( startsWith( filter, "[" ) || startsWith( filter, "~[" ) )
2938 filters.addTags( filter );
2939 else
2940 filters.addFilter( TestCaseFilter( filter ) );
2941 }
2942 m_filterSets.push_back( filters );
2943 }
2944 }
2945
2946 virtual ~Config() {
2947 m_os.rdbuf( std::cout.rdbuf() );
2948 m_stream.release();
2949 }
2950
2951 void setFilename( std::string const& filename ) {
2952 m_data.outputFilename = filename;
2953 }
2954
2955 std::string const& getFilename() const {
2956 return m_data.outputFilename ;
2957 }
2958
2959 bool listTests() const { return m_data.listTests; }
2960 bool listTestNamesOnly() const { return m_data.listTestNamesOnly; }
2961 bool listTags() const { return m_data.listTags; }
2962 bool listReporters() const { return m_data.listReporters; }
2963
2964 std::string getProcessName() const {
2965 return m_data.processName;
2966 }
2967
2968 bool shouldDebugBreak() const {
2969 return m_data.shouldDebugBreak;
2970 }
2971
2972 void setStreamBuf( std::streambuf* buf ) {
2973 m_os.rdbuf( buf ? buf : std::cout.rdbuf() );
2974 }
2975
2976 void useStream( std::string const& streamName ) {
2977 Stream stream = createStream( streamName );
2978 setStreamBuf( stream.streamBuf );
2979 m_stream.release();
2980 m_stream = stream;
2981 }
2982
2983 std::string getReporterName() const { return m_data.reporterName; }
2984
2985 void addTestSpec( std::string const& testSpec ) {
2986 TestCaseFilters filters( testSpec );
2987 filters.addFilter( TestCaseFilter( testSpec ) );
2988 m_filterSets.push_back( filters );
2989 }
2990
2991 int abortAfter() const {
2992 return m_data.abortAfter;
2993 }
2994
2995 std::vector<TestCaseFilters> const& filters() const {
2996 return m_filterSets;
2997 }
2998
2999 bool showHelp() const { return m_data.showHelp; }
3000 bool showInvisibles() const { return m_data.showInvisibles; }
3001
3002 // IConfig interface
3003 virtual bool allowThrows() const { return !m_data.noThrow; }
3004 virtual std::ostream& stream() const { return m_os; }
3005 virtual std::string name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
3006 virtual bool includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
3007 virtual bool warnAboutMissingAssertions() const { return m_data.warnings & WarnAbout::NoAssertions; }
3008 virtual ShowDurations::OrNot showDurations() const { return m_data.showDurations; }
3009
3010 private:
3011 ConfigData m_data;
3012
3013 Stream m_stream;
3014 mutable std::ostream m_os;
3015 std::vector<TestCaseFilters> m_filterSets;
3016 };
3017
3018 } // end namespace Catch
3019
3020 // #included from: catch_clara.h
3021 #define TWOBLUECUBES_CATCH_CLARA_H_INCLUDED
3022
3023 // Use Catch's value for console width (store Clara's off to the side, if present)
3024 #ifdef CLARA_CONFIG_CONSOLE_WIDTH
3025 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CLARA_CONFIG_CONSOLE_WIDTH
3026 #undef CLARA_CONFIG_CONSOLE_WIDTH
3027 #endif
3028 #define CLARA_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH
3029
3030 // Declare Clara inside the Catch namespace
3031 #define STITCH_CLARA_OPEN_NAMESPACE namespace Catch {
3032 // #included from: ../external/clara.h
3033
3034 // Only use header guard if we are not using an outer namespace
3035 #if !defined(TWOBLUECUBES_CLARA_H_INCLUDED) || defined(STITCH_CLARA_OPEN_NAMESPACE)
3036
3037 #ifndef STITCH_CLARA_OPEN_NAMESPACE
3038 #define TWOBLUECUBES_CLARA_H_INCLUDED
3039 #define STITCH_CLARA_OPEN_NAMESPACE
3040 #define STITCH_CLARA_CLOSE_NAMESPACE
3041 #else
3042 #define STITCH_CLARA_CLOSE_NAMESPACE }
3043 #endif
3044
3045 #define STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE STITCH_CLARA_OPEN_NAMESPACE
3046
3047 // ----------- #included from tbc_text_format.h -----------
3048
3049 // Only use header guard if we are not using an outer namespace
3050 #if !defined(TBC_TEXT_FORMAT_H_INCLUDED) || defined(STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE)
3051 #ifndef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE
3052 #define TBC_TEXT_FORMAT_H_INCLUDED
3053 #endif
3054
3055 #include <string>
3056 #include <vector>
3057 #include <sstream>
3058
3059 // Use optional outer namespace
3060 #ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE
3061 namespace STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE {
3062 #endif
3063
3064 namespace Tbc {
3065
3066 #ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH
3067 const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH;
3068 #else
3069 const unsigned int consoleWidth = 80;
3070 #endif
3071
3072 struct TextAttributes {
3073 TextAttributes()
3074 : initialIndent( std::string::npos ),
3075 indent( 0 ),
3076 width( consoleWidth-1 ),
3077 tabChar( '\t' )
3078 {}
3079
3080 TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; }
3081 TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; }
3082 TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; }
3083 TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; }
3084
3085 std::size_t initialIndent; // indent of first line, or npos
3086 std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos
3087 std::size_t width; // maximum width of text, including indent. Longer text will wrap
3088 char tabChar; // If this char is seen the indent is changed to current pos
3089 };
3090
3091 class Text {
3092 public:
3093 Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() )
3094 : attr( _attr )
3095 {
3096 std::string wrappableChars = " [({.,/|\\-";
3097 std::size_t indent = _attr.initialIndent != std::string::npos
3098 ? _attr.initialIndent
3099 : _attr.indent;
3100 std::string remainder = _str;
3101
3102 while( !remainder.empty() ) {
3103 if( lines.size() >= 1000 ) {
3104 lines.push_back( "... message truncated due to excessive size" );
3105 return;
3106 }
3107 std::size_t tabPos = std::string::npos;
3108 std::size_t width = (std::min)( remainder.size(), _attr.width - indent );
3109 std::size_t pos = remainder.find_first_of( '\n' );
3110 if( pos <= width ) {
3111 width = pos;
3112 }
3113 pos = remainder.find_last_of( _attr.tabChar, width );
3114 if( pos != std::string::npos ) {
3115 tabPos = pos;
3116 if( remainder[width] == '\n' )
3117 width--;
3118 remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 );
3119 }
3120
3121 if( width == remainder.size() ) {
3122 spliceLine( indent, remainder, width );
3123 }
3124 else if( remainder[width] == '\n' ) {
3125 spliceLine( indent, remainder, width );
3126 if( width <= 1 || remainder.size() != 1 )
3127 remainder = remainder.substr( 1 );
3128 indent = _attr.indent;
3129 }
3130 else {
3131 pos = remainder.find_last_of( wrappableChars, width );
3132 if( pos != std::string::npos && pos > 0 ) {
3133 spliceLine( indent, remainder, pos );
3134 if( remainder[0] == ' ' )
3135 remainder = remainder.substr( 1 );
3136 }
3137 else {
3138 spliceLine( indent, remainder, width-1 );
3139 lines.back() += "-";
3140 }
3141 if( lines.size() == 1 )
3142 indent = _attr.indent;
3143 if( tabPos != std::string::npos )
3144 indent += tabPos;
3145 }
3146 }
3147 }
3148
3149 void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) {
3150 lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) );
3151 _remainder = _remainder.substr( _pos );
3152 }
3153
3154 typedef std::vector<std::string>::const_iterator const_iterator;
3155
3156 const_iterator begin() const { return lines.begin(); }
3157 const_iterator end() const { return lines.end(); }
3158 std::string const& last() const { return lines.back(); }
3159 std::size_t size() const { return lines.size(); }
3160 std::string const& operator[]( std::size_t _index ) const { return lines[_index]; }
3161 std::string toString() const {
3162 std::ostringstream oss;
3163 oss << *this;
3164 return oss.str();
3165 }
3166
3167 inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) {
3168 for( Text::const_iterator it = _text.begin(), itEnd = _text.end();
3169 it != itEnd; ++it ) {
3170 if( it != _text.begin() )
3171 _stream << "\n";
3172 _stream << *it;
3173 }
3174 return _stream;
3175 }
3176
3177 private:
3178 std::string str;
3179 TextAttributes attr;
3180 std::vector<std::string> lines;
3181 };
3182
3183 } // end namespace Tbc
3184
3185 #ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE
3186 } // end outer namespace
3187 #endif
3188
3189 #endif // TBC_TEXT_FORMAT_H_INCLUDED
3190
3191 // ----------- end of #include from tbc_text_format.h -----------
3192 // ........... back in /Users/philnash/Dev/OSS/Clara/srcs/clara.h
3193
3194 #undef STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE
3195
3196 #include <map>
3197 #include <algorithm>
3198 #include <stdexcept>
3199 #include <memory>
3200
3201 // Use optional outer namespace
3202 #ifdef STITCH_CLARA_OPEN_NAMESPACE
3203 STITCH_CLARA_OPEN_NAMESPACE
3204 #endif
3205
3206 namespace Clara {
3207
3208 struct UnpositionalTag {};
3209
3210 extern UnpositionalTag _;
3211
3212 #ifdef CLARA_CONFIG_MAIN
3213 UnpositionalTag _;
3214 #endif
3215
3216 namespace Detail {
3217
3218 #ifdef CLARA_CONSOLE_WIDTH
3219 const unsigned int consoleWidth = CLARA_CONFIG_CONSOLE_WIDTH;
3220 #else
3221 const unsigned int consoleWidth = 80;
3222 #endif
3223
3224 using namespace Tbc;
3225
3226 inline bool startsWith( std::string const& str, std::string const& prefix ) {
3227 return str.size() >= prefix.size() && str.substr( 0, prefix.size() ) == prefix;
3228 }
3229
3230 template<typename T> struct RemoveConstRef{ typedef T type; };
3231 template<typename T> struct RemoveConstRef<T&>{ typedef T type; };
3232 template<typename T> struct RemoveConstRef<T const&>{ typedef T type; };
3233 template<typename T> struct RemoveConstRef<T const>{ typedef T type; };
3234
3235 template<typename T> struct IsBool { static const bool value = false; };
3236 template<> struct IsBool<bool> { static const bool value = true; };
3237
3238 template<typename T>
3239 void convertInto( std::string const& _source, T& _dest ) {
3240 std::stringstream ss;
3241 ss << _source;
3242 ss >> _dest;
3243 if( ss.fail() )
3244 throw std::runtime_error( "Unable to convert " + _source + " to destination type" );
3245 }
3246 inline void convertInto( std::string const& _source, std::string& _dest ) {
3247 _dest = _source;
3248 }
3249 inline void convertInto( std::string const& _source, bool& _dest ) {
3250 std::string sourceLC = _source;
3251 std::transform( sourceLC.begin(), sourceLC.end(), sourceLC.begin(), ::tolower );
3252 if( sourceLC == "y" || sourceLC == "1" || sourceLC == "true" || sourceLC == "yes" || sourceLC == "on" )
3253 _dest = true;
3254 else if( sourceLC == "n" || sourceLC == "0" || sourceLC == "false" || sourceLC == "no" || sourceLC == "off" )
3255 _dest = false;
3256 else
3257 throw std::runtime_error( "Expected a boolean value but did not recognise:\n '" + _source + "'" );
3258 }
3259 inline void convertInto( bool _source, bool& _dest ) {
3260 _dest = _source;
3261 }
3262 template<typename T>
3263 inline void convertInto( bool, T& ) {
3264 throw std::runtime_error( "Invalid conversion" );
3265 }
3266
3267 template<typename ConfigT>
3268 struct IArgFunction {
3269 virtual ~IArgFunction() {}
3270 # ifdef CATCH_CPP11_OR_GREATER
3271 IArgFunction() = default;
3272 IArgFunction( IArgFunction const& ) = default;
3273 # endif
3274 virtual void set( ConfigT& config, std::string const& value ) const = 0;
3275 virtual void setFlag( ConfigT& config ) const = 0;
3276 virtual bool takesArg() const = 0;
3277 virtual IArgFunction* clone() const = 0;
3278 };
3279
3280 template<typename ConfigT>
3281 class BoundArgFunction {
3282 public:
3283 BoundArgFunction() : functionObj( NULL ) {}
3284 BoundArgFunction( IArgFunction<ConfigT>* _functionObj ) : functionObj( _functionObj ) {}
3285 BoundArgFunction( BoundArgFunction const& other ) : functionObj( other.functionObj ? other.functionObj->clone() : NULL ) {}
3286 BoundArgFunction& operator = ( BoundArgFunction const& other ) {
3287 IArgFunction<ConfigT>* newFunctionObj = other.functionObj ? other.functionObj->clone() : NULL;
3288 delete functionObj;
3289 functionObj = newFunctionObj;
3290 return *this;
3291 }
3292 ~BoundArgFunction() { delete functionObj; }
3293
3294 void set( ConfigT& config, std::string const& value ) const {
3295 functionObj->set( config, value );
3296 }
3297 void setFlag( ConfigT& config ) const {
3298 functionObj->setFlag( config );
3299 }
3300 bool takesArg() const { return functionObj->takesArg(); }
3301
3302 bool isSet() const {
3303 return functionObj != NULL;
3304 }
3305 private:
3306 IArgFunction<ConfigT>* functionObj;
3307 };
3308
3309 template<typename C>
3310 struct NullBinder : IArgFunction<C>{
3311 virtual void set( C&, std::string const& ) const {}
3312 virtual void setFlag( C& ) const {}
3313 virtual bool takesArg() const { return true; }
3314 virtual IArgFunction<C>* clone() const { return new NullBinder( *this ); }
3315 };
3316
3317 template<typename C, typename M>
3318 struct BoundDataMember : IArgFunction<C>{
3319 BoundDataMember( M C::* _member ) : member( _member ) {}
3320 virtual void set( C& p, std::string const& stringValue ) const {
3321 convertInto( stringValue, p.*member );
3322 }
3323 virtual void setFlag( C& p ) const {
3324 convertInto( true, p.*member );
3325 }
3326 virtual bool takesArg() const { return !IsBool<M>::value; }
3327 virtual IArgFunction<C>* clone() const { return new BoundDataMember( *this ); }
3328 M C::* member;
3329 };
3330 template<typename C, typename M>
3331 struct BoundUnaryMethod : IArgFunction<C>{
3332 BoundUnaryMethod( void (C::*_member)( M ) ) : member( _member ) {}
3333 virtual void set( C& p, std::string const& stringValue ) const {
3334 typename RemoveConstRef<M>::type value;
3335 convertInto( stringValue, value );
3336 (p.*member)( value );
3337 }
3338 virtual void setFlag( C& p ) const {
3339 typename RemoveConstRef<M>::type value;
3340 convertInto( true, value );
3341 (p.*member)( value );
3342 }
3343 virtual bool takesArg() const { return !IsBool<M>::value; }
3344 virtual IArgFunction<C>* clone() const { return new BoundUnaryMethod( *this ); }
3345 void (C::*member)( M );
3346 };
3347 template<typename C>
3348 struct BoundNullaryMethod : IArgFunction<C>{
3349 BoundNullaryMethod( void (C::*_member)() ) : member( _member ) {}
3350 virtual void set( C& p, std::string const& stringValue ) const {
3351 bool value;
3352 convertInto( stringValue, value );
3353 if( value )
3354 (p.*member)();
3355 }
3356 virtual void setFlag( C& p ) const {
3357 (p.*member)();
3358 }
3359 virtual bool takesArg() const { return false; }
3360 virtual IArgFunction<C>* clone() const { return new BoundNullaryMethod( *this ); }
3361 void (C::*member)();
3362 };
3363
3364 template<typename C>
3365 struct BoundUnaryFunction : IArgFunction<C>{
3366 BoundUnaryFunction( void (*_function)( C& ) ) : function( _function ) {}
3367 virtual void set( C& obj, std::string const& stringValue ) const {
3368 bool value;
3369 convertInto( stringValue, value );
3370 if( value )
3371 function( obj );
3372 }
3373 virtual void setFlag( C& p ) const {
3374 function( p );
3375 }
3376 virtual bool takesArg() const { return false; }
3377 virtual IArgFunction<C>* clone() const { return new BoundUnaryFunction( *this ); }
3378 void (*function)( C& );
3379 };
3380
3381 template<typename C, typename T>
3382 struct BoundBinaryFunction : IArgFunction<C>{
3383 BoundBinaryFunction( void (*_function)( C&, T ) ) : function( _function ) {}
3384 virtual void set( C& obj, std::string const& stringValue ) const {
3385 typename RemoveConstRef<T>::type value;
3386 convertInto( stringValue, value );
3387 function( obj, value );
3388 }
3389 virtual void setFlag( C& obj ) const {
3390 typename RemoveConstRef<T>::type value;
3391 convertInto( true, value );
3392 function( obj, value );
3393 }
3394 virtual bool takesArg() const { return !IsBool<T>::value; }
3395 virtual IArgFunction<C>* clone() const { return new BoundBinaryFunction( *this ); }
3396 void (*function)( C&, T );
3397 };
3398
3399 } // namespace Detail
3400
3401 struct Parser {
3402 Parser() : separators( " \t=:" ) {}
3403
3404 struct Token {
3405 enum Type { Positional, ShortOpt, LongOpt };
3406 Token( Type _type, std::string const& _data ) : type( _type ), data( _data ) {}
3407 Type type;
3408 std::string data;
3409 };
3410
3411 void parseIntoTokens( int argc, char const * const * argv, std::vector<Parser::Token>& tokens ) const {
3412 const std::string doubleDash = "--";
3413 for( int i = 1; i < argc && argv[i] != doubleDash; ++i )
3414 parseIntoTokens( argv[i] , tokens);
3415 }
3416 void parseIntoTokens( std::string arg, std::vector<Parser::Token>& tokens ) const {
3417 while( !arg.empty() ) {
3418 Parser::Token token( Parser::Token::Positional, arg );
3419 arg = "";
3420 if( token.data[0] == '-' ) {
3421 if( token.data.size() > 1 && token.data[1] == '-' ) {
3422 token = Parser::Token( Parser::Token::LongOpt, token.data.substr( 2 ) );
3423 }
3424 else {
3425 token = Parser::Token( Parser::Token::ShortOpt, token.data.substr( 1 ) );
3426 if( token.data.size() > 1 && separators.find( token.data[1] ) == std::string::npos ) {
3427 arg = "-" + token.data.substr( 1 );
3428 token.data = token.data.substr( 0, 1 );
3429 }
3430 }
3431 }
3432 if( token.type != Parser::Token::Positional ) {
3433 std::size_t pos = token.data.find_first_of( separators );
3434 if( pos != std::string::npos ) {
3435 arg = token.data.substr( pos+1 );
3436 token.data = token.data.substr( 0, pos );
3437 }
3438 }
3439 tokens.push_back( token );
3440 }
3441 }
3442 std::string separators;
3443 };
3444
3445 template<typename ConfigT>
3446 struct CommonArgProperties {
3447 CommonArgProperties() {}
3448 CommonArgProperties( Detail::BoundArgFunction<ConfigT> const& _boundField ) : boundField( _boundField ) {}
3449
3450 Detail::BoundArgFunction<ConfigT> boundField;
3451 std::string description;
3452 std::string detail;
3453 std::string placeholder; // Only value if boundField takes an arg
3454
3455 bool takesArg() const {
3456 return !placeholder.empty();
3457 }
3458 void validate() const {
3459 if( !boundField.isSet() )
3460 throw std::logic_error( "option not bound" );
3461 }
3462 };
3463 struct OptionArgProperties {
3464 std::vector<std::string> shortNames;
3465 std::string longName;
3466
3467 bool hasShortName( std::string const& shortName ) const {
3468 return std::find( shortNames.begin(), shortNames.end(), shortName ) != shortNames.end();
3469 }
3470 bool hasLongName( std::string const& _longName ) const {
3471 return _longName == longName;
3472 }
3473 };
3474 struct PositionalArgProperties {
3475 PositionalArgProperties() : position( -1 ) {}
3476 int position; // -1 means non-positional (floating)
3477
3478 bool isFixedPositional() const {
3479 return position != -1;
3480 }
3481 };
3482
3483 template<typename ConfigT>
3484 class CommandLine {
3485
3486 struct Arg : CommonArgProperties<ConfigT>, OptionArgProperties, PositionalArgProperties {
3487 Arg() {}
3488 Arg( Detail::BoundArgFunction<ConfigT> const& _boundField ) : CommonArgProperties<ConfigT>( _boundField ) {}
3489
3490 using CommonArgProperties<ConfigT>::placeholder; // !TBD
3491
3492 std::string dbgName() const {
3493 if( !longName.empty() )
3494 return "--" + longName;
3495 if( !shortNames.empty() )
3496 return "-" + shortNames[0];
3497 return "positional args";
3498 }
3499 std::string commands() const {
3500 std::ostringstream oss;
3501 bool first = true;
3502 std::vector<std::string>::const_iterator it = shortNames.begin(), itEnd = shortNames.end();
3503 for(; it != itEnd; ++it ) {
3504 if( first )
3505 first = false;
3506 else
3507 oss << ", ";
3508 oss << "-" << *it;
3509 }
3510 if( !longName.empty() ) {
3511 if( !first )
3512 oss << ", ";
3513 oss << "--" << longName;
3514 }
3515 if( !placeholder.empty() )
3516 oss << " <" << placeholder << ">";
3517 return oss.str();
3518 }
3519 };
3520
3521 // NOTE: std::auto_ptr is deprecated in c++11/c++0x
3522 #if defined(__cplusplus) && __cplusplus > 199711L
3523 typedef std::unique_ptr<Arg> ArgAutoPtr;
3524 #else
3525 typedef std::auto_ptr<Arg> ArgAutoPtr;
3526 #endif
3527
3528 friend void addOptName( Arg& arg, std::string const& optName )
3529 {
3530 if( optName.empty() )
3531 return;
3532 if( Detail::startsWith( optName, "--" ) ) {
3533 if( !arg.longName.empty() )
3534 throw std::logic_error( "Only one long opt may be specified. '"
3535 + arg.longName
3536 + "' already specified, now attempting to add '"
3537 + optName + "'" );
3538 arg.longName = optName.substr( 2 );
3539 }
3540 else if( Detail::startsWith( optName, "-" ) )
3541 arg.shortNames.push_back( optName.substr( 1 ) );
3542 else
3543 throw std::logic_error( "option must begin with - or --. Option was: '" + optName + "'" );
3544 }
3545 friend void setPositionalArg( Arg& arg, int position )
3546 {
3547 arg.position = position;
3548 }
3549
3550 class ArgBuilder {
3551 public:
3552 ArgBuilder( Arg* arg ) : m_arg( arg ) {}
3553
3554 // Bind a non-boolean data member (requires placeholder string)
3555 template<typename C, typename M>
3556 void bind( M C::* field, std::string const& placeholder ) {
3557 m_arg->boundField = new Detail::BoundDataMember<C,M>( field );
3558 m_arg->placeholder = placeholder;
3559 }
3560 // Bind a boolean data member (no placeholder required)
3561 template<typename C>
3562 void bind( bool C::* field ) {
3563 m_arg->boundField = new Detail::BoundDataMember<C,bool>( field );
3564 }
3565
3566 // Bind a method taking a single, non-boolean argument (requires a placeholder string)
3567 template<typename C, typename M>
3568 void bind( void (C::* unaryMethod)( M ), std::string const& placeholder ) {
3569 m_arg->boundField = new Detail::BoundUnaryMethod<C,M>( unaryMethod );
3570 m_arg->placeholder = placeholder;
3571 }
3572
3573 // Bind a method taking a single, boolean argument (no placeholder string required)
3574 template<typename C>
3575 void bind( void (C::* unaryMethod)( bool ) ) {
3576 m_arg->boundField = new Detail::BoundUnaryMethod<C,bool>( unaryMethod );
3577 }
3578
3579 // Bind a method that takes no arguments (will be called if opt is present)
3580 template<typename C>
3581 void bind( void (C::* nullaryMethod)() ) {
3582 m_arg->boundField = new Detail::BoundNullaryMethod<C>( nullaryMethod );
3583 }
3584
3585 // Bind a free function taking a single argument - the object to operate on (no placeholder string required)
3586 template<typename C>
3587 void bind( void (* unaryFunction)( C& ) ) {
3588 m_arg->boundField = new Detail::BoundUnaryFunction<C>( unaryFunction );
3589 }
3590
3591 // Bind a free function taking a single argument - the object to operate on (requires a placeholder string)
3592 template<typename C, typename T>
3593 void bind( void (* binaryFunction)( C&, T ), std::string const& placeholder ) {
3594 m_arg->boundField = new Detail::BoundBinaryFunction<C, T>( binaryFunction );
3595 m_arg->placeholder = placeholder;
3596 }
3597
3598 ArgBuilder& describe( std::string const& description ) {
3599 m_arg->description = description;
3600 return *this;
3601 }
3602 ArgBuilder& detail( std::string const& detail ) {
3603 m_arg->detail = detail;
3604 return *this;
3605 }
3606
3607 protected:
3608 Arg* m_arg;
3609 };
3610
3611 class OptBuilder : public ArgBuilder {
3612 public:
3613 OptBuilder( Arg* arg ) : ArgBuilder( arg ) {}
3614 OptBuilder( OptBuilder& other ) : ArgBuilder( other ) {}
3615
3616 OptBuilder& operator[]( std::string const& optName ) {
3617 addOptName( *ArgBuilder::m_arg, optName );
3618 return *this;
3619 }
3620 };
3621
3622 public:
3623
3624 CommandLine()
3625 : m_boundProcessName( new Detail::NullBinder<ConfigT>() ),
3626 m_highestSpecifiedArgPosition( 0 ),
3627 m_throwOnUnrecognisedTokens( false )
3628 {}
3629 CommandLine( CommandLine const& other )
3630 : m_boundProcessName( other.m_boundProcessName ),
3631 m_options ( other.m_options ),
3632 m_positionalArgs( other.m_positionalArgs ),
3633 m_highestSpecifiedArgPosition( other.m_highestSpecifiedArgPosition ),
3634 m_throwOnUnrecognisedTokens( other.m_throwOnUnrecognisedTokens )
3635 {
3636 if( other.m_floatingArg.get() )
3637 m_floatingArg = ArgAutoPtr( new Arg( *other.m_floatingArg ) );
3638 }
3639
3640 CommandLine& setThrowOnUnrecognisedTokens( bool shouldThrow = true ) {
3641 m_throwOnUnrecognisedTokens = shouldThrow;
3642 return *this;
3643 }
3644
3645 OptBuilder operator[]( std::string const& optName ) {
3646 m_options.push_back( Arg() );
3647 addOptName( m_options.back(), optName );
3648 OptBuilder builder( &m_options.back() );
3649 return builder;
3650 }
3651
3652 ArgBuilder operator[]( int position ) {
3653 m_positionalArgs.insert( std::make_pair( position, Arg() ) );
3654 if( position > m_highestSpecifiedArgPosition )
3655 m_highestSpecifiedArgPosition = position;
3656 setPositionalArg( m_positionalArgs[position], position );
3657 ArgBuilder builder( &m_positionalArgs[position] );
3658 return builder;
3659 }
3660
3661 // Invoke this with the _ instance
3662 ArgBuilder operator[]( UnpositionalTag ) {
3663 if( m_floatingArg.get() )
3664 throw std::logic_error( "Only one unpositional argument can be added" );
3665 m_floatingArg = ArgAutoPtr( new Arg() );
3666 ArgBuilder builder( m_floatingArg.get() );
3667 return builder;
3668 }
3669
3670 template<typename C, typename M>
3671 void bindProcessName( M C::* field ) {
3672 m_boundProcessName = new Detail::BoundDataMember<C,M>( field );
3673 }
3674 template<typename C, typename M>
3675 void bindProcessName( void (C::*_unaryMethod)( M ) ) {
3676 m_boundProcessName = new Detail::BoundUnaryMethod<C,M>( _unaryMethod );
3677 }
3678
3679 void optUsage( std::ostream& os, std::size_t indent = 0, std::size_t width = Detail::consoleWidth ) const {
3680 typename std::vector<Arg>::const_iterator itBegin = m_options.begin(), itEnd = m_options.end(), it;
3681 std::size_t maxWidth = 0;
3682 for( it = itBegin; it != itEnd; ++it )
3683 maxWidth = (std::max)( maxWidth, it->commands().size() );
3684
3685 for( it = itBegin; it != itEnd; ++it ) {
3686 Detail::Text usage( it->commands(), Detail::TextAttributes()
3687 .setWidth( maxWidth+indent )
3688 .setIndent( indent ) );
3689 Detail::Text desc( it->description, Detail::TextAttributes()
3690 .setWidth( width - maxWidth - 3 ) );
3691
3692 for( std::size_t i = 0; i < (std::max)( usage.size(), desc.size() ); ++i ) {
3693 std::string usageCol = i < usage.size() ? usage[i] : "";
3694 os << usageCol;
3695
3696 if( i < desc.size() && !desc[i].empty() )
3697 os << std::string( indent + 2 + maxWidth - usageCol.size(), ' ' )
3698 << desc[i];
3699 os << "\n";
3700 }
3701 }
3702 }
3703 std::string optUsage() const {
3704 std::ostringstream oss;
3705 optUsage( oss );
3706 return oss.str();
3707 }
3708
3709 void argSynopsis( std::ostream& os ) const {
3710 for( int i = 1; i <= m_highestSpecifiedArgPosition; ++i ) {
3711 if( i > 1 )
3712 os << " ";
3713 typename std::map<int, Arg>::const_iterator it = m_positionalArgs.find( i );
3714 if( it != m_positionalArgs.end() )
3715 os << "<" << it->second.placeholder << ">";
3716 else if( m_floatingArg.get() )
3717 os << "<" << m_floatingArg->placeholder << ">";
3718 else
3719 throw std::logic_error( "non consecutive positional arguments with no floating args" );
3720 }
3721 // !TBD No indication of mandatory args
3722 if( m_floatingArg.get() ) {
3723 if( m_highestSpecifiedArgPosition > 1 )
3724 os << " ";
3725 os << "[<" << m_floatingArg->placeholder << "> ...]";
3726 }
3727 }
3728 std::string argSynopsis() const {
3729 std::ostringstream oss;
3730 argSynopsis( oss );
3731 return oss.str();
3732 }
3733
3734 void usage( std::ostream& os, std::string const& procName ) const {
3735 validate();
3736 os << "usage:\n " << procName << " ";
3737 argSynopsis( os );
3738 if( !m_options.empty() ) {
3739 os << " [options]\n\nwhere options are: \n";
3740 optUsage( os, 2 );
3741 }
3742 os << "\n";
3743 }
3744 std::string usage( std::string const& procName ) const {
3745 std::ostringstream oss;
3746 usage( oss, procName );
3747 return oss.str();
3748 }
3749
3750 ConfigT parse( int argc, char const * const * argv ) const {
3751 ConfigT config;
3752 parseInto( argc, argv, config );
3753 return config;
3754 }
3755
3756 std::vector<Parser::Token> parseInto( int argc, char const * const * argv, ConfigT& config ) const {
3757 std::string processName = argv[0];
3758 std::size_t lastSlash = processName.find_last_of( "/\\" );
3759 if( lastSlash != std::string::npos )
3760 processName = processName.substr( lastSlash+1 );
3761 m_boundProcessName.set( config, processName );
3762 std::vector<Parser::Token> tokens;
3763 Parser parser;
3764 parser.parseIntoTokens( argc, argv, tokens );
3765 return populate( tokens, config );
3766 }
3767
3768 std::vector<Parser::Token> populate( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {
3769 validate();
3770 std::vector<Parser::Token> unusedTokens = populateOptions( tokens, config );
3771 unusedTokens = populateFixedArgs( unusedTokens, config );
3772 unusedTokens = populateFloatingArgs( unusedTokens, config );
3773 return unusedTokens;
3774 }
3775
3776 std::vector<Parser::Token> populateOptions( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {
3777 std::vector<Parser::Token> unusedTokens;
3778 std::vector<std::string> errors;
3779 for( std::size_t i = 0; i < tokens.size(); ++i ) {
3780 Parser::Token const& token = tokens[i];
3781 typename std::vector<Arg>::const_iterator it = m_options.begin(), itEnd = m_options.end();
3782 for(; it != itEnd; ++it ) {
3783 Arg const& arg = *it;
3784
3785 try {
3786 if( ( token.type == Parser::Token::ShortOpt && arg.hasShortName( token.data ) ) ||
3787 ( token.type == Parser::Token::LongOpt && arg.hasLongName( token.data ) ) ) {
3788 if( arg.takesArg() ) {
3789 if( i == tokens.size()-1 || tokens[i+1].type != Parser::Token::Positional )
3790 errors.push_back( "Expected argument to option: " + token.data );
3791 else
3792 arg.boundField.set( config, tokens[++i].data );
3793 }
3794 else {
3795 arg.boundField.setFlag( config );
3796 }
3797 break;
3798 }
3799 }
3800 catch( std::exception& ex ) {
3801 errors.push_back( std::string( ex.what() ) + "\n- while parsing: (" + arg.commands() + ")" );
3802 }
3803 }
3804 if( it == itEnd ) {
3805 if( token.type == Parser::Token::Positional || !m_throwOnUnrecognisedTokens )
3806 unusedTokens.push_back( token );
3807 else if( m_throwOnUnrecognisedTokens )
3808 errors.push_back( "unrecognised option: " + token.data );
3809 }
3810 }
3811 if( !errors.empty() ) {
3812 std::ostringstream oss;
3813 for( std::vector<std::string>::const_iterator it = errors.begin(), itEnd = errors.end();
3814 it != itEnd;
3815 ++it ) {
3816 if( it != errors.begin() )
3817 oss << "\n";
3818 oss << *it;
3819 }
3820 throw std::runtime_error( oss.str() );
3821 }
3822 return unusedTokens;
3823 }
3824 std::vector<Parser::Token> populateFixedArgs( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {
3825 std::vector<Parser::Token> unusedTokens;
3826 int position = 1;
3827 for( std::size_t i = 0; i < tokens.size(); ++i ) {
3828 Parser::Token const& token = tokens[i];
3829 typename std::map<int, Arg>::const_iterator it = m_positionalArgs.find( position );
3830 if( it != m_positionalArgs.end() )
3831 it->second.boundField.set( config, token.data );
3832 else
3833 unusedTokens.push_back( token );
3834 if( token.type == Parser::Token::Positional )
3835 position++;
3836 }
3837 return unusedTokens;
3838 }
3839 std::vector<Parser::Token> populateFloatingArgs( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {
3840 if( !m_floatingArg.get() )
3841 return tokens;
3842 std::vector<Parser::Token> unusedTokens;
3843 for( std::size_t i = 0; i < tokens.size(); ++i ) {
3844 Parser::Token const& token = tokens[i];
3845 if( token.type == Parser::Token::Positional )
3846 m_floatingArg->boundField.set( config, token.data );
3847 else
3848 unusedTokens.push_back( token );
3849 }
3850 return unusedTokens;
3851 }
3852
3853 void validate() const
3854 {
3855 if( m_options.empty() && m_positionalArgs.empty() && !m_floatingArg.get() )
3856 throw std::logic_error( "No options or arguments specified" );
3857
3858 for( typename std::vector<Arg>::const_iterator it = m_options.begin(),
3859 itEnd = m_options.end();
3860 it != itEnd; ++it )
3861 it->validate();
3862 }
3863
3864 private:
3865 Detail::BoundArgFunction<ConfigT> m_boundProcessName;
3866 std::vector<Arg> m_options;
3867 std::map<int, Arg> m_positionalArgs;
3868 ArgAutoPtr m_floatingArg;
3869 int m_highestSpecifiedArgPosition;
3870 bool m_throwOnUnrecognisedTokens;
3871 };
3872
3873 } // end namespace Clara
3874
3875 STITCH_CLARA_CLOSE_NAMESPACE
3876 #undef STITCH_CLARA_OPEN_NAMESPACE
3877 #undef STITCH_CLARA_CLOSE_NAMESPACE
3878
3879 #endif // TWOBLUECUBES_CLARA_H_INCLUDED
3880 #undef STITCH_CLARA_OPEN_NAMESPACE
3881
3882 // Restore Clara's value for console width, if present
3883 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
3884 #define CLARA_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
3885 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
3886 #endif
3887
3888 #include <fstream>
3889
3890 namespace Catch {
3891
3892 inline void abortAfterFirst( ConfigData& config ) { config.abortAfter = 1; }
3893 inline void abortAfterX( ConfigData& config, int x ) {
3894 if( x < 1 )
3895 throw std::runtime_error( "Value after -x or --abortAfter must be greater than zero" );
3896 config.abortAfter = x;
3897 }
3898 inline void addTestOrTags( ConfigData& config, std::string const& _testSpec ) { config.testsOrTags.push_back( _testSpec ); }
3899
3900 inline void addWarning( ConfigData& config, std::string const& _warning ) {
3901 if( _warning == "NoAssertions" )
3902 config.warnings = (WarnAbout::What)( config.warnings | WarnAbout::NoAssertions );
3903 else
3904 throw std::runtime_error( "Unrecognised warning: '" + _warning + "'" );
3905
3906 }
3907 inline void setVerbosity( ConfigData& config, int level ) {
3908 // !TBD: accept strings?
3909 config.verbosity = (Verbosity::Level)level;
3910 }
3911 inline void setShowDurations( ConfigData& config, bool _showDurations ) {
3912 config.showDurations = _showDurations
3913 ? ShowDurations::Always
3914 : ShowDurations::Never;
3915 }
3916 inline void loadTestNamesFromFile( ConfigData& config, std::string const& _filename ) {
3917 std::ifstream f( _filename.c_str() );
3918 if( !f.is_open() )
3919 throw std::domain_error( "Unable to load input file: " + _filename );
3920
3921 std::string line;
3922 while( std::getline( f, line ) ) {
3923 line = trim(line);
3924 if( !line.empty() && !startsWith( line, "#" ) )
3925 addTestOrTags( config, line );
3926 }
3927 }
3928
3929 inline Clara::CommandLine<ConfigData> makeCommandLineParser() {
3930
3931 using namespace Clara;
3932 CommandLine<ConfigData> cli;
3933
3934 cli.bindProcessName( &ConfigData::processName );
3935
3936 cli["-?"]["-h"]["--help"]
3937 .describe( "display usage information" )
3938 .bind( &ConfigData::showHelp );
3939
3940 cli["-l"]["--list-tests"]
3941 .describe( "list all/matching test cases" )
3942 .bind( &ConfigData::listTests );
3943
3944 cli["-t"]["--list-tags"]
3945 .describe( "list all/matching tags" )
3946 .bind( &ConfigData::listTags );
3947
3948 cli["-s"]["--success"]
3949 .describe( "include successful tests in output" )
3950 .bind( &ConfigData::showSuccessfulTests );
3951
3952 cli["-b"]["--break"]
3953 .describe( "break into debugger on failure" )
3954 .bind( &ConfigData::shouldDebugBreak );
3955
3956 cli["-e"]["--nothrow"]
3957 .describe( "skip exception tests" )
3958 .bind( &ConfigData::noThrow );
3959
3960 cli["-i"]["--invisibles"]
3961 .describe( "show invisibles (tabs, newlines)" )
3962 .bind( &ConfigData::showInvisibles );
3963
3964 cli["-o"]["--out"]
3965 .describe( "output filename" )
3966 .bind( &ConfigData::outputFilename, "filename" );
3967
3968 cli["-r"]["--reporter"]
3969 // .placeholder( "name[:filename]" )
3970 .describe( "reporter to use (defaults to console)" )
3971 .bind( &ConfigData::reporterName, "name" );
3972
3973 cli["-n"]["--name"]
3974 .describe( "suite name" )
3975 .bind( &ConfigData::name, "name" );
3976
3977 cli["-a"]["--abort"]
3978 .describe( "abort at first failure" )
3979 .bind( &abortAfterFirst );
3980
3981 cli["-x"]["--abortx"]
3982 .describe( "abort after x failures" )
3983 .bind( &abortAfterX, "no. failures" );
3984
3985 cli["-w"]["--warn"]
3986 .describe( "enable warnings" )
3987 .bind( &addWarning, "warning name" );
3988
3989 // - needs updating if reinstated
3990 // cli.into( &setVerbosity )
3991 // .describe( "level of verbosity (0=no output)" )
3992 // .shortOpt( "v")
3993 // .longOpt( "verbosity" )
3994 // .placeholder( "level" );
3995
3996 cli[_]
3997 .describe( "which test or tests to use" )
3998 .bind( &addTestOrTags, "test name, pattern or tags" );
3999
4000 cli["-d"]["--durations"]
4001 .describe( "show test durations" )
4002 .bind( &setShowDurations, "yes/no" );
4003
4004 cli["-f"]["--input-file"]
4005 .describe( "load test names to run from a file" )
4006 .bind( &loadTestNamesFromFile, "filename" );
4007
4008 // Less common commands which don't have a short form
4009 cli["--list-test-names-only"]
4010 .describe( "list all/matching test cases names only" )
4011 .bind( &ConfigData::listTestNamesOnly );
4012
4013 cli["--list-reporters"]
4014 .describe( "list all reporters" )
4015 .bind( &ConfigData::listReporters );
4016
4017 return cli;
4018 }
4019
4020 } // end namespace Catch
4021
4022 // #included from: internal/catch_list.hpp
4023 #define TWOBLUECUBES_CATCH_LIST_HPP_INCLUDED
4024
4025 // #included from: catch_text.h
4026 #define TWOBLUECUBES_CATCH_TEXT_H_INCLUDED
4027
4028 #define TBC_TEXT_FORMAT_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH
4029
4030 #define CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE Catch
4031 // #included from: ../external/tbc_text_format.h
4032 // Only use header guard if we are not using an outer namespace
4033 #ifndef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
4034 # ifdef TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED
4035 # ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
4036 # define TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
4037 # endif
4038 # else
4039 # define TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED
4040 # endif
4041 #endif
4042 #ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
4043 #include <string>
4044 #include <vector>
4045 #include <sstream>
4046
4047 // Use optional outer namespace
4048 #ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
4049 namespace CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE {
4050 #endif
4051
4052 namespace Tbc {
4053
4054 #ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH
4055 const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH;
4056 #else
4057 const unsigned int consoleWidth = 80;
4058 #endif
4059
4060 struct TextAttributes {
4061 TextAttributes()
4062 : initialIndent( std::string::npos ),
4063 indent( 0 ),
4064 width( consoleWidth-1 ),
4065 tabChar( '\t' )
4066 {}
4067
4068 TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; }
4069 TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; }
4070 TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; }
4071 TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; }
4072
4073 std::size_t initialIndent; // indent of first line, or npos
4074 std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos
4075 std::size_t width; // maximum width of text, including indent. Longer text will wrap
4076 char tabChar; // If this char is seen the indent is changed to current pos
4077 };
4078
4079 class Text {
4080 public:
4081 Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() )
4082 : attr( _attr )
4083 {
4084 std::string wrappableChars = " [({.,/|\\-";
4085 std::size_t indent = _attr.initialIndent != std::string::npos
4086 ? _attr.initialIndent
4087 : _attr.indent;
4088 std::string remainder = _str;
4089
4090 while( !remainder.empty() ) {
4091 if( lines.size() >= 1000 ) {
4092 lines.push_back( "... message truncated due to excessive size" );
4093 return;
4094 }
4095 std::size_t tabPos = std::string::npos;
4096 std::size_t width = (std::min)( remainder.size(), _attr.width - indent );
4097 std::size_t pos = remainder.find_first_of( '\n' );
4098 if( pos <= width ) {
4099 width = pos;
4100 }
4101 pos = remainder.find_last_of( _attr.tabChar, width );
4102 if( pos != std::string::npos ) {
4103 tabPos = pos;
4104 if( remainder[width] == '\n' )
4105 width--;
4106 remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 );
4107 }
4108
4109 if( width == remainder.size() ) {
4110 spliceLine( indent, remainder, width );
4111 }
4112 else if( remainder[width] == '\n' ) {
4113 spliceLine( indent, remainder, width );
4114 if( width <= 1 || remainder.size() != 1 )
4115 remainder = remainder.substr( 1 );
4116 indent = _attr.indent;
4117 }
4118 else {
4119 pos = remainder.find_last_of( wrappableChars, width );
4120 if( pos != std::string::npos && pos > 0 ) {
4121 spliceLine( indent, remainder, pos );
4122 if( remainder[0] == ' ' )
4123 remainder = remainder.substr( 1 );
4124 }
4125 else {
4126 spliceLine( indent, remainder, width-1 );
4127 lines.back() += "-";
4128 }
4129 if( lines.size() == 1 )
4130 indent = _attr.indent;
4131 if( tabPos != std::string::npos )
4132 indent += tabPos;
4133 }
4134 }
4135 }
4136
4137 void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) {
4138 lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) );
4139 _remainder = _remainder.substr( _pos );
4140 }
4141
4142 typedef std::vector<std::string>::const_iterator const_iterator;
4143
4144 const_iterator begin() const { return lines.begin(); }
4145 const_iterator end() const { return lines.end(); }
4146 std::string const& last() const { return lines.back(); }
4147 std::size_t size() const { return lines.size(); }
4148 std::string const& operator[]( std::size_t _index ) const { return lines[_index]; }
4149 std::string toString() const {
4150 std::ostringstream oss;
4151 oss << *this;
4152 return oss.str();
4153 }
4154
4155 inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) {
4156 for( Text::const_iterator it = _text.begin(), itEnd = _text.end();
4157 it != itEnd; ++it ) {
4158 if( it != _text.begin() )
4159 _stream << "\n";
4160 _stream << *it;
4161 }
4162 return _stream;
4163 }
4164
4165 private:
4166 std::string str;
4167 TextAttributes attr;
4168 std::vector<std::string> lines;
4169 };
4170
4171 } // end namespace Tbc
4172
4173 #ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
4174 } // end outer namespace
4175 #endif
4176
4177 #endif // TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
4178 #undef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
4179
4180 namespace Catch {
4181 using Tbc::Text;
4182 using Tbc::TextAttributes;
4183 }
4184
4185 // #included from: catch_console_colour.hpp
4186 #define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_HPP_INCLUDED
4187
4188 namespace Catch {
4189
4190 namespace Detail {
4191 struct IColourImpl;
4192 }
4193
4194 struct Colour {
4195 enum Code {
4196 None = 0,
4197
4198 White,
4199 Red,
4200 Green,
4201 Blue,
4202 Cyan,
4203 Yellow,
4204 Grey,
4205
4206 Bright = 0x10,
4207
4208 BrightRed = Bright | Red,
4209 BrightGreen = Bright | Green,
4210 LightGrey = Bright | Grey,
4211 BrightWhite = Bright | White,
4212
4213 // By intention
4214 FileName = LightGrey,
4215 ResultError = BrightRed,
4216 ResultSuccess = BrightGreen,
4217
4218 Error = BrightRed,
4219 Success = Green,
4220
4221 OriginalExpression = Cyan,
4222 ReconstructedExpression = Yellow,
4223
4224 SecondaryText = LightGrey,
4225 Headers = White
4226 };
4227
4228 // Use constructed object for RAII guard
4229 Colour( Code _colourCode );
4230 ~Colour();
4231
4232 // Use static method for one-shot changes
4233 static void use( Code _colourCode );
4234
4235 private:
4236 static Detail::IColourImpl* impl();
4237 };
4238
4239 } // end namespace Catch
4240
4241 // #included from: catch_interfaces_reporter.h
4242 #define TWOBLUECUBES_CATCH_INTERFACES_REPORTER_H_INCLUDED
4243
4244 // #included from: catch_option.hpp
4245 #define TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED
4246
4247 namespace Catch {
4248
4249 // An optional type
4250 template<typename T>
4251 class Option {
4252 public:
4253 Option() : nullableValue( NULL ) {}
4254 Option( T const& _value )
4255 : nullableValue( new( storage ) T( _value ) )
4256 {}
4257 Option( Option const& _other )
4258 : nullableValue( _other ? new( storage ) T( *_other ) : NULL )
4259 {}
4260
4261 ~Option() {
4262 reset();
4263 }
4264
4265 Option& operator= ( Option const& _other ) {
4266 if( &_other != this ) {
4267 reset();
4268 if( _other )
4269 nullableValue = new( storage ) T( *_other );
4270 }
4271 return *this;
4272 }
4273 Option& operator = ( T const& _value ) {
4274 reset();
4275 nullableValue = new( storage ) T( _value );
4276 return *this;
4277 }
4278
4279 void reset() {
4280 if( nullableValue )
4281 nullableValue->~T();
4282 nullableValue = NULL;
4283 }
4284
4285 T& operator*() { return *nullableValue; }
4286 T const& operator*() const { return *nullableValue; }
4287 T* operator->() { return nullableValue; }
4288 const T* operator->() const { return nullableValue; }
4289
4290 T valueOr( T const& defaultValue ) const {
4291 return nullableValue ? *nullableValue : defaultValue;
4292 }
4293
4294 bool some() const { return nullableValue != NULL; }
4295 bool none() const { return nullableValue == NULL; }
4296
4297 bool operator !() const { return nullableValue == NULL; }
4298 operator SafeBool::type() const {
4299 return SafeBool::makeSafe( some() );
4300 }
4301
4302 private:
4303 T* nullableValue;
4304 char storage[sizeof(T)];
4305 };
4306
4307 } // end namespace Catch
4308
4309 #include <string>
4310 #include <ostream>
4311 #include <map>
4312 #include <assert.h>
4313
4314 namespace Catch
4315 {
4316 struct ReporterConfig {
4317 explicit ReporterConfig( Ptr<IConfig> const& _fullConfig )
4318 : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
4319
4320 ReporterConfig( Ptr<IConfig> const& _fullConfig, std::ostream& _stream )
4321 : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
4322
4323 std::ostream& stream() const { return *m_stream; }
4324 Ptr<IConfig> fullConfig() const { return m_fullConfig; }
4325
4326 private:
4327 std::ostream* m_stream;
4328 Ptr<IConfig> m_fullConfig;
4329 };
4330
4331 struct ReporterPreferences {
4332 ReporterPreferences()
4333 : shouldRedirectStdOut( false )
4334 {}
4335
4336 bool shouldRedirectStdOut;
4337 };
4338
4339 template<typename T>
4340 struct LazyStat : Option<T> {
4341 LazyStat() : used( false ) {}
4342 LazyStat& operator=( T const& _value ) {
4343 Option<T>::operator=( _value );
4344 used = false;
4345 return *this;
4346 }
4347 void reset() {
4348 Option<T>::reset();
4349 used = false;
4350 }
4351 bool used;
4352 };
4353
4354 struct TestRunInfo {
4355 TestRunInfo( std::string const& _name ) : name( _name ) {}
4356 std::string name;
4357 };
4358 struct GroupInfo {
4359 GroupInfo( std::string const& _name,
4360 std::size_t _groupIndex,
4361 std::size_t _groupsCount )
4362 : name( _name ),
4363 groupIndex( _groupIndex ),
4364 groupsCounts( _groupsCount )
4365 {}
4366
4367 std::string name;
4368 std::size_t groupIndex;
4369 std::size_t groupsCounts;
4370 };
4371
4372 struct AssertionStats {
4373 AssertionStats( AssertionResult const& _assertionResult,
4374 std::vector<MessageInfo> const& _infoMessages,
4375 Totals const& _totals )
4376 : assertionResult( _assertionResult ),
4377 infoMessages( _infoMessages ),
4378 totals( _totals )
4379 {
4380 if( assertionResult.hasMessage() ) {
4381 // Copy message into messages list.
4382 // !TBD This should have been done earlier, somewhere
4383 MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
4384 builder << assertionResult.getMessage();
4385 builder.m_info.message = builder.m_stream.str();
4386
4387 infoMessages.push_back( builder.m_info );
4388 }
4389 }
4390 virtual ~AssertionStats();
4391
4392 # ifdef CATCH_CPP11_OR_GREATER
4393 AssertionStats( AssertionStats const& ) = default;
4394 AssertionStats( AssertionStats && ) = default;
4395 AssertionStats& operator = ( AssertionStats const& ) = default;
4396 AssertionStats& operator = ( AssertionStats && ) = default;
4397 # endif
4398
4399 AssertionResult assertionResult;
4400 std::vector<MessageInfo> infoMessages;
4401 Totals totals;
4402 };
4403
4404 struct SectionStats {
4405 SectionStats( SectionInfo const& _sectionInfo,
4406 Counts const& _assertions,
4407 double _durationInSeconds,
4408 bool _missingAssertions )
4409 : sectionInfo( _sectionInfo ),
4410 assertions( _assertions ),
4411 durationInSeconds( _durationInSeconds ),
4412 missingAssertions( _missingAssertions )
4413 {}
4414 virtual ~SectionStats();
4415 # ifdef CATCH_CPP11_OR_GREATER
4416 SectionStats( SectionStats const& ) = default;
4417 SectionStats( SectionStats && ) = default;
4418 SectionStats& operator = ( SectionStats const& ) = default;
4419 SectionStats& operator = ( SectionStats && ) = default;
4420 # endif
4421
4422 SectionInfo sectionInfo;
4423 Counts assertions;
4424 double durationInSeconds;
4425 bool missingAssertions;
4426 };
4427
4428 struct TestCaseStats {
4429 TestCaseStats( TestCaseInfo const& _testInfo,
4430 Totals const& _totals,
4431 std::string const& _stdOut,
4432 std::string const& _stdErr,
4433 bool _aborting )
4434 : testInfo( _testInfo ),
4435 totals( _totals ),
4436 stdOut( _stdOut ),
4437 stdErr( _stdErr ),
4438 aborting( _aborting )
4439 {}
4440 virtual ~TestCaseStats();
4441
4442 # ifdef CATCH_CPP11_OR_GREATER
4443 TestCaseStats( TestCaseStats const& ) = default;
4444 TestCaseStats( TestCaseStats && ) = default;
4445 TestCaseStats& operator = ( TestCaseStats const& ) = default;
4446 TestCaseStats& operator = ( TestCaseStats && ) = default;
4447 # endif
4448
4449 TestCaseInfo testInfo;
4450 Totals totals;
4451 std::string stdOut;
4452 std::string stdErr;
4453 bool aborting;
4454 };
4455
4456 struct TestGroupStats {
4457 TestGroupStats( GroupInfo const& _groupInfo,
4458 Totals const& _totals,
4459 bool _aborting )
4460 : groupInfo( _groupInfo ),
4461 totals( _totals ),
4462 aborting( _aborting )
4463 {}
4464 TestGroupStats( GroupInfo const& _groupInfo )
4465 : groupInfo( _groupInfo ),
4466 aborting( false )
4467 {}
4468 virtual ~TestGroupStats();
4469
4470 # ifdef CATCH_CPP11_OR_GREATER
4471 TestGroupStats( TestGroupStats const& ) = default;
4472 TestGroupStats( TestGroupStats && ) = default;
4473 TestGroupStats& operator = ( TestGroupStats const& ) = default;
4474 TestGroupStats& operator = ( TestGroupStats && ) = default;
4475 # endif
4476
4477 GroupInfo groupInfo;
4478 Totals totals;
4479 bool aborting;
4480 };
4481
4482 struct TestRunStats {
4483 TestRunStats( TestRunInfo const& _runInfo,
4484 Totals const& _totals,
4485 bool _aborting )
4486 : runInfo( _runInfo ),
4487 totals( _totals ),
4488 aborting( _aborting )
4489 {}
4490 virtual ~TestRunStats();
4491
4492 # ifndef CATCH_CPP11_OR_GREATER
4493 TestRunStats( TestRunStats const& _other )
4494 : runInfo( _other.runInfo ),
4495 totals( _other.totals ),
4496 aborting( _other.aborting )
4497 {}
4498 # else
4499 TestRunStats( TestRunStats const& ) = default;
4500 TestRunStats( TestRunStats && ) = default;
4501 TestRunStats& operator = ( TestRunStats const& ) = default;
4502 TestRunStats& operator = ( TestRunStats && ) = default;
4503 # endif
4504
4505 TestRunInfo runInfo;
4506 Totals totals;
4507 bool aborting;
4508 };
4509
4510 struct IStreamingReporter : IShared {
4511 virtual ~IStreamingReporter();
4512
4513 // Implementing class must also provide the following static method:
4514 // static std::string getDescription();
4515
4516 virtual ReporterPreferences getPreferences() const = 0;
4517
4518 virtual void noMatchingTestCases( std::string const& spec ) = 0;
4519
4520 virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
4521 virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
4522
4523 virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
4524 virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
4525
4526 virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
4527
4528 virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
4529 virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
4530 virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
4531 virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
4532 virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
4533 };
4534
4535 struct IReporterFactory {
4536 virtual ~IReporterFactory();
4537 virtual IStreamingReporter* create( ReporterConfig const& config ) const = 0;
4538 virtual std::string getDescription() const = 0;
4539 };
4540
4541 struct IReporterRegistry {
4542 typedef std::map<std::string, IReporterFactory*> FactoryMap;
4543
4544 virtual ~IReporterRegistry();
4545 virtual IStreamingReporter* create( std::string const& name, Ptr<IConfig> const& config ) const = 0;
4546 virtual FactoryMap const& getFactories() const = 0;
4547 };
4548
4549 }
4550
4551 #include <limits>
4552 #include <algorithm>
4553
4554 namespace Catch {
4555
4556 inline std::size_t listTests( Config const& config ) {
4557 if( config.filters().empty() )
4558 std::cout << "All available test cases:\n";
4559 else
4560 std::cout << "Matching test cases:\n";
4561
4562 std::size_t matchedTests = 0;
4563 TextAttributes nameAttr, tagsAttr;
4564 nameAttr.setInitialIndent( 2 ).setIndent( 4 );
4565 tagsAttr.setIndent( 6 );
4566
4567 std::vector<TestCase> matchedTestCases;
4568 getRegistryHub().getTestCaseRegistry().getFilteredTests( config, matchedTestCases );
4569 for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();
4570 it != itEnd;
4571 ++it ) {
4572 matchedTests++;
4573 TestCaseInfo const& testCaseInfo = it->getTestCaseInfo();
4574 Colour::Code colour = testCaseInfo.isHidden
4575 ? Colour::SecondaryText
4576 : Colour::None;
4577 Colour colourGuard( colour );
4578
4579 std::cout << Text( testCaseInfo.name, nameAttr ) << std::endl;
4580 if( !testCaseInfo.tags.empty() )
4581 std::cout << Text( testCaseInfo.tagsAsString, tagsAttr ) << std::endl;
4582 }
4583
4584 if( config.filters().empty() )
4585 std::cout << pluralise( matchedTests, "test case" ) << "\n" << std::endl;
4586 else
4587 std::cout << pluralise( matchedTests, "matching test case" ) << "\n" << std::endl;
4588 return matchedTests;
4589 }
4590
4591 inline std::size_t listTestsNamesOnly( Config const& config ) {
4592 std::size_t matchedTests = 0;
4593 std::vector<TestCase> matchedTestCases;
4594 getRegistryHub().getTestCaseRegistry().getFilteredTests( config, matchedTestCases );
4595 for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();
4596 it != itEnd;
4597 ++it ) {
4598 matchedTests++;
4599 TestCaseInfo const& testCaseInfo = it->getTestCaseInfo();
4600 std::cout << testCaseInfo.name << std::endl;
4601 }
4602 return matchedTests;
4603 }
4604
4605 inline std::size_t listTags( Config const& config ) {
4606 if( config.filters().empty() )
4607 std::cout << "All available tags:\n";
4608 else
4609 std::cout << "Matching tags:\n";
4610
4611 std::map<std::string, int> tagCounts;
4612
4613 std::vector<TestCase> matchedTestCases;
4614 getRegistryHub().getTestCaseRegistry().getFilteredTests( config, matchedTestCases );
4615 for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();
4616 it != itEnd;
4617 ++it ) {
4618 for( std::set<std::string>::const_iterator tagIt = it->getTestCaseInfo().tags.begin(),
4619 tagItEnd = it->getTestCaseInfo().tags.end();
4620 tagIt != tagItEnd;
4621 ++tagIt ) {
4622 std::string tagName = *tagIt;
4623 std::map<std::string, int>::iterator countIt = tagCounts.find( tagName );
4624 if( countIt == tagCounts.end() )
4625 tagCounts.insert( std::make_pair( tagName, 1 ) );
4626 else
4627 countIt->second++;
4628 }
4629 }
4630
4631 for( std::map<std::string, int>::const_iterator countIt = tagCounts.begin(),
4632 countItEnd = tagCounts.end();
4633 countIt != countItEnd;
4634 ++countIt ) {
4635 std::ostringstream oss;
4636 oss << " " << countIt->second << " ";
4637 Text wrapper( "[" + countIt->first + "]", TextAttributes()
4638 .setInitialIndent( 0 )
4639 .setIndent( oss.str().size() )
4640 .setWidth( CATCH_CONFIG_CONSOLE_WIDTH-10 ) );
4641 std::cout << oss.str() << wrapper << "\n";
4642 }
4643 std::cout << pluralise( tagCounts.size(), "tag" ) << "\n" << std::endl;
4644 return tagCounts.size();
4645 }
4646
4647 inline std::size_t listReporters( Config const& /*config*/ ) {
4648 std::cout << "Available reports:\n";
4649 IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
4650 IReporterRegistry::FactoryMap::const_iterator itBegin = factories.begin(), itEnd = factories.end(), it;
4651 std::size_t maxNameLen = 0;
4652 for(it = itBegin; it != itEnd; ++it )
4653 maxNameLen = (std::max)( maxNameLen, it->first.size() );
4654
4655 for(it = itBegin; it != itEnd; ++it ) {
4656 Text wrapper( it->second->getDescription(), TextAttributes()
4657 .setInitialIndent( 0 )
4658 .setIndent( 7+maxNameLen )
4659 .setWidth( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) );
4660 std::cout << " "
4661 << it->first
4662 << ":"
4663 << std::string( maxNameLen - it->first.size() + 2, ' ' )
4664 << wrapper << "\n";
4665 }
4666 std::cout << std::endl;
4667 return factories.size();
4668 }
4669
4670 inline Option<std::size_t> list( Config const& config ) {
4671 Option<std::size_t> listedCount;
4672 if( config.listTests() )
4673 listedCount = listedCount.valueOr(0) + listTests( config );
4674 if( config.listTestNamesOnly() )
4675 listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
4676 if( config.listTags() )
4677 listedCount = listedCount.valueOr(0) + listTags( config );
4678 if( config.listReporters() )
4679 listedCount = listedCount.valueOr(0) + listReporters( config );
4680 return listedCount;
4681 }
4682
4683 } // end namespace Catch
4684
4685 // #included from: internal/catch_runner_impl.hpp
4686 #define TWOBLUECUBES_CATCH_RUNNER_IMPL_HPP_INCLUDED
4687
4688 // #included from: catch_test_case_tracker.hpp
4689 #define TWOBLUECUBES_CATCH_TEST_CASE_TRACKER_HPP_INCLUDED
4690
4691 #include <map>
4692 #include <string>
4693 #include <assert.h>
4694
4695 namespace Catch {
4696 namespace SectionTracking {
4697
4698 class TrackedSection {
4699
4700 typedef std::map<std::string, TrackedSection> TrackedSections;
4701
4702 public:
4703 enum RunState {
4704 NotStarted,
4705 Executing,
4706 ExecutingChildren,
4707 Completed
4708 };
4709
4710 TrackedSection( std::string const& name, TrackedSection* parent )
4711 : m_name( name ), m_runState( NotStarted ), m_parent( parent )
4712 {}
4713
4714 RunState runState() const { return m_runState; }
4715
4716 TrackedSection* findChild( std::string const& childName ) {
4717 TrackedSections::iterator it = m_children.find( childName );
4718 return it != m_children.end()
4719 ? &it->second
4720 : NULL;
4721 }
4722 TrackedSection* acquireChild( std::string const& childName ) {
4723 if( TrackedSection* child = findChild( childName ) )
4724 return child;
4725 m_children.insert( std::make_pair( childName, TrackedSection( childName, this ) ) );
4726 return findChild( childName );
4727 }
4728 void enter() {
4729 if( m_runState == NotStarted )
4730 m_runState = Executing;
4731 }
4732 void leave() {
4733 for( TrackedSections::const_iterator it = m_children.begin(), itEnd = m_children.end();
4734 it != itEnd;
4735 ++it )
4736 if( it->second.runState() != Completed ) {
4737 m_runState = ExecutingChildren;
4738 return;
4739 }
4740 m_runState = Completed;
4741 }
4742 TrackedSection* getParent() {
4743 return m_parent;
4744 }
4745 bool hasChildren() const {
4746 return !m_children.empty();
4747 }
4748
4749 private:
4750 std::string m_name;
4751 RunState m_runState;
4752 TrackedSections m_children;
4753 TrackedSection* m_parent;
4754
4755 };
4756
4757 class TestCaseTracker {
4758 public:
4759 TestCaseTracker( std::string const& testCaseName )
4760 : m_testCase( testCaseName, NULL ),
4761 m_currentSection( &m_testCase ),
4762 m_completedASectionThisRun( false )
4763 {}
4764
4765 bool enterSection( std::string const& name ) {
4766 TrackedSection* child = m_currentSection->acquireChild( name );
4767 if( m_completedASectionThisRun || child->runState() == TrackedSection::Completed )
4768 return false;
4769
4770 m_currentSection = child;
4771 m_currentSection->enter();
4772 return true;
4773 }
4774 void leaveSection() {
4775 m_currentSection->leave();
4776 m_currentSection = m_currentSection->getParent();
4777 assert( m_currentSection != NULL );
4778 m_completedASectionThisRun = true;
4779 }
4780
4781 bool currentSectionHasChildren() const {
4782 return m_currentSection->hasChildren();
4783 }
4784 bool isCompleted() const {
4785 return m_testCase.runState() == TrackedSection::Completed;
4786 }
4787
4788 class Guard {
4789 public:
4790 Guard( TestCaseTracker& tracker ) : m_tracker( tracker ) {
4791 m_tracker.enterTestCase();
4792 }
4793 ~Guard() {
4794 m_tracker.leaveTestCase();
4795 }
4796 private:
4797 Guard( Guard const& );
4798 void operator = ( Guard const& );
4799 TestCaseTracker& m_tracker;
4800 };
4801
4802 private:
4803 void enterTestCase() {
4804 m_currentSection = &m_testCase;
4805 m_completedASectionThisRun = false;
4806 m_testCase.enter();
4807 }
4808 void leaveTestCase() {
4809 m_testCase.leave();
4810 }
4811
4812 TrackedSection m_testCase;
4813 TrackedSection* m_currentSection;
4814 bool m_completedASectionThisRun;
4815 };
4816
4817 } // namespace SectionTracking
4818
4819 using SectionTracking::TestCaseTracker;
4820
4821 } // namespace Catch
4822
4823 #include <set>
4824 #include <string>
4825
4826 namespace Catch {
4827
4828 class StreamRedirect {
4829
4830 public:
4831 StreamRedirect( std::ostream& stream, std::string& targetString )
4832 : m_stream( stream ),
4833 m_prevBuf( stream.rdbuf() ),
4834 m_targetString( targetString )
4835 {
4836 stream.rdbuf( m_oss.rdbuf() );
4837 }
4838
4839 ~StreamRedirect() {
4840 m_targetString += m_oss.str();
4841 m_stream.rdbuf( m_prevBuf );
4842 }
4843
4844 private:
4845 std::ostream& m_stream;
4846 std::streambuf* m_prevBuf;
4847 std::ostringstream m_oss;
4848 std::string& m_targetString;
4849 };
4850
4851 ///////////////////////////////////////////////////////////////////////////
4852
4853 class RunContext : public IResultCapture, public IRunner {
4854
4855 RunContext( RunContext const& );
4856 void operator =( RunContext const& );
4857
4858 public:
4859
4860 explicit RunContext( Ptr<IConfig const> const& config, Ptr<IStreamingReporter> const& reporter )
4861 : m_runInfo( config->name() ),
4862 m_context( getCurrentMutableContext() ),
4863 m_activeTestCase( NULL ),
4864 m_config( config ),
4865 m_reporter( reporter ),
4866 m_prevRunner( &m_context.getRunner() ),
4867 m_prevResultCapture( &m_context.getResultCapture() ),
4868 m_prevConfig( m_context.getConfig() )
4869 {
4870 m_context.setRunner( this );
4871 m_context.setConfig( m_config );
4872 m_context.setResultCapture( this );
4873 m_reporter->testRunStarting( m_runInfo );
4874 }
4875
4876 virtual ~RunContext() {
4877 m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, aborting() ) );
4878 m_context.setRunner( m_prevRunner );
4879 m_context.setConfig( NULL );
4880 m_context.setResultCapture( m_prevResultCapture );
4881 m_context.setConfig( m_prevConfig );
4882 }
4883
4884 void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ) {
4885 m_reporter->testGroupStarting( GroupInfo( testSpec, groupIndex, groupsCount ) );
4886 }
4887 void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ) {
4888 m_reporter->testGroupEnded( TestGroupStats( GroupInfo( testSpec, groupIndex, groupsCount ), totals, aborting() ) );
4889 }
4890
4891 Totals runTest( TestCase const& testCase ) {
4892 Totals prevTotals = m_totals;
4893
4894 std::string redirectedCout;
4895 std::string redirectedCerr;
4896
4897 TestCaseInfo testInfo = testCase.getTestCaseInfo();
4898
4899 m_reporter->testCaseStarting( testInfo );
4900
4901 m_activeTestCase = &testCase;
4902 m_testCaseTracker = TestCaseTracker( testInfo.name );
4903
4904 do {
4905 do {
4906 runCurrentTest( redirectedCout, redirectedCerr );
4907 }
4908 while( !m_testCaseTracker->isCompleted() && !aborting() );
4909 }
4910 while( getCurrentContext().advanceGeneratorsForCurrentTest() && !aborting() );
4911
4912 Totals deltaTotals = m_totals.delta( prevTotals );
4913 m_totals.testCases += deltaTotals.testCases;
4914 m_reporter->testCaseEnded( TestCaseStats( testInfo,
4915 deltaTotals,
4916 redirectedCout,
4917 redirectedCerr,
4918 aborting() ) );
4919
4920 m_activeTestCase = NULL;
4921 m_testCaseTracker.reset();
4922
4923 return deltaTotals;
4924 }
4925
4926 Ptr<IConfig const> config() const {
4927 return m_config;
4928 }
4929
4930 private: // IResultCapture
4931
4932 virtual ResultAction::Value acceptExpression( ExpressionResultBuilder const& assertionResult, AssertionInfo const& assertionInfo ) {
4933 m_lastAssertionInfo = assertionInfo;
4934 return actOnCurrentResult( assertionResult.buildResult( assertionInfo ) );
4935 }
4936
4937 virtual void assertionEnded( AssertionResult const& result ) {
4938 if( result.getResultType() == ResultWas::Ok ) {
4939 m_totals.assertions.passed++;
4940 }
4941 else if( !result.isOk() ) {
4942 m_totals.assertions.failed++;
4943 }
4944
4945 if( m_reporter->assertionEnded( AssertionStats( result, m_messages, m_totals ) ) )
4946 m_messages.clear();
4947
4948 // Reset working state
4949 m_lastAssertionInfo = AssertionInfo( "", m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition );
4950 }
4951
4952 virtual bool sectionStarted (
4953 SectionInfo const& sectionInfo,
4954 Counts& assertions
4955 )
4956 {
4957 std::ostringstream oss;
4958 oss << sectionInfo.name << "@" << sectionInfo.lineInfo;
4959
4960 if( !m_testCaseTracker->enterSection( oss.str() ) )
4961 return false;
4962
4963 m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
4964
4965 m_reporter->sectionStarting( sectionInfo );
4966
4967 assertions = m_totals.assertions;
4968
4969 return true;
4970 }
4971 bool testForMissingAssertions( Counts& assertions ) {
4972 if( assertions.total() != 0 ||
4973 !m_config->warnAboutMissingAssertions() ||
4974 m_testCaseTracker->currentSectionHasChildren() )
4975 return false;
4976 m_totals.assertions.failed++;
4977 assertions.failed++;
4978 return true;
4979 }
4980
4981 virtual void sectionEnded( SectionInfo const& info, Counts const& prevAssertions, double _durationInSeconds ) {
4982 if( std::uncaught_exception() ) {
4983 m_unfinishedSections.push_back( UnfinishedSections( info, prevAssertions, _durationInSeconds ) );
4984 return;
4985 }
4986
4987 Counts assertions = m_totals.assertions - prevAssertions;
4988 bool missingAssertions = testForMissingAssertions( assertions );
4989
4990 m_testCaseTracker->leaveSection();
4991
4992 m_reporter->sectionEnded( SectionStats( info, assertions, _durationInSeconds, missingAssertions ) );
4993 m_messages.clear();
4994 }
4995
4996 virtual void pushScopedMessage( MessageInfo const& message ) {
4997 m_messages.push_back( message );
4998 }
4999
5000 virtual void popScopedMessage( MessageInfo const& message ) {
5001 m_messages.erase( std::remove( m_messages.begin(), m_messages.end(), message ), m_messages.end() );
5002 }
5003
5004 virtual bool shouldDebugBreak() const {
5005 return m_config->shouldDebugBreak();
5006 }
5007
5008 virtual std::string getCurrentTestName() const {
5009 return m_activeTestCase
5010 ? m_activeTestCase->getTestCaseInfo().name
5011 : "";
5012 }
5013
5014 virtual const AssertionResult* getLastResult() const {
5015 return &m_lastResult;
5016 }
5017
5018 public:
5019 // !TBD We need to do this another way!
5020 bool aborting() const {
5021 return m_totals.assertions.failed == static_cast<std::size_t>( m_config->abortAfter() );
5022 }
5023
5024 private:
5025
5026 ResultAction::Value actOnCurrentResult( AssertionResult const& result ) {
5027 m_lastResult = result;
5028 assertionEnded( m_lastResult );
5029
5030 ResultAction::Value action = ResultAction::None;
5031
5032 if( !m_lastResult.isOk() ) {
5033 action = ResultAction::Failed;
5034 if( shouldDebugBreak() )
5035 action = (ResultAction::Value)( action | ResultAction::Debug );
5036 if( aborting() )
5037 action = (ResultAction::Value)( action | ResultAction::Abort );
5038 }
5039 return action;
5040 }
5041
5042 void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ) {
5043 TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
5044 SectionInfo testCaseSection( testCaseInfo.name, testCaseInfo.description, testCaseInfo.lineInfo );
5045 m_reporter->sectionStarting( testCaseSection );
5046 Counts prevAssertions = m_totals.assertions;
5047 double duration = 0;
5048 try {
5049 m_lastAssertionInfo = AssertionInfo( "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal );
5050 TestCaseTracker::Guard guard( *m_testCaseTracker );
5051
5052 Timer timer;
5053 timer.start();
5054 if( m_reporter->getPreferences().shouldRedirectStdOut ) {
5055 StreamRedirect coutRedir( std::cout, redirectedCout );
5056 StreamRedirect cerrRedir( std::cerr, redirectedCerr );
5057 m_activeTestCase->invoke();
5058 }
5059 else {
5060 m_activeTestCase->invoke();
5061 }
5062 duration = timer.getElapsedSeconds();
5063 }
5064 catch( TestFailureException& ) {
5065 // This just means the test was aborted due to failure
5066 }
5067 catch(...) {
5068 ExpressionResultBuilder exResult( ResultWas::ThrewException );
5069 exResult << translateActiveException();
5070 actOnCurrentResult( exResult.buildResult( m_lastAssertionInfo ) );
5071 }
5072 // If sections ended prematurely due to an exception we stored their
5073 // infos here so we can tear them down outside the unwind process.
5074 for( std::vector<UnfinishedSections>::const_reverse_iterator it = m_unfinishedSections.rbegin(),
5075 itEnd = m_unfinishedSections.rend();
5076 it != itEnd;
5077 ++it )
5078 sectionEnded( it->info, it->prevAssertions, it->durationInSeconds );
5079 m_unfinishedSections.clear();
5080 m_messages.clear();
5081
5082 Counts assertions = m_totals.assertions - prevAssertions;
5083 bool missingAssertions = testForMissingAssertions( assertions );
5084
5085 SectionStats testCaseSectionStats( testCaseSection, assertions, duration, missingAssertions );
5086 m_reporter->sectionEnded( testCaseSectionStats );
5087 }
5088
5089 private:
5090 struct UnfinishedSections {
5091 UnfinishedSections( SectionInfo const& _info, Counts const& _prevAssertions, double _durationInSeconds )
5092 : info( _info ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds )
5093 {}
5094
5095 SectionInfo info;
5096 Counts prevAssertions;
5097 double durationInSeconds;
5098 };
5099
5100 TestRunInfo m_runInfo;
5101 IMutableContext& m_context;
5102 TestCase const* m_activeTestCase;
5103 Option<TestCaseTracker> m_testCaseTracker;
5104 AssertionResult m_lastResult;
5105
5106 Ptr<IConfig const> m_config;
5107 Totals m_totals;
5108 Ptr<IStreamingReporter> m_reporter;
5109 std::vector<MessageInfo> m_messages;
5110 IRunner* m_prevRunner;
5111 IResultCapture* m_prevResultCapture;
5112 Ptr<IConfig const> m_prevConfig;
5113 AssertionInfo m_lastAssertionInfo;
5114 std::vector<UnfinishedSections> m_unfinishedSections;
5115 };
5116
5117 } // end namespace Catch
5118
5119 // #included from: internal/catch_version.h
5120 #define TWOBLUECUBES_CATCH_VERSION_H_INCLUDED
5121
5122 namespace Catch {
5123
5124 // Versioning information
5125 struct Version {
5126 Version( unsigned int _majorVersion,
5127 unsigned int _minorVersion,
5128 unsigned int _buildNumber,
5129 char const* const _branchName )
5130 : majorVersion( _majorVersion ),
5131 minorVersion( _minorVersion ),
5132 buildNumber( _buildNumber ),
5133 branchName( _branchName )
5134 {}
5135
5136 unsigned int const majorVersion;
5137 unsigned int const minorVersion;
5138 unsigned int const buildNumber;
5139 char const* const branchName;
5140
5141 private:
5142 void operator=( Version const& );
5143 };
5144
5145 extern Version libraryVersion;
5146 }
5147
5148 #include <fstream>
5149 #include <stdlib.h>
5150 #include <limits>
5151
5152 namespace Catch {
5153
5154 class Runner {
5155
5156 public:
5157 Runner( Ptr<Config> const& config )
5158 : m_config( config )
5159 {
5160 openStream();
5161 makeReporter();
5162 }
5163
5164 Totals runTests() {
5165
5166 std::vector<TestCaseFilters> filterGroups = m_config->filters();
5167 if( filterGroups.empty() ) {
5168 TestCaseFilters filterGroup( "" );
5169 filterGroups.push_back( filterGroup );
5170 }
5171
5172 RunContext context( m_config.get(), m_reporter );
5173
5174 Totals totals;
5175
5176 for( std::size_t i=0; i < filterGroups.size() && !context.aborting(); ++i ) {
5177 context.testGroupStarting( filterGroups[i].getName(), i, filterGroups.size() );
5178 totals += runTestsForGroup( context, filterGroups[i] );
5179 context.testGroupEnded( filterGroups[i].getName(), totals, i, filterGroups.size() );
5180 }
5181 return totals;
5182 }
5183 Totals runTestsForGroup( RunContext& context, TestCaseFilters const& filterGroup ) {
5184 Totals totals;
5185
5186 std::vector<TestCase> testCases;
5187 getRegistryHub().getTestCaseRegistry().getFilteredTests( filterGroup, *m_config, testCases );
5188
5189 int testsRunForGroup = 0;
5190 for( std::vector<TestCase>::const_iterator it = testCases.begin(), itEnd = testCases.end();
5191 it != itEnd;
5192 ++it ) {
5193 testsRunForGroup++;
5194 if( m_testsAlreadyRun.find( *it ) == m_testsAlreadyRun.end() ) {
5195
5196 if( context.aborting() )
5197 break;
5198
5199 totals += context.runTest( *it );
5200 m_testsAlreadyRun.insert( *it );
5201 }
5202 }
5203 if( testsRunForGroup == 0 && !filterGroup.getName().empty() )
5204 m_reporter->noMatchingTestCases( filterGroup.getName() );
5205 return totals;
5206 }
5207
5208 private:
5209 void openStream() {
5210 // Open output file, if specified
5211 if( !m_config->getFilename().empty() ) {
5212 m_ofs.open( m_config->getFilename().c_str() );
5213 if( m_ofs.fail() ) {
5214 std::ostringstream oss;
5215 oss << "Unable to open file: '" << m_config->getFilename() << "'";
5216 throw std::domain_error( oss.str() );
5217 }
5218 m_config->setStreamBuf( m_ofs.rdbuf() );
5219 }
5220 }
5221 void makeReporter() {
5222 std::string reporterName = m_config->getReporterName().empty()
5223 ? "console"
5224 : m_config->getReporterName();
5225
5226 m_reporter = getRegistryHub().getReporterRegistry().create( reporterName, m_config.get() );
5227 if( !m_reporter ) {
5228 std::ostringstream oss;
5229 oss << "No reporter registered with name: '" << reporterName << "'";
5230 throw std::domain_error( oss.str() );
5231 }
5232 }
5233
5234 private:
5235 Ptr<Config> m_config;
5236 std::ofstream m_ofs;
5237 Ptr<IStreamingReporter> m_reporter;
5238 std::set<TestCase> m_testsAlreadyRun;
5239 };
5240
5241 class Session {
5242 static bool alreadyInstantiated;
5243
5244 public:
5245
5246 struct OnUnusedOptions { enum DoWhat { Ignore, Fail }; };
5247
5248 Session()
5249 : m_cli( makeCommandLineParser() ) {
5250 if( alreadyInstantiated ) {
5251 std::string msg = "Only one instance of Catch::Session can ever be used";
5252 std::cerr << msg << std::endl;
5253 throw std::logic_error( msg );
5254 }
5255 alreadyInstantiated = true;
5256 }
5257 ~Session() {
5258 Catch::cleanUp();
5259 }
5260
5261 void showHelp( std::string const& processName ) {
5262 std::cout << "\nCatch v" << libraryVersion.majorVersion << "."
5263 << libraryVersion.minorVersion << " build "
5264 << libraryVersion.buildNumber;
5265 if( libraryVersion.branchName != std::string( "master" ) )
5266 std::cout << " (" << libraryVersion.branchName << " branch)";
5267 std::cout << "\n";
5268
5269 m_cli.usage( std::cout, processName );
5270 std::cout << "For more detail usage please see the project docs\n" << std::endl;
5271 }
5272
5273 int applyCommandLine( int argc, char* const argv[], OnUnusedOptions::DoWhat unusedOptionBehaviour = OnUnusedOptions::Fail ) {
5274 try {
5275 m_cli.setThrowOnUnrecognisedTokens( unusedOptionBehaviour == OnUnusedOptions::Fail );
5276 m_unusedTokens = m_cli.parseInto( argc, argv, m_configData );
5277 if( m_configData.showHelp )
5278 showHelp( m_configData.processName );
5279 m_config.reset();
5280 }
5281 catch( std::exception& ex ) {
5282 {
5283 Colour colourGuard( Colour::Red );
5284 std::cerr << "\nError(s) in input:\n"
5285 << Text( ex.what(), TextAttributes().setIndent(2) )
5286 << "\n\n";
5287 }
5288 m_cli.usage( std::cout, m_configData.processName );
5289 return (std::numeric_limits<int>::max)();
5290 }
5291 return 0;
5292 }
5293
5294 void useConfigData( ConfigData const& _configData ) {
5295 m_configData = _configData;
5296 m_config.reset();
5297 }
5298
5299 int run( int argc, char* const argv[] ) {
5300
5301 int returnCode = applyCommandLine( argc, argv );
5302 if( returnCode == 0 )
5303 returnCode = run();
5304 return returnCode;
5305 }
5306
5307 int run() {
5308 if( m_configData.showHelp )
5309 return 0;
5310
5311 try
5312 {
5313 config(); // Force config to be constructed
5314 Runner runner( m_config );
5315
5316 // Handle list request
5317 if( Option<std::size_t> listed = list( config() ) )
5318 return static_cast<int>( *listed );
5319
5320 return static_cast<int>( runner.runTests().assertions.failed );
5321 }
5322 catch( std::exception& ex ) {
5323 std::cerr << ex.what() << std::endl;
5324 return (std::numeric_limits<int>::max)();
5325 }
5326 }
5327
5328 Clara::CommandLine<ConfigData> const& cli() const {
5329 return m_cli;
5330 }
5331 std::vector<Clara::Parser::Token> const& unusedTokens() const {
5332 return m_unusedTokens;
5333 }
5334 ConfigData& configData() {
5335 return m_configData;
5336 }
5337 Config& config() {
5338 if( !m_config )
5339 m_config = new Config( m_configData );
5340 return *m_config;
5341 }
5342
5343 private:
5344 Clara::CommandLine<ConfigData> m_cli;
5345 std::vector<Clara::Parser::Token> m_unusedTokens;
5346 ConfigData m_configData;
5347 Ptr<Config> m_config;
5348 };
5349
5350 bool Session::alreadyInstantiated = false;
5351
5352 } // end namespace Catch
5353
5354 // #included from: catch_registry_hub.hpp
5355 #define TWOBLUECUBES_CATCH_REGISTRY_HUB_HPP_INCLUDED
5356
5357 // #included from: catch_test_case_registry_impl.hpp
5358 #define TWOBLUECUBES_CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED
5359
5360 #include <vector>
5361 #include <set>
5362 #include <sstream>
5363 #include <iostream>
5364
5365 namespace Catch {
5366
5367 class TestRegistry : public ITestCaseRegistry {
5368 public:
5369 TestRegistry() : m_unnamedCount( 0 ) {}
5370 virtual ~TestRegistry();
5371
5372 virtual void registerTest( TestCase const& testCase ) {
5373 std::string name = testCase.getTestCaseInfo().name;
5374 if( name == "" ) {
5375 std::ostringstream oss;
5376 oss << "Anonymous test case " << ++m_unnamedCount;
5377 return registerTest( testCase.withName( oss.str() ) );
5378 }
5379
5380 if( m_functions.find( testCase ) == m_functions.end() ) {
5381 m_functions.insert( testCase );
5382 m_functionsInOrder.push_back( testCase );
5383 if( !testCase.isHidden() )
5384 m_nonHiddenFunctions.push_back( testCase );
5385 }
5386 else {
5387 TestCase const& prev = *m_functions.find( testCase );
5388 {
5389 Colour colourGuard( Colour::Red );
5390 std::cerr << "error: TEST_CASE( \"" << name << "\" ) already defined.\n"
5391 << "\tFirst seen at " << prev.getTestCaseInfo().lineInfo << "\n"
5392 << "\tRedefined at " << testCase.getTestCaseInfo().lineInfo << std::endl;
5393 }
5394 exit(1);
5395 }
5396 }
5397
5398 virtual std::vector<TestCase> const& getAllTests() const {
5399 return m_functionsInOrder;
5400 }
5401
5402 virtual std::vector<TestCase> const& getAllNonHiddenTests() const {
5403 return m_nonHiddenFunctions;
5404 }
5405
5406 virtual void getFilteredTests( TestCaseFilters const& filters, IConfig const& config, std::vector<TestCase>& matchingTestCases ) const {
5407 for( std::vector<TestCase>::const_iterator it = m_functionsInOrder.begin(),
5408 itEnd = m_functionsInOrder.end();
5409 it != itEnd;
5410 ++it ) {
5411 if( filters.shouldInclude( *it ) && ( config.allowThrows() || !it->throws() ) )
5412 matchingTestCases.push_back( *it );
5413 }
5414 }
5415 virtual void getFilteredTests( IConfig const& config, std::vector<TestCase>& matchingTestCases ) const {
5416 if( config.filters().empty() )
5417 return getFilteredTests( TestCaseFilters( "empty" ), config, matchingTestCases );
5418
5419 for( std::vector<TestCaseFilters>::const_iterator it = config.filters().begin(),
5420 itEnd = config.filters().end();
5421 it != itEnd;
5422 ++it )
5423 getFilteredTests( *it, config, matchingTestCases );
5424 }
5425
5426 private:
5427
5428 std::set<TestCase> m_functions;
5429 std::vector<TestCase> m_functionsInOrder;
5430 std::vector<TestCase> m_nonHiddenFunctions;
5431 size_t m_unnamedCount;
5432 };
5433
5434 ///////////////////////////////////////////////////////////////////////////
5435
5436 class FreeFunctionTestCase : public SharedImpl<ITestCase> {
5437 public:
5438
5439 FreeFunctionTestCase( TestFunction fun ) : m_fun( fun ) {}
5440
5441 virtual void invoke() const {
5442 m_fun();
5443 }
5444
5445 private:
5446 virtual ~FreeFunctionTestCase();
5447
5448 TestFunction m_fun;
5449 };
5450
5451 inline std::string extractClassName( std::string const& classOrQualifiedMethodName ) {
5452 std::string className = classOrQualifiedMethodName;
5453 if( startsWith( className, "&" ) )
5454 {
5455 std::size_t lastColons = className.rfind( "::" );
5456 std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
5457 if( penultimateColons == std::string::npos )
5458 penultimateColons = 1;
5459 className = className.substr( penultimateColons, lastColons-penultimateColons );
5460 }
5461 return className;
5462 }
5463
5464 ///////////////////////////////////////////////////////////////////////////
5465
5466 AutoReg::AutoReg( TestFunction function,
5467 SourceLineInfo const& lineInfo,
5468 NameAndDesc const& nameAndDesc ) {
5469 registerTestCase( new FreeFunctionTestCase( function ), "", nameAndDesc, lineInfo );
5470 }
5471
5472 AutoReg::~AutoReg() {}
5473
5474 void AutoReg::registerTestCase( ITestCase* testCase,
5475 char const* classOrQualifiedMethodName,
5476 NameAndDesc const& nameAndDesc,
5477 SourceLineInfo const& lineInfo ) {
5478
5479 getMutableRegistryHub().registerTest
5480 ( makeTestCase( testCase,
5481 extractClassName( classOrQualifiedMethodName ),
5482 nameAndDesc.name,
5483 nameAndDesc.description,
5484 lineInfo ) );
5485 }
5486
5487 } // end namespace Catch
5488
5489 // #included from: catch_reporter_registry.hpp
5490 #define TWOBLUECUBES_CATCH_REPORTER_REGISTRY_HPP_INCLUDED
5491
5492 #include <map>
5493
5494 namespace Catch {
5495
5496 class ReporterRegistry : public IReporterRegistry {
5497
5498 public:
5499
5500 virtual ~ReporterRegistry() {
5501 deleteAllValues( m_factories );
5502 }
5503
5504 virtual IStreamingReporter* create( std::string const& name, Ptr<IConfig> const& config ) const {
5505 FactoryMap::const_iterator it = m_factories.find( name );
5506 if( it == m_factories.end() )
5507 return NULL;
5508 return it->second->create( ReporterConfig( config ) );
5509 }
5510
5511 void registerReporter( std::string const& name, IReporterFactory* factory ) {
5512 m_factories.insert( std::make_pair( name, factory ) );
5513 }
5514
5515 FactoryMap const& getFactories() const {
5516 return m_factories;
5517 }
5518
5519 private:
5520 FactoryMap m_factories;
5521 };
5522 }
5523
5524 // #included from: catch_exception_translator_registry.hpp
5525 #define TWOBLUECUBES_CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED
5526
5527 #ifdef __OBJC__
5528 #import "Foundation/Foundation.h"
5529 #endif
5530
5531 namespace Catch {
5532
5533 class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
5534 public:
5535 ~ExceptionTranslatorRegistry() {
5536 deleteAll( m_translators );
5537 }
5538
5539 virtual void registerTranslator( const IExceptionTranslator* translator ) {
5540 m_translators.push_back( translator );
5541 }
5542
5543 virtual std::string translateActiveException() const {
5544 try {
5545 #ifdef __OBJC__
5546 // In Objective-C try objective-c exceptions first
5547 @try {
5548 throw;
5549 }
5550 @catch (NSException *exception) {
5551 return toString( [exception description] );
5552 }
5553 #else
5554 throw;
5555 #endif
5556 }
5557 catch( std::exception& ex ) {
5558 return ex.what();
5559 }
5560 catch( std::string& msg ) {
5561 return msg;
5562 }
5563 catch( const char* msg ) {
5564 return msg;
5565 }
5566 catch(...) {
5567 return tryTranslators( m_translators.begin() );
5568 }
5569 }
5570
5571 std::string tryTranslators( std::vector<const IExceptionTranslator*>::const_iterator it ) const {
5572 if( it == m_translators.end() )
5573 return "Unknown exception";
5574
5575 try {
5576 return (*it)->translate();
5577 }
5578 catch(...) {
5579 return tryTranslators( it+1 );
5580 }
5581 }
5582
5583 private:
5584 std::vector<const IExceptionTranslator*> m_translators;
5585 };
5586 }
5587
5588 namespace Catch {
5589
5590 namespace {
5591
5592 class RegistryHub : public IRegistryHub, public IMutableRegistryHub {
5593
5594 RegistryHub( RegistryHub const& );
5595 void operator=( RegistryHub const& );
5596
5597 public: // IRegistryHub
5598 RegistryHub() {
5599 }
5600 virtual IReporterRegistry const& getReporterRegistry() const {
5601 return m_reporterRegistry;
5602 }
5603 virtual ITestCaseRegistry const& getTestCaseRegistry() const {
5604 return m_testCaseRegistry;
5605 }
5606 virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() {
5607 return m_exceptionTranslatorRegistry;
5608 }
5609
5610 public: // IMutableRegistryHub
5611 virtual void registerReporter( std::string const& name, IReporterFactory* factory ) {
5612 m_reporterRegistry.registerReporter( name, factory );
5613 }
5614 virtual void registerTest( TestCase const& testInfo ) {
5615 m_testCaseRegistry.registerTest( testInfo );
5616 }
5617 virtual void registerTranslator( const IExceptionTranslator* translator ) {
5618 m_exceptionTranslatorRegistry.registerTranslator( translator );
5619 }
5620
5621 private:
5622 TestRegistry m_testCaseRegistry;
5623 ReporterRegistry m_reporterRegistry;
5624 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
5625 };
5626
5627 // Single, global, instance
5628 inline RegistryHub*& getTheRegistryHub() {
5629 static RegistryHub* theRegistryHub = NULL;
5630 if( !theRegistryHub )
5631 theRegistryHub = new RegistryHub();
5632 return theRegistryHub;
5633 }
5634 }
5635
5636 IRegistryHub& getRegistryHub() {
5637 return *getTheRegistryHub();
5638 }
5639 IMutableRegistryHub& getMutableRegistryHub() {
5640 return *getTheRegistryHub();
5641 }
5642 void cleanUp() {
5643 delete getTheRegistryHub();
5644 getTheRegistryHub() = NULL;
5645 cleanUpContext();
5646 }
5647 std::string translateActiveException() {
5648 return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
5649 }
5650
5651 } // end namespace Catch
5652
5653 // #included from: catch_notimplemented_exception.hpp
5654 #define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_HPP_INCLUDED
5655
5656 #include <ostream>
5657
5658 namespace Catch {
5659
5660 NotImplementedException::NotImplementedException( SourceLineInfo const& lineInfo )
5661 : m_lineInfo( lineInfo ) {
5662 std::ostringstream oss;
5663 oss << lineInfo << ": function ";
5664 oss << "not implemented";
5665 m_what = oss.str();
5666 }
5667
5668 const char* NotImplementedException::what() const CATCH_NOEXCEPT {
5669 return m_what.c_str();
5670 }
5671
5672 } // end namespace Catch
5673
5674 // #included from: catch_context_impl.hpp
5675 #define TWOBLUECUBES_CATCH_CONTEXT_IMPL_HPP_INCLUDED
5676
5677 // #included from: catch_stream.hpp
5678 #define TWOBLUECUBES_CATCH_STREAM_HPP_INCLUDED
5679
5680 // #included from: catch_streambuf.h
5681 #define TWOBLUECUBES_CATCH_STREAMBUF_H_INCLUDED
5682
5683 #include <streambuf>
5684
5685 namespace Catch {
5686
5687 class StreamBufBase : public std::streambuf {
5688 public:
5689 virtual ~StreamBufBase() CATCH_NOEXCEPT;
5690 };
5691 }
5692
5693 #include <stdexcept>
5694 #include <cstdio>
5695
5696 namespace Catch {
5697
5698 template<typename WriterF, size_t bufferSize=256>
5699 class StreamBufImpl : public StreamBufBase {
5700 char data[bufferSize];
5701 WriterF m_writer;
5702
5703 public:
5704 StreamBufImpl() {
5705 setp( data, data + sizeof(data) );
5706 }
5707
5708 ~StreamBufImpl() CATCH_NOEXCEPT {
5709 sync();
5710 }
5711
5712 private:
5713 int overflow( int c ) {
5714 sync();
5715
5716 if( c != EOF ) {
5717 if( pbase() == epptr() )
5718 m_writer( std::string( 1, static_cast<char>( c ) ) );
5719 else
5720 sputc( static_cast<char>( c ) );
5721 }
5722 return 0;
5723 }
5724
5725 int sync() {
5726 if( pbase() != pptr() ) {
5727 m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
5728 setp( pbase(), epptr() );
5729 }
5730 return 0;
5731 }
5732 };
5733
5734 ///////////////////////////////////////////////////////////////////////////
5735
5736 struct OutputDebugWriter {
5737
5738 void operator()( std::string const&str ) {
5739 writeToDebugConsole( str );
5740 }
5741 };
5742
5743 Stream::Stream()
5744 : streamBuf( NULL ), isOwned( false )
5745 {}
5746
5747 Stream::Stream( std::streambuf* _streamBuf, bool _isOwned )
5748 : streamBuf( _streamBuf ), isOwned( _isOwned )
5749 {}
5750
5751 void Stream::release() {
5752 if( isOwned ) {
5753 delete streamBuf;
5754 streamBuf = NULL;
5755 isOwned = false;
5756 }
5757 }
5758 }
5759
5760 namespace Catch {
5761
5762 class Context : public IMutableContext {
5763
5764 Context() : m_config( NULL ), m_runner( NULL ), m_resultCapture( NULL ) {}
5765 Context( Context const& );
5766 void operator=( Context const& );
5767
5768 public: // IContext
5769 virtual IResultCapture& getResultCapture() {
5770 return *m_resultCapture;
5771 }
5772 virtual IRunner& getRunner() {
5773 return *m_runner;
5774 }
5775 virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) {
5776 return getGeneratorsForCurrentTest()
5777 .getGeneratorInfo( fileInfo, totalSize )
5778 .getCurrentIndex();
5779 }
5780 virtual bool advanceGeneratorsForCurrentTest() {
5781 IGeneratorsForTest* generators = findGeneratorsForCurrentTest();
5782 return generators && generators->moveNext();
5783 }
5784
5785 virtual Ptr<IConfig const> getConfig() const {
5786 return m_config;
5787 }
5788
5789 public: // IMutableContext
5790 virtual void setResultCapture( IResultCapture* resultCapture ) {
5791 m_resultCapture = resultCapture;
5792 }
5793 virtual void setRunner( IRunner* runner ) {
5794 m_runner = runner;
5795 }
5796 virtual void setConfig( Ptr<IConfig const> const& config ) {
5797 m_config = config;
5798 }
5799
5800 friend IMutableContext& getCurrentMutableContext();
5801
5802 private:
5803 IGeneratorsForTest* findGeneratorsForCurrentTest() {
5804 std::string testName = getResultCapture().getCurrentTestName();
5805
5806 std::map<std::string, IGeneratorsForTest*>::const_iterator it =
5807 m_generatorsByTestName.find( testName );
5808 return it != m_generatorsByTestName.end()
5809 ? it->second
5810 : NULL;
5811 }
5812
5813 IGeneratorsForTest& getGeneratorsForCurrentTest() {
5814 IGeneratorsForTest* generators = findGeneratorsForCurrentTest();
5815 if( !generators ) {
5816 std::string testName = getResultCapture().getCurrentTestName();
5817 generators = createGeneratorsForTest();
5818 m_generatorsByTestName.insert( std::make_pair( testName, generators ) );
5819 }
5820 return *generators;
5821 }
5822
5823 private:
5824 Ptr<IConfig const> m_config;
5825 IRunner* m_runner;
5826 IResultCapture* m_resultCapture;
5827 std::map<std::string, IGeneratorsForTest*> m_generatorsByTestName;
5828 };
5829
5830 namespace {
5831 Context* currentContext = NULL;
5832 }
5833 IMutableContext& getCurrentMutableContext() {
5834 if( !currentContext )
5835 currentContext = new Context();
5836 return *currentContext;
5837 }
5838 IContext& getCurrentContext() {
5839 return getCurrentMutableContext();
5840 }
5841
5842 Stream createStream( std::string const& streamName ) {
5843 if( streamName == "stdout" ) return Stream( std::cout.rdbuf(), false );
5844 if( streamName == "stderr" ) return Stream( std::cerr.rdbuf(), false );
5845 if( streamName == "debug" ) return Stream( new StreamBufImpl<OutputDebugWriter>, true );
5846
5847 throw std::domain_error( "Unknown stream: " + streamName );
5848 }
5849
5850 void cleanUpContext() {
5851 delete currentContext;
5852 currentContext = NULL;
5853 }
5854 }
5855
5856 // #included from: catch_console_colour_impl.hpp
5857 #define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_IMPL_HPP_INCLUDED
5858
5859 namespace Catch { namespace Detail {
5860 struct IColourImpl {
5861 virtual ~IColourImpl() {}
5862 virtual void use( Colour::Code _colourCode ) = 0;
5863 };
5864 }}
5865
5866 #if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
5867
5868 #ifndef NOMINMAX
5869 #define NOMINMAX
5870 #endif
5871
5872 #ifdef __AFXDLL
5873 #include <AfxWin.h>
5874 #else
5875 #include <windows.h>
5876 #endif
5877
5878 namespace Catch {
5879 namespace {
5880
5881 class Win32ColourImpl : public Detail::IColourImpl {
5882 public:
5883 Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
5884 {
5885 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
5886 GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
5887 originalAttributes = csbiInfo.wAttributes;
5888 }
5889
5890 virtual void use( Colour::Code _colourCode ) {
5891 switch( _colourCode ) {
5892 case Colour::None: return setTextAttribute( originalAttributes );
5893 case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
5894 case Colour::Red: return setTextAttribute( FOREGROUND_RED );
5895 case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
5896 case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
5897 case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
5898 case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
5899 case Colour::Grey: return setTextAttribute( 0 );
5900
5901 case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
5902 case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
5903 case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
5904 case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
5905
5906 case Colour::Bright: throw std::logic_error( "not a colour" );
5907 }
5908 }
5909
5910 private:
5911 void setTextAttribute( WORD _textAttribute ) {
5912 SetConsoleTextAttribute( stdoutHandle, _textAttribute );
5913 }
5914 HANDLE stdoutHandle;
5915 WORD originalAttributes;
5916 };
5917
5918 inline bool shouldUseColourForPlatform() {
5919 return true;
5920 }
5921
5922 static Detail::IColourImpl* platformColourInstance() {
5923 static Win32ColourImpl s_instance;
5924 return &s_instance;
5925 }
5926
5927 } // end anon namespace
5928 } // end namespace Catch
5929
5930 #else // Not Windows - assumed to be POSIX compatible //////////////////////////
5931
5932 #include <unistd.h>
5933
5934 namespace Catch {
5935 namespace {
5936
5937 // use POSIX/ ANSI console terminal codes
5938 // Thanks to Adam Strzelecki for original contribution
5939 // (http://github.com/nanoant)
5940 // https://github.com/philsquared/Catch/pull/131
5941 class PosixColourImpl : public Detail::IColourImpl {
5942 public:
5943 virtual void use( Colour::Code _colourCode ) {
5944 switch( _colourCode ) {
5945 case Colour::None:
5946 case Colour::White: return setColour( "[0m" );
5947 case Colour::Red: return setColour( "[0;31m" );
5948 case Colour::Green: return setColour( "[0;32m" );
5949 case Colour::Blue: return setColour( "[0:34m" );
5950 case Colour::Cyan: return setColour( "[0;36m" );
5951 case Colour::Yellow: return setColour( "[0;33m" );
5952 case Colour::Grey: return setColour( "[1;30m" );
5953
5954 case Colour::LightGrey: return setColour( "[0;37m" );
5955 case Colour::BrightRed: return setColour( "[1;31m" );
5956 case Colour::BrightGreen: return setColour( "[1;32m" );
5957 case Colour::BrightWhite: return setColour( "[1;37m" );
5958
5959 case Colour::Bright: throw std::logic_error( "not a colour" );
5960 }
5961 }
5962 private:
5963 void setColour( const char* _escapeCode ) {
5964 std::cout << '\033' << _escapeCode;
5965 }
5966 };
5967
5968 inline bool shouldUseColourForPlatform() {
5969 return isatty(STDOUT_FILENO);
5970 }
5971
5972 static Detail::IColourImpl* platformColourInstance() {
5973 static PosixColourImpl s_instance;
5974 return &s_instance;
5975 }
5976
5977 } // end anon namespace
5978 } // end namespace Catch
5979
5980 #endif // not Windows
5981
5982 namespace Catch {
5983
5984 namespace {
5985 struct NoColourImpl : Detail::IColourImpl {
5986 void use( Colour::Code ) {}
5987
5988 static IColourImpl* instance() {
5989 static NoColourImpl s_instance;
5990 return &s_instance;
5991 }
5992 };
5993 static bool shouldUseColour() {
5994 return shouldUseColourForPlatform() && !isDebuggerActive();
5995 }
5996 }
5997
5998 Colour::Colour( Code _colourCode ){ use( _colourCode ); }
5999 Colour::~Colour(){ use( None ); }
6000 void Colour::use( Code _colourCode ) {
6001 impl()->use( _colourCode );
6002 }
6003
6004 Detail::IColourImpl* Colour::impl() {
6005 return shouldUseColour()
6006 ? platformColourInstance()
6007 : NoColourImpl::instance();
6008 }
6009
6010 } // end namespace Catch
6011
6012 // #included from: catch_generators_impl.hpp
6013 #define TWOBLUECUBES_CATCH_GENERATORS_IMPL_HPP_INCLUDED
6014
6015 #include <vector>
6016 #include <string>
6017 #include <map>
6018
6019 namespace Catch {
6020
6021 struct GeneratorInfo : IGeneratorInfo {
6022
6023 GeneratorInfo( std::size_t size )
6024 : m_size( size ),
6025 m_currentIndex( 0 )
6026 {}
6027
6028 bool moveNext() {
6029 if( ++m_currentIndex == m_size ) {
6030 m_currentIndex = 0;
6031 return false;
6032 }
6033 return true;
6034 }
6035
6036 std::size_t getCurrentIndex() const {
6037 return m_currentIndex;
6038 }
6039
6040 std::size_t m_size;
6041 std::size_t m_currentIndex;
6042 };
6043
6044 ///////////////////////////////////////////////////////////////////////////
6045
6046 class GeneratorsForTest : public IGeneratorsForTest {
6047
6048 public:
6049 ~GeneratorsForTest() {
6050 deleteAll( m_generatorsInOrder );
6051 }
6052
6053 IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) {
6054 std::map<std::string, IGeneratorInfo*>::const_iterator it = m_generatorsByName.find( fileInfo );
6055 if( it == m_generatorsByName.end() ) {
6056 IGeneratorInfo* info = new GeneratorInfo( size );
6057 m_generatorsByName.insert( std::make_pair( fileInfo, info ) );
6058 m_generatorsInOrder.push_back( info );
6059 return *info;
6060 }
6061 return *it->second;
6062 }
6063
6064 bool moveNext() {
6065 std::vector<IGeneratorInfo*>::const_iterator it = m_generatorsInOrder.begin();
6066 std::vector<IGeneratorInfo*>::const_iterator itEnd = m_generatorsInOrder.end();
6067 for(; it != itEnd; ++it ) {
6068 if( (*it)->moveNext() )
6069 return true;
6070 }
6071 return false;
6072 }
6073
6074 private:
6075 std::map<std::string, IGeneratorInfo*> m_generatorsByName;
6076 std::vector<IGeneratorInfo*> m_generatorsInOrder;
6077 };
6078
6079 IGeneratorsForTest* createGeneratorsForTest()
6080 {
6081 return new GeneratorsForTest();
6082 }
6083
6084 } // end namespace Catch
6085
6086 // #included from: catch_assertionresult.hpp
6087 #define TWOBLUECUBES_CATCH_ASSERTIONRESULT_HPP_INCLUDED
6088
6089 namespace Catch {
6090
6091 AssertionInfo::AssertionInfo( std::string const& _macroName,
6092 SourceLineInfo const& _lineInfo,
6093 std::string const& _capturedExpression,
6094 ResultDisposition::Flags _resultDisposition )
6095 : macroName( _macroName ),
6096 lineInfo( _lineInfo ),
6097 capturedExpression( _capturedExpression ),
6098 resultDisposition( _resultDisposition )
6099 {}
6100
6101 AssertionResult::AssertionResult() {}
6102
6103 AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
6104 : m_info( info ),
6105 m_resultData( data )
6106 {}
6107
6108 AssertionResult::~AssertionResult() {}
6109
6110 // Result was a success
6111 bool AssertionResult::succeeded() const {
6112 return Catch::isOk( m_resultData.resultType );
6113 }
6114
6115 // Result was a success, or failure is suppressed
6116 bool AssertionResult::isOk() const {
6117 return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
6118 }
6119
6120 ResultWas::OfType AssertionResult::getResultType() const {
6121 return m_resultData.resultType;
6122 }
6123
6124 bool AssertionResult::hasExpression() const {
6125 return !m_info.capturedExpression.empty();
6126 }
6127
6128 bool AssertionResult::hasMessage() const {
6129 return !m_resultData.message.empty();
6130 }
6131
6132 std::string AssertionResult::getExpression() const {
6133 if( shouldNegate( m_info.resultDisposition ) )
6134 return "!" + m_info.capturedExpression;
6135 else
6136 return m_info.capturedExpression;
6137 }
6138 std::string AssertionResult::getExpressionInMacro() const {
6139 if( m_info.macroName.empty() )
6140 return m_info.capturedExpression;
6141 else
6142 return m_info.macroName + "( " + m_info.capturedExpression + " )";
6143 }
6144
6145 bool AssertionResult::hasExpandedExpression() const {
6146 return hasExpression() && getExpandedExpression() != getExpression();
6147 }
6148
6149 std::string AssertionResult::getExpandedExpression() const {
6150 return m_resultData.reconstructedExpression;
6151 }
6152
6153 std::string AssertionResult::getMessage() const {
6154 return m_resultData.message;
6155 }
6156 SourceLineInfo AssertionResult::getSourceInfo() const {
6157 return m_info.lineInfo;
6158 }
6159
6160 std::string AssertionResult::getTestMacroName() const {
6161 return m_info.macroName;
6162 }
6163
6164 } // end namespace Catch
6165
6166 // #included from: catch_expressionresult_builder.hpp
6167 #define TWOBLUECUBES_CATCH_EXPRESSIONRESULT_BUILDER_HPP_INCLUDED
6168
6169 #include <assert.h>
6170
6171 namespace Catch {
6172
6173 ExpressionResultBuilder::ExpressionResultBuilder( ResultWas::OfType resultType ) {
6174 m_data.resultType = resultType;
6175 }
6176 ExpressionResultBuilder::ExpressionResultBuilder( ExpressionResultBuilder const& other )
6177 : m_data( other.m_data ),
6178 m_exprComponents( other.m_exprComponents )
6179 {
6180 m_stream << other.m_stream.str();
6181 }
6182 ExpressionResultBuilder& ExpressionResultBuilder::operator=(ExpressionResultBuilder const& other ) {
6183 m_data = other.m_data;
6184 m_exprComponents = other.m_exprComponents;
6185 m_stream.str("");
6186 m_stream << other.m_stream.str();
6187 return *this;
6188 }
6189 ExpressionResultBuilder& ExpressionResultBuilder::setResultType( ResultWas::OfType result ) {
6190 m_data.resultType = result;
6191 return *this;
6192 }
6193 ExpressionResultBuilder& ExpressionResultBuilder::setResultType( bool result ) {
6194 m_data.resultType = result ? ResultWas::Ok : ResultWas::ExpressionFailed;
6195 return *this;
6196 }
6197 ExpressionResultBuilder& ExpressionResultBuilder::endExpression( ResultDisposition::Flags resultDisposition ) {
6198 m_exprComponents.shouldNegate = shouldNegate( resultDisposition );
6199 return *this;
6200 }
6201 ExpressionResultBuilder& ExpressionResultBuilder::setLhs( std::string const& lhs ) {
6202 m_exprComponents.lhs = lhs;
6203 return *this;
6204 }
6205 ExpressionResultBuilder& ExpressionResultBuilder::setRhs( std::string const& rhs ) {
6206 m_exprComponents.rhs = rhs;
6207 return *this;
6208 }
6209 ExpressionResultBuilder& ExpressionResultBuilder::setOp( std::string const& op ) {
6210 m_exprComponents.op = op;
6211 return *this;
6212 }
6213 AssertionResult ExpressionResultBuilder::buildResult( AssertionInfo const& info ) const
6214 {
6215 assert( m_data.resultType != ResultWas::Unknown );
6216
6217 AssertionResultData data = m_data;
6218
6219 // Flip bool results if shouldNegate is set
6220 if( m_exprComponents.shouldNegate && data.resultType == ResultWas::Ok )
6221 data.resultType = ResultWas::ExpressionFailed;
6222 else if( m_exprComponents.shouldNegate && data.resultType == ResultWas::ExpressionFailed )
6223 data.resultType = ResultWas::Ok;
6224
6225 data.message = m_stream.str();
6226 data.reconstructedExpression = reconstructExpression( info );
6227 if( m_exprComponents.shouldNegate ) {
6228 if( m_exprComponents.op == "" )
6229 data.reconstructedExpression = "!" + data.reconstructedExpression;
6230 else
6231 data.reconstructedExpression = "!(" + data.reconstructedExpression + ")";
6232 }
6233 return AssertionResult( info, data );
6234 }
6235 std::string ExpressionResultBuilder::reconstructExpression( AssertionInfo const& info ) const {
6236 if( m_exprComponents.op == "" )
6237 return m_exprComponents.lhs.empty() ? info.capturedExpression : m_exprComponents.op + m_exprComponents.lhs;
6238 else if( m_exprComponents.op == "matches" )
6239 return m_exprComponents.lhs + " " + m_exprComponents.rhs;
6240 else if( m_exprComponents.op != "!" ) {
6241 if( m_exprComponents.lhs.size() + m_exprComponents.rhs.size() < 40 &&
6242 m_exprComponents.lhs.find("\n") == std::string::npos &&
6243 m_exprComponents.rhs.find("\n") == std::string::npos )
6244 return m_exprComponents.lhs + " " + m_exprComponents.op + " " + m_exprComponents.rhs;
6245 else
6246 return m_exprComponents.lhs + "\n" + m_exprComponents.op + "\n" + m_exprComponents.rhs;
6247 }
6248 else
6249 return "{can't expand - use " + info.macroName + "_FALSE( " + info.capturedExpression.substr(1) + " ) instead of " + info.macroName + "( " + info.capturedExpression + " ) for better diagnostics}";
6250 }
6251
6252 } // end namespace Catch
6253
6254 // #included from: catch_test_case_info.hpp
6255 #define TWOBLUECUBES_CATCH_TEST_CASE_INFO_HPP_INCLUDED
6256
6257 namespace Catch {
6258
6259 inline bool isSpecialTag( std::string const& tag ) {
6260 return tag == "." ||
6261 tag == "hide" ||
6262 tag == "!hide" ||
6263 tag == "!throws";
6264 }
6265 inline bool isReservedTag( std::string const& tag ) {
6266 return !isSpecialTag( tag ) && tag.size() > 0 && !isalnum( tag[0] );
6267 }
6268
6269 TestCase makeTestCase( ITestCase* _testCase,
6270 std::string const& _className,
6271 std::string const& _name,
6272 std::string const& _descOrTags,
6273 SourceLineInfo const& _lineInfo )
6274 {
6275 std::string desc = _descOrTags;
6276 bool isHidden( startsWith( _name, "./" ) ); // Legacy support
6277 std::set<std::string> tags;
6278 TagExtracter( tags ).parse( desc );
6279 for( std::set<std::string>::const_iterator it = tags.begin(), itEnd = tags.end();
6280 it != itEnd;
6281 ++it )
6282 if( isReservedTag( *it ) ) {
6283 {
6284 Colour colourGuard( Colour::Red );
6285 std::cerr
6286 << "Tag name [" << *it << "] not allowed.\n"
6287 << "Tag names starting with non alpha-numeric characters are reserved\n";
6288 }
6289 {
6290 Colour colourGuard( Colour::FileName );
6291 std::cerr << _lineInfo << std::endl;
6292 }
6293 exit(1);
6294 }
6295
6296 if( tags.find( "hide" ) != tags.end() || tags.find( "." ) != tags.end() )
6297 isHidden = true;
6298
6299 if( isHidden ) {
6300 tags.insert( "hide" );
6301 tags.insert( "." );
6302 }
6303 TestCaseInfo info( _name, _className, desc, tags, isHidden, _lineInfo );
6304 return TestCase( _testCase, info );
6305 }
6306
6307 TestCaseInfo::TestCaseInfo( std::string const& _name,
6308 std::string const& _className,
6309 std::string const& _description,
6310 std::set<std::string> const& _tags,
6311 bool _isHidden,
6312 SourceLineInfo const& _lineInfo )
6313 : name( _name ),
6314 className( _className ),
6315 description( _description ),
6316 tags( _tags ),
6317 lineInfo( _lineInfo ),
6318 isHidden( _isHidden ),
6319 throws( false )
6320 {
6321 std::ostringstream oss;
6322 for( std::set<std::string>::const_iterator it = _tags.begin(), itEnd = _tags.end(); it != itEnd; ++it ) {
6323 oss << "[" << *it << "]";
6324 if( *it == "!throws" )
6325 throws = true;
6326 }
6327 tagsAsString = oss.str();
6328 }
6329
6330 TestCaseInfo::TestCaseInfo( TestCaseInfo const& other )
6331 : name( other.name ),
6332 className( other.className ),
6333 description( other.description ),
6334 tags( other.tags ),
6335 tagsAsString( other.tagsAsString ),
6336 lineInfo( other.lineInfo ),
6337 isHidden( other.isHidden ),
6338 throws( other.throws )
6339 {}
6340
6341 TestCase::TestCase( ITestCase* testCase, TestCaseInfo const& info ) : TestCaseInfo( info ), test( testCase ) {}
6342
6343 TestCase::TestCase( TestCase const& other )
6344 : TestCaseInfo( other ),
6345 test( other.test )
6346 {}
6347
6348 TestCase TestCase::withName( std::string const& _newName ) const {
6349 TestCase other( *this );
6350 other.name = _newName;
6351 return other;
6352 }
6353
6354 void TestCase::invoke() const {
6355 test->invoke();
6356 }
6357
6358 bool TestCase::isHidden() const {
6359 return TestCaseInfo::isHidden;
6360 }
6361 bool TestCase::throws() const {
6362 return TestCaseInfo::throws;
6363 }
6364
6365 bool TestCase::hasTag( std::string const& tag ) const {
6366 return tags.find( toLower( tag ) ) != tags.end();
6367 }
6368 bool TestCase::matchesTags( std::string const& tagPattern ) const {
6369 TagExpression exp;
6370 TagExpressionParser( exp ).parse( tagPattern );
6371 return exp.matches( tags );
6372 }
6373 std::set<std::string> const& TestCase::getTags() const {
6374 return tags;
6375 }
6376
6377 void TestCase::swap( TestCase& other ) {
6378 test.swap( other.test );
6379 className.swap( other.className );
6380 name.swap( other.name );
6381 description.swap( other.description );
6382 std::swap( lineInfo, other.lineInfo );
6383 }
6384
6385 bool TestCase::operator == ( TestCase const& other ) const {
6386 return test.get() == other.test.get() &&
6387 name == other.name &&
6388 className == other.className;
6389 }
6390
6391 bool TestCase::operator < ( TestCase const& other ) const {
6392 return name < other.name;
6393 }
6394 TestCase& TestCase::operator = ( TestCase const& other ) {
6395 TestCase temp( other );
6396 swap( temp );
6397 return *this;
6398 }
6399
6400 TestCaseInfo const& TestCase::getTestCaseInfo() const
6401 {
6402 return *this;
6403 }
6404
6405 } // end namespace Catch
6406
6407 // #included from: catch_tags.hpp
6408 #define TWOBLUECUBES_CATCH_TAGS_HPP_INCLUDED
6409
6410 namespace Catch {
6411 TagParser::~TagParser() {}
6412
6413 void TagParser::parse( std::string const& str ) {
6414 std::size_t pos = 0;
6415 while( pos < str.size() ) {
6416 char c = str[pos];
6417 if( c == '[' ) {
6418 std::size_t end = str.find_first_of( ']', pos );
6419 if( end != std::string::npos ) {
6420 acceptTag( str.substr( pos+1, end-pos-1 ) );
6421 pos = end+1;
6422 }
6423 else {
6424 acceptChar( c );
6425 pos++;
6426 }
6427 }
6428 else {
6429 acceptChar( c );
6430 pos++;
6431 }
6432 }
6433 endParse();
6434 }
6435
6436 TagExtracter::TagExtracter( std::set<std::string>& tags )
6437 : m_tags( tags )
6438 {}
6439
6440 TagExtracter::~TagExtracter() {}
6441
6442 void TagExtracter::parse( std::string& description ) {
6443 TagParser::parse( description );
6444 description = m_remainder;
6445 }
6446
6447 void TagExtracter::acceptTag( std::string const& tag ) {
6448 m_tags.insert( toLower( tag ) );
6449 }
6450 void TagExtracter::acceptChar( char c ) {
6451 m_remainder += c;
6452 }
6453
6454 Tag::Tag() : m_isNegated( false ) {}
6455 Tag::Tag( std::string const& name, bool isNegated )
6456 : m_name( name ),
6457 m_isNegated( isNegated )
6458 {}
6459
6460 std::string Tag::getName() const {
6461 return m_name;
6462 }
6463 bool Tag::isNegated() const {
6464 return m_isNegated;
6465 }
6466
6467 bool Tag::operator ! () const {
6468 return m_name.empty();
6469 }
6470
6471 void TagSet::add( Tag const& tag ) {
6472 m_tags.insert( std::make_pair( toLower( tag.getName() ), tag ) );
6473 }
6474
6475 bool TagSet::empty() const {
6476 return m_tags.empty();
6477 }
6478
6479 bool TagSet::matches( std::set<std::string> const& tags ) const {
6480 for( TagMap::const_iterator
6481 it = m_tags.begin(), itEnd = m_tags.end();
6482 it != itEnd;
6483 ++it ) {
6484 bool found = tags.find( it->first ) != tags.end();
6485 if( found == it->second.isNegated() )
6486 return false;
6487 }
6488 return true;
6489 }
6490
6491 bool TagExpression::matches( std::set<std::string> const& tags ) const {
6492 for( std::vector<TagSet>::const_iterator
6493 it = m_tagSets.begin(), itEnd = m_tagSets.end();
6494 it != itEnd;
6495 ++it )
6496 if( it->matches( tags ) )
6497 return true;
6498 return false;
6499 }
6500
6501 TagExpressionParser::TagExpressionParser( TagExpression& exp )
6502 : m_isNegated( false ),
6503 m_exp( exp )
6504 {}
6505
6506 TagExpressionParser::~TagExpressionParser() {}
6507
6508 void TagExpressionParser::acceptTag( std::string const& tag ) {
6509 m_currentTagSet.add( Tag( tag, m_isNegated ) );
6510 m_isNegated = false;
6511 }
6512
6513 void TagExpressionParser::acceptChar( char c ) {
6514 switch( c ) {
6515 case '~':
6516 m_isNegated = true;
6517 break;
6518 case ',':
6519 m_exp.m_tagSets.push_back( m_currentTagSet );
6520 m_currentTagSet = TagSet();
6521 break;
6522 }
6523 }
6524
6525 void TagExpressionParser::endParse() {
6526 if( !m_currentTagSet.empty() )
6527 m_exp.m_tagSets.push_back( m_currentTagSet );
6528 }
6529
6530 } // end namespace Catch
6531
6532 // #included from: catch_test_spec.hpp
6533 #define TWOBLUECUBES_CATCH_TEST_SPEC_HPP_INCLUDED
6534
6535 namespace Catch {
6536
6537 TestCaseFilter::TestCaseFilter( std::string const& testSpec, IfFilterMatches::DoWhat matchBehaviour )
6538 : m_stringToMatch( toLower( testSpec ) ),
6539 m_filterType( matchBehaviour ),
6540 m_wildcardPosition( NoWildcard )
6541 {
6542 if( m_filterType == IfFilterMatches::AutoDetectBehaviour ) {
6543 if( startsWith( m_stringToMatch, "exclude:" ) ) {
6544 m_stringToMatch = m_stringToMatch.substr( 8 );
6545 m_filterType = IfFilterMatches::ExcludeTests;
6546 }
6547 else if( startsWith( m_stringToMatch, "~" ) ) {
6548 m_stringToMatch = m_stringToMatch.substr( 1 );
6549 m_filterType = IfFilterMatches::ExcludeTests;
6550 }
6551 else {
6552 m_filterType = IfFilterMatches::IncludeTests;
6553 }
6554 }
6555
6556 if( startsWith( m_stringToMatch, "*" ) ) {
6557 m_stringToMatch = m_stringToMatch.substr( 1 );
6558 m_wildcardPosition = (WildcardPosition)( m_wildcardPosition | WildcardAtStart );
6559 }
6560 if( endsWith( m_stringToMatch, "*" ) ) {
6561 m_stringToMatch = m_stringToMatch.substr( 0, m_stringToMatch.size()-1 );
6562 m_wildcardPosition = (WildcardPosition)( m_wildcardPosition | WildcardAtEnd );
6563 }
6564 }
6565
6566 IfFilterMatches::DoWhat TestCaseFilter::getFilterType() const {
6567 return m_filterType;
6568 }
6569
6570 bool TestCaseFilter::shouldInclude( TestCase const& testCase ) const {
6571 return isMatch( testCase ) == (m_filterType == IfFilterMatches::IncludeTests);
6572 }
6573
6574 #ifdef __clang__
6575 #pragma clang diagnostic push
6576 #pragma clang diagnostic ignored "-Wunreachable-code"
6577 #endif
6578
6579 bool TestCaseFilter::isMatch( TestCase const& testCase ) const {
6580 std::string name = testCase.getTestCaseInfo().name;
6581 toLowerInPlace( name );
6582
6583 switch( m_wildcardPosition ) {
6584 case NoWildcard:
6585 return m_stringToMatch == name;
6586 case WildcardAtStart:
6587 return endsWith( name, m_stringToMatch );
6588 case WildcardAtEnd:
6589 return startsWith( name, m_stringToMatch );
6590 case WildcardAtBothEnds:
6591 return contains( name, m_stringToMatch );
6592 }
6593 throw std::logic_error( "Unhandled wildcard type" );
6594 }
6595
6596 #ifdef __clang__
6597 #pragma clang diagnostic pop
6598 #endif
6599
6600 TestCaseFilters::TestCaseFilters( std::string const& name ) : m_name( name ) {}
6601
6602 std::string TestCaseFilters::getName() const {
6603 return m_name;
6604 }
6605
6606 void TestCaseFilters::addFilter( TestCaseFilter const& filter ) {
6607 if( filter.getFilterType() == IfFilterMatches::ExcludeTests )
6608 m_exclusionFilters.push_back( filter );
6609 else
6610 m_inclusionFilters.push_back( filter );
6611 }
6612
6613 void TestCaseFilters::addTags( std::string const& tagPattern ) {
6614 TagExpression exp;
6615 TagExpressionParser( exp ).parse( tagPattern );
6616
6617 m_tagExpressions.push_back( exp );
6618 }
6619
6620 bool TestCaseFilters::shouldInclude( TestCase const& testCase ) const {
6621 if( !m_tagExpressions.empty() ) {
6622 std::vector<TagExpression>::const_iterator it = m_tagExpressions.begin();
6623 std::vector<TagExpression>::const_iterator itEnd = m_tagExpressions.end();
6624 for(; it != itEnd; ++it )
6625 if( it->matches( testCase.getTags() ) )
6626 break;
6627 if( it == itEnd )
6628 return false;
6629 }
6630
6631 if( !m_inclusionFilters.empty() ) {
6632 std::vector<TestCaseFilter>::const_iterator it = m_inclusionFilters.begin();
6633 std::vector<TestCaseFilter>::const_iterator itEnd = m_inclusionFilters.end();
6634 for(; it != itEnd; ++it )
6635 if( it->shouldInclude( testCase ) )
6636 break;
6637 if( it == itEnd )
6638 return false;
6639 }
6640 else if( m_exclusionFilters.empty() && m_tagExpressions.empty() ) {
6641 return !testCase.isHidden();
6642 }
6643
6644 std::vector<TestCaseFilter>::const_iterator it = m_exclusionFilters.begin();
6645 std::vector<TestCaseFilter>::const_iterator itEnd = m_exclusionFilters.end();
6646 for(; it != itEnd; ++it )
6647 if( !it->shouldInclude( testCase ) )
6648 return false;
6649 return true;
6650 }
6651 }
6652
6653 // #included from: catch_version.hpp
6654 #define TWOBLUECUBES_CATCH_VERSION_HPP_INCLUDED
6655
6656 namespace Catch {
6657
6658 // These numbers are maintained by a script
6659 Version libraryVersion( 1, 0, 43, "master" );
6660 }
6661
6662 // #included from: catch_message.hpp
6663 #define TWOBLUECUBES_CATCH_MESSAGE_HPP_INCLUDED
6664
6665 namespace Catch {
6666
6667 MessageInfo::MessageInfo( std::string const& _macroName,
6668 SourceLineInfo const& _lineInfo,
6669 ResultWas::OfType _type )
6670 : macroName( _macroName ),
6671 lineInfo( _lineInfo ),
6672 type( _type ),
6673 sequence( ++globalCount )
6674 {}
6675
6676 // This may need protecting if threading support is added
6677 unsigned int MessageInfo::globalCount = 0;
6678
6679 ////////////////////////////////////////////////////////////////////////////
6680
6681 ScopedMessage::ScopedMessage( MessageBuilder const& builder )
6682 : m_info( builder.m_info )
6683 {
6684 m_info.message = builder.m_stream.str();
6685 getResultCapture().pushScopedMessage( m_info );
6686 }
6687 ScopedMessage::~ScopedMessage() {
6688 getResultCapture().popScopedMessage( m_info );
6689 }
6690
6691 } // end namespace Catch
6692
6693 // #included from: catch_legacy_reporter_adapter.hpp
6694 #define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_HPP_INCLUDED
6695
6696 // #included from: catch_legacy_reporter_adapter.h
6697 #define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_H_INCLUDED
6698
6699 namespace Catch
6700 {
6701 // Deprecated
6702 struct IReporter : IShared {
6703 virtual ~IReporter();
6704
6705 virtual bool shouldRedirectStdout() const = 0;
6706
6707 virtual void StartTesting() = 0;
6708 virtual void EndTesting( Totals const& totals ) = 0;
6709 virtual void StartGroup( std::string const& groupName ) = 0;
6710 virtual void EndGroup( std::string const& groupName, Totals const& totals ) = 0;
6711 virtual void StartTestCase( TestCaseInfo const& testInfo ) = 0;
6712 virtual void EndTestCase( TestCaseInfo const& testInfo, Totals const& totals, std::string const& stdOut, std::string const& stdErr ) = 0;
6713 virtual void StartSection( std::string const& sectionName, std::string const& description ) = 0;
6714 virtual void EndSection( std::string const& sectionName, Counts const& assertions ) = 0;
6715 virtual void NoAssertionsInSection( std::string const& sectionName ) = 0;
6716 virtual void NoAssertionsInTestCase( std::string const& testName ) = 0;
6717 virtual void Aborted() = 0;
6718 virtual void Result( AssertionResult const& result ) = 0;
6719 };
6720
6721 class LegacyReporterAdapter : public SharedImpl<IStreamingReporter>
6722 {
6723 public:
6724 LegacyReporterAdapter( Ptr<IReporter> const& legacyReporter );
6725 virtual ~LegacyReporterAdapter();
6726
6727 virtual ReporterPreferences getPreferences() const;
6728 virtual void noMatchingTestCases( std::string const& );
6729 virtual void testRunStarting( TestRunInfo const& );
6730 virtual void testGroupStarting( GroupInfo const& groupInfo );
6731 virtual void testCaseStarting( TestCaseInfo const& testInfo );
6732 virtual void sectionStarting( SectionInfo const& sectionInfo );
6733 virtual void assertionStarting( AssertionInfo const& );
6734 virtual bool assertionEnded( AssertionStats const& assertionStats );
6735 virtual void sectionEnded( SectionStats const& sectionStats );
6736 virtual void testCaseEnded( TestCaseStats const& testCaseStats );
6737 virtual void testGroupEnded( TestGroupStats const& testGroupStats );
6738 virtual void testRunEnded( TestRunStats const& testRunStats );
6739
6740 private:
6741 Ptr<IReporter> m_legacyReporter;
6742 };
6743 }
6744
6745 namespace Catch
6746 {
6747 LegacyReporterAdapter::LegacyReporterAdapter( Ptr<IReporter> const& legacyReporter )
6748 : m_legacyReporter( legacyReporter )
6749 {}
6750 LegacyReporterAdapter::~LegacyReporterAdapter() {}
6751
6752 ReporterPreferences LegacyReporterAdapter::getPreferences() const {
6753 ReporterPreferences prefs;
6754 prefs.shouldRedirectStdOut = m_legacyReporter->shouldRedirectStdout();
6755 return prefs;
6756 }
6757
6758 void LegacyReporterAdapter::noMatchingTestCases( std::string const& ) {}
6759 void LegacyReporterAdapter::testRunStarting( TestRunInfo const& ) {
6760 m_legacyReporter->StartTesting();
6761 }
6762 void LegacyReporterAdapter::testGroupStarting( GroupInfo const& groupInfo ) {
6763 m_legacyReporter->StartGroup( groupInfo.name );
6764 }
6765 void LegacyReporterAdapter::testCaseStarting( TestCaseInfo const& testInfo ) {
6766 m_legacyReporter->StartTestCase( testInfo );
6767 }
6768 void LegacyReporterAdapter::sectionStarting( SectionInfo const& sectionInfo ) {
6769 m_legacyReporter->StartSection( sectionInfo.name, sectionInfo.description );
6770 }
6771 void LegacyReporterAdapter::assertionStarting( AssertionInfo const& ) {
6772 // Not on legacy interface
6773 }
6774
6775 bool LegacyReporterAdapter::assertionEnded( AssertionStats const& assertionStats ) {
6776 if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) {
6777 for( std::vector<MessageInfo>::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end();
6778 it != itEnd;
6779 ++it ) {
6780 if( it->type == ResultWas::Info ) {
6781 ExpressionResultBuilder expressionBuilder( it->type );
6782 expressionBuilder << it->message;
6783 AssertionInfo info( it->macroName, it->lineInfo, "", ResultDisposition::Normal );
6784 AssertionResult result = expressionBuilder.buildResult( info );
6785 m_legacyReporter->Result( result );
6786 }
6787 }
6788 }
6789 m_legacyReporter->Result( assertionStats.assertionResult );
6790 return true;
6791 }
6792 void LegacyReporterAdapter::sectionEnded( SectionStats const& sectionStats ) {
6793 if( sectionStats.missingAssertions )
6794 m_legacyReporter->NoAssertionsInSection( sectionStats.sectionInfo.name );
6795 m_legacyReporter->EndSection( sectionStats.sectionInfo.name, sectionStats.assertions );
6796 }
6797 void LegacyReporterAdapter::testCaseEnded( TestCaseStats const& testCaseStats ) {
6798 m_legacyReporter->EndTestCase
6799 ( testCaseStats.testInfo,
6800 testCaseStats.totals,
6801 testCaseStats.stdOut,
6802 testCaseStats.stdErr );
6803 }
6804 void LegacyReporterAdapter::testGroupEnded( TestGroupStats const& testGroupStats ) {
6805 if( testGroupStats.aborting )
6806 m_legacyReporter->Aborted();
6807 m_legacyReporter->EndGroup( testGroupStats.groupInfo.name, testGroupStats.totals );
6808 }
6809 void LegacyReporterAdapter::testRunEnded( TestRunStats const& testRunStats ) {
6810 m_legacyReporter->EndTesting( testRunStats.totals );
6811 }
6812 }
6813
6814 // #included from: catch_timer.hpp
6815
6816 #ifdef __clang__
6817 #pragma clang diagnostic push
6818 #pragma clang diagnostic ignored "-Wc++11-long-long"
6819 #endif
6820
6821 #ifdef CATCH_PLATFORM_WINDOWS
6822 #include <windows.h>
6823 #else
6824 #include <sys/time.h>
6825 #endif
6826
6827 namespace Catch {
6828
6829 namespace {
6830 #ifdef CATCH_PLATFORM_WINDOWS
6831 uint64_t getCurrentTicks() {
6832 static uint64_t hz=0, hzo=0;
6833 if (!hz) {
6834 QueryPerformanceFrequency((LARGE_INTEGER*)&hz);
6835 QueryPerformanceCounter((LARGE_INTEGER*)&hzo);
6836 }
6837 uint64_t t;
6838 QueryPerformanceCounter((LARGE_INTEGER*)&t);
6839 return ((t-hzo)*1000000)/hz;
6840 }
6841 #else
6842 uint64_t getCurrentTicks() {
6843 timeval t;
6844 gettimeofday(&t,NULL);
6845 return (uint64_t)t.tv_sec * 1000000ull + (uint64_t)t.tv_usec;
6846 }
6847 #endif
6848 }
6849
6850 void Timer::start() {
6851 m_ticks = getCurrentTicks();
6852 }
6853 unsigned int Timer::getElapsedNanoseconds() const {
6854 return (unsigned int)(getCurrentTicks() - m_ticks);
6855 }
6856 unsigned int Timer::getElapsedMilliseconds() const {
6857 return (unsigned int)((getCurrentTicks() - m_ticks)/1000);
6858 }
6859 double Timer::getElapsedSeconds() const {
6860 return (getCurrentTicks() - m_ticks)/1000000.0;
6861 }
6862
6863 } // namespace Catch
6864
6865 #ifdef __clang__
6866 #pragma clang diagnostic pop
6867 #endif
6868 // #included from: catch_common.hpp
6869 #define TWOBLUECUBES_CATCH_COMMON_HPP_INCLUDED
6870
6871 namespace Catch {
6872
6873 bool startsWith( std::string const& s, std::string const& prefix ) {
6874 return s.size() >= prefix.size() && s.substr( 0, prefix.size() ) == prefix;
6875 }
6876 bool endsWith( std::string const& s, std::string const& suffix ) {
6877 return s.size() >= suffix.size() && s.substr( s.size()-suffix.size(), suffix.size() ) == suffix;
6878 }
6879 bool contains( std::string const& s, std::string const& infix ) {
6880 return s.find( infix ) != std::string::npos;
6881 }
6882 void toLowerInPlace( std::string& s ) {
6883 std::transform( s.begin(), s.end(), s.begin(), ::tolower );
6884 }
6885 std::string toLower( std::string const& s ) {
6886 std::string lc = s;
6887 toLowerInPlace( lc );
6888 return lc;
6889 }
6890 std::string trim( std::string const& str ) {
6891 static char const* whitespaceChars = "\n\r\t ";
6892 std::string::size_type start = str.find_first_not_of( whitespaceChars );
6893 std::string::size_type end = str.find_last_not_of( whitespaceChars );
6894
6895 return start != std::string::npos ? str.substr( start, 1+end-start ) : "";
6896 }
6897
6898 pluralise::pluralise( std::size_t count, std::string const& label )
6899 : m_count( count ),
6900 m_label( label )
6901 {}
6902
6903 std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
6904 os << pluraliser.m_count << " " << pluraliser.m_label;
6905 if( pluraliser.m_count != 1 )
6906 os << "s";
6907 return os;
6908 }
6909
6910 SourceLineInfo::SourceLineInfo() : line( 0 ){}
6911 SourceLineInfo::SourceLineInfo( char const* _file, std::size_t _line )
6912 : file( _file ),
6913 line( _line )
6914 {}
6915 SourceLineInfo::SourceLineInfo( SourceLineInfo const& other )
6916 : file( other.file ),
6917 line( other.line )
6918 {}
6919 bool SourceLineInfo::empty() const {
6920 return file.empty();
6921 }
6922 bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const {
6923 return line == other.line && file == other.file;
6924 }
6925
6926 std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
6927 #ifndef __GNUG__
6928 os << info.file << "(" << info.line << ")";
6929 #else
6930 os << info.file << ":" << info.line;
6931 #endif
6932 return os;
6933 }
6934
6935 void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ) {
6936 std::ostringstream oss;
6937 oss << locationInfo << ": Internal Catch error: '" << message << "'";
6938 if( isTrue( true ))
6939 throw std::logic_error( oss.str() );
6940 }
6941 }
6942
6943 // #included from: catch_section.hpp
6944 #define TWOBLUECUBES_CATCH_SECTION_HPP_INCLUDED
6945
6946 namespace Catch {
6947
6948 Section::Section( SourceLineInfo const& lineInfo,
6949 std::string const& name,
6950 std::string const& description )
6951 : m_info( name, description, lineInfo ),
6952 m_sectionIncluded( getCurrentContext().getResultCapture().sectionStarted( m_info, m_assertions ) )
6953 {
6954 m_timer.start();
6955 }
6956
6957 Section::~Section() {
6958 if( m_sectionIncluded )
6959 getCurrentContext().getResultCapture().sectionEnded( m_info, m_assertions, m_timer.getElapsedSeconds() );
6960 }
6961
6962 // This indicates whether the section should be executed or not
6963 Section::operator bool() {
6964 return m_sectionIncluded;
6965 }
6966
6967 } // end namespace Catch
6968
6969 // #included from: catch_debugger.hpp
6970 #define TWOBLUECUBES_CATCH_DEBUGGER_HPP_INCLUDED
6971
6972 #include <iostream>
6973
6974 #ifdef CATCH_PLATFORM_MAC
6975
6976 #include <assert.h>
6977 #include <stdbool.h>
6978 #include <sys/types.h>
6979 #include <unistd.h>
6980 #include <sys/sysctl.h>
6981
6982 namespace Catch{
6983
6984 // The following function is taken directly from the following technical note:
6985 // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
6986
6987 // Returns true if the current process is being debugged (either
6988 // running under the debugger or has a debugger attached post facto).
6989 bool isDebuggerActive(){
6990
6991 int mib[4];
6992 struct kinfo_proc info;
6993 size_t size;
6994
6995 // Initialize the flags so that, if sysctl fails for some bizarre
6996 // reason, we get a predictable result.
6997
6998 info.kp_proc.p_flag = 0;
6999
7000 // Initialize mib, which tells sysctl the info we want, in this case
7001 // we're looking for information about a specific process ID.
7002
7003 mib[0] = CTL_KERN;
7004 mib[1] = KERN_PROC;
7005 mib[2] = KERN_PROC_PID;
7006 mib[3] = getpid();
7007
7008 // Call sysctl.
7009
7010 size = sizeof(info);
7011 if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0) != 0 ) {
7012 std::cerr << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
7013 return false;
7014 }
7015
7016 // We're being debugged if the P_TRACED flag is set.
7017
7018 return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
7019 }
7020 } // namespace Catch
7021
7022 #elif defined(_MSC_VER)
7023 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
7024 namespace Catch {
7025 bool isDebuggerActive() {
7026 return IsDebuggerPresent() != 0;
7027 }
7028 }
7029 #elif defined(__MINGW32__)
7030 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
7031 namespace Catch {
7032 bool isDebuggerActive() {
7033 return IsDebuggerPresent() != 0;
7034 }
7035 }
7036 #else
7037 namespace Catch {
7038 inline bool isDebuggerActive() { return false; }
7039 }
7040 #endif // Platform
7041
7042 #ifdef CATCH_PLATFORM_WINDOWS
7043 extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA( const char* );
7044 namespace Catch {
7045 void writeToDebugConsole( std::string const& text ) {
7046 ::OutputDebugStringA( text.c_str() );
7047 }
7048 }
7049 #else
7050 namespace Catch {
7051 void writeToDebugConsole( std::string const& text ) {
7052 // !TBD: Need a version for Mac/ XCode and other IDEs
7053 std::cout << text;
7054 }
7055 }
7056 #endif // Platform
7057
7058 // #included from: catch_tostring.hpp
7059 #define TWOBLUECUBES_CATCH_TOSTRING_HPP_INCLUDED
7060
7061 namespace Catch {
7062
7063 std::string toString( std::string const& value ) {
7064 std::string s = value;
7065 if( getCurrentContext().getConfig()->showInvisibles() ) {
7066 for(size_t i = 0; i < s.size(); ++i ) {
7067 std::string subs;
7068 switch( s[i] ) {
7069 case '\n': subs = "\\n"; break;
7070 case '\t': subs = "\\t"; break;
7071 default: break;
7072 }
7073 if( !subs.empty() ) {
7074 s = s.substr( 0, i ) + subs + s.substr( i+1 );
7075 ++i;
7076 }
7077 }
7078 }
7079 return "\"" + s + "\"";
7080 }
7081 std::string toString( std::wstring const& value ) {
7082
7083 std::string s;
7084 s.reserve( value.size() );
7085 for(size_t i = 0; i < value.size(); ++i )
7086 s += value[i] <= 0xff ? static_cast<char>( value[i] ) : '?';
7087 return toString( s );
7088 }
7089
7090 std::string toString( const char* const value ) {
7091 return value ? Catch::toString( std::string( value ) ) : std::string( "{null string}" );
7092 }
7093
7094 std::string toString( char* const value ) {
7095 return Catch::toString( static_cast<const char*>( value ) );
7096 }
7097
7098 std::string toString( int value ) {
7099 std::ostringstream oss;
7100 oss << value;
7101 return oss.str();
7102 }
7103
7104 std::string toString( unsigned long value ) {
7105 std::ostringstream oss;
7106 if( value > 8192 )
7107 oss << "0x" << std::hex << value;
7108 else
7109 oss << value;
7110 return oss.str();
7111 }
7112
7113 std::string toString( unsigned int value ) {
7114 return toString( static_cast<unsigned long>( value ) );
7115 }
7116
7117 std::string toString( const double value ) {
7118 std::ostringstream oss;
7119 oss << std::setprecision( 10 )
7120 << std::fixed
7121 << value;
7122 std::string d = oss.str();
7123 std::size_t i = d.find_last_not_of( '0' );
7124 if( i != std::string::npos && i != d.size()-1 ) {
7125 if( d[i] == '.' )
7126 i++;
7127 d = d.substr( 0, i+1 );
7128 }
7129 return d;
7130 }
7131
7132 std::string toString( bool value ) {
7133 return value ? "true" : "false";
7134 }
7135
7136 std::string toString( char value ) {
7137 return value < ' '
7138 ? toString( static_cast<unsigned int>( value ) )
7139 : Detail::makeString( value );
7140 }
7141
7142 std::string toString( signed char value ) {
7143 return toString( static_cast<char>( value ) );
7144 }
7145
7146 std::string toString( unsigned char value ) {
7147 return toString( static_cast<char>( value ) );
7148 }
7149
7150 #ifdef CATCH_CONFIG_CPP11_NULLPTR
7151 std::string toString( std::nullptr_t ) {
7152 return "nullptr";
7153 }
7154 #endif
7155
7156 #ifdef __OBJC__
7157 std::string toString( NSString const * const& nsstring ) {
7158 if( !nsstring )
7159 return "nil";
7160 return std::string( "@\"" ) + [nsstring UTF8String] + "\"";
7161 }
7162 std::string toString( NSString * CATCH_ARC_STRONG const& nsstring ) {
7163 if( !nsstring )
7164 return "nil";
7165 return std::string( "@\"" ) + [nsstring UTF8String] + "\"";
7166 }
7167 std::string toString( NSObject* const& nsObject ) {
7168 return toString( [nsObject description] );
7169 }
7170 #endif
7171
7172 } // end namespace Catch
7173
7174 // #included from: ../reporters/catch_reporter_xml.hpp
7175 #define TWOBLUECUBES_CATCH_REPORTER_XML_HPP_INCLUDED
7176
7177 // #included from: catch_reporter_bases.hpp
7178 #define TWOBLUECUBES_CATCH_REPORTER_BASES_HPP_INCLUDED
7179
7180 namespace Catch {
7181
7182 struct StreamingReporterBase : SharedImpl<IStreamingReporter> {
7183
7184 StreamingReporterBase( ReporterConfig const& _config )
7185 : m_config( _config.fullConfig() ),
7186 stream( _config.stream() )
7187 {}
7188
7189 virtual ~StreamingReporterBase();
7190
7191 virtual void noMatchingTestCases( std::string const& ) {}
7192
7193 virtual void testRunStarting( TestRunInfo const& _testRunInfo ) {
7194 currentTestRunInfo = _testRunInfo;
7195 }
7196 virtual void testGroupStarting( GroupInfo const& _groupInfo ) {
7197 currentGroupInfo = _groupInfo;
7198 }
7199
7200 virtual void testCaseStarting( TestCaseInfo const& _testInfo ) {
7201 currentTestCaseInfo = _testInfo;
7202 }
7203 virtual void sectionStarting( SectionInfo const& _sectionInfo ) {
7204 m_sectionStack.push_back( _sectionInfo );
7205 }
7206
7207 virtual void sectionEnded( SectionStats const& /* _sectionStats */ ) {
7208 m_sectionStack.pop_back();
7209 }
7210 virtual void testCaseEnded( TestCaseStats const& /* _testCaseStats */ ) {
7211 currentTestCaseInfo.reset();
7212 assert( m_sectionStack.empty() );
7213 }
7214 virtual void testGroupEnded( TestGroupStats const& /* _testGroupStats */ ) {
7215 currentGroupInfo.reset();
7216 }
7217 virtual void testRunEnded( TestRunStats const& /* _testRunStats */ ) {
7218 currentTestCaseInfo.reset();
7219 currentGroupInfo.reset();
7220 currentTestRunInfo.reset();
7221 }
7222
7223 Ptr<IConfig> m_config;
7224 std::ostream& stream;
7225
7226 LazyStat<TestRunInfo> currentTestRunInfo;
7227 LazyStat<GroupInfo> currentGroupInfo;
7228 LazyStat<TestCaseInfo> currentTestCaseInfo;
7229
7230 std::vector<SectionInfo> m_sectionStack;
7231 };
7232
7233 struct CumulativeReporterBase : SharedImpl<IStreamingReporter> {
7234 template<typename T, typename ChildNodeT>
7235 struct Node : SharedImpl<> {
7236 explicit Node( T const& _value ) : value( _value ) {}
7237 virtual ~Node() {}
7238
7239 typedef std::vector<Ptr<ChildNodeT> > ChildNodes;
7240 T value;
7241 ChildNodes children;
7242 };
7243 struct SectionNode : SharedImpl<> {
7244 explicit SectionNode( SectionStats const& _stats ) : stats( _stats ) {}
7245 virtual ~SectionNode();
7246
7247 bool operator == ( SectionNode const& other ) const {
7248 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
7249 }
7250 bool operator == ( Ptr<SectionNode> const& other ) const {
7251 return operator==( *other );
7252 }
7253
7254 SectionStats stats;
7255 typedef std::vector<Ptr<SectionNode> > ChildSections;
7256 typedef std::vector<AssertionStats> Assertions;
7257 ChildSections childSections;
7258 Assertions assertions;
7259 std::string stdOut;
7260 std::string stdErr;
7261 };
7262
7263 struct BySectionInfo {
7264 BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
7265 bool operator() ( Ptr<SectionNode> const& node ) const {
7266 return node->stats.sectionInfo.lineInfo == m_other.lineInfo;
7267 }
7268 private:
7269 BySectionInfo& operator=( BySectionInfo const& other ); // = delete;
7270
7271 SectionInfo const& m_other;
7272 };
7273
7274 typedef Node<TestCaseStats, SectionNode> TestCaseNode;
7275 typedef Node<TestGroupStats, TestCaseNode> TestGroupNode;
7276 typedef Node<TestRunStats, TestGroupNode> TestRunNode;
7277
7278 CumulativeReporterBase( ReporterConfig const& _config )
7279 : m_config( _config.fullConfig() ),
7280 stream( _config.stream() )
7281 {}
7282 ~CumulativeReporterBase();
7283
7284 virtual void testRunStarting( TestRunInfo const& ) {}
7285 virtual void testGroupStarting( GroupInfo const& ) {}
7286
7287 virtual void testCaseStarting( TestCaseInfo const& ) {}
7288
7289 virtual void sectionStarting( SectionInfo const& sectionInfo ) {
7290 SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
7291 Ptr<SectionNode> node;
7292 if( m_sectionStack.empty() ) {
7293 if( !m_rootSection )
7294 m_rootSection = new SectionNode( incompleteStats );
7295 node = m_rootSection;
7296 }
7297 else {
7298 SectionNode& parentNode = *m_sectionStack.back();
7299 SectionNode::ChildSections::const_iterator it =
7300 std::find_if( parentNode.childSections.begin(),
7301 parentNode.childSections.end(),
7302 BySectionInfo( sectionInfo ) );
7303 if( it == parentNode.childSections.end() ) {
7304 node = new SectionNode( incompleteStats );
7305 parentNode.childSections.push_back( node );
7306 }
7307 else
7308 node = *it;
7309 }
7310 m_sectionStack.push_back( node );
7311 m_deepestSection = node;
7312 }
7313
7314 virtual void assertionStarting( AssertionInfo const& ) {}
7315
7316 virtual bool assertionEnded( AssertionStats const& assertionStats ) {
7317 assert( !m_sectionStack.empty() );
7318 SectionNode& sectionNode = *m_sectionStack.back();
7319 sectionNode.assertions.push_back( assertionStats );
7320 return true;
7321 }
7322 virtual void sectionEnded( SectionStats const& sectionStats ) {
7323 assert( !m_sectionStack.empty() );
7324 SectionNode& node = *m_sectionStack.back();
7325 node.stats = sectionStats;
7326 m_sectionStack.pop_back();
7327 }
7328 virtual void testCaseEnded( TestCaseStats const& testCaseStats ) {
7329 Ptr<TestCaseNode> node = new TestCaseNode( testCaseStats );
7330 assert( m_sectionStack.size() == 0 );
7331 node->children.push_back( m_rootSection );
7332 m_testCases.push_back( node );
7333 m_rootSection.reset();
7334
7335 assert( m_deepestSection );
7336 m_deepestSection->stdOut = testCaseStats.stdOut;
7337 m_deepestSection->stdErr = testCaseStats.stdErr;
7338 }
7339 virtual void testGroupEnded( TestGroupStats const& testGroupStats ) {
7340 Ptr<TestGroupNode> node = new TestGroupNode( testGroupStats );
7341 node->children.swap( m_testCases );
7342 m_testGroups.push_back( node );
7343 }
7344 virtual void testRunEnded( TestRunStats const& testRunStats ) {
7345 Ptr<TestRunNode> node = new TestRunNode( testRunStats );
7346 node->children.swap( m_testGroups );
7347 m_testRuns.push_back( node );
7348 testRunEndedCumulative();
7349 }
7350 virtual void testRunEndedCumulative() = 0;
7351
7352 Ptr<IConfig> m_config;
7353 std::ostream& stream;
7354 std::vector<AssertionStats> m_assertions;
7355 std::vector<std::vector<Ptr<SectionNode> > > m_sections;
7356 std::vector<Ptr<TestCaseNode> > m_testCases;
7357 std::vector<Ptr<TestGroupNode> > m_testGroups;
7358
7359 std::vector<Ptr<TestRunNode> > m_testRuns;
7360
7361 Ptr<SectionNode> m_rootSection;
7362 Ptr<SectionNode> m_deepestSection;
7363 std::vector<Ptr<SectionNode> > m_sectionStack;
7364
7365 };
7366
7367 } // end namespace Catch
7368
7369 // #included from: ../internal/catch_reporter_registrars.hpp
7370 #define TWOBLUECUBES_CATCH_REPORTER_REGISTRARS_HPP_INCLUDED
7371
7372 namespace Catch {
7373
7374 template<typename T>
7375 class LegacyReporterRegistrar {
7376
7377 class ReporterFactory : public IReporterFactory {
7378 virtual IStreamingReporter* create( ReporterConfig const& config ) const {
7379 return new LegacyReporterAdapter( new T( config ) );
7380 }
7381
7382 virtual std::string getDescription() const {
7383 return T::getDescription();
7384 }
7385 };
7386
7387 public:
7388
7389 LegacyReporterRegistrar( std::string const& name ) {
7390 getMutableRegistryHub().registerReporter( name, new ReporterFactory() );
7391 }
7392 };
7393
7394 template<typename T>
7395 class ReporterRegistrar {
7396
7397 class ReporterFactory : public IReporterFactory {
7398
7399 // *** Please Note ***:
7400 // - If you end up here looking at a compiler error because it's trying to register
7401 // your custom reporter class be aware that the native reporter interface has changed
7402 // to IStreamingReporter. The "legacy" interface, IReporter, is still supported via
7403 // an adapter. Just use REGISTER_LEGACY_REPORTER to take advantage of the adapter.
7404 // However please consider updating to the new interface as the old one is now
7405 // deprecated and will probably be removed quite soon!
7406 // Please contact me via github if you have any questions at all about this.
7407 // In fact, ideally, please contact me anyway to let me know you've hit this - as I have
7408 // no idea who is actually using custom reporters at all (possibly no-one!).
7409 // The new interface is designed to minimise exposure to interface changes in the future.
7410 virtual IStreamingReporter* create( ReporterConfig const& config ) const {
7411 return new T( config );
7412 }
7413
7414 virtual std::string getDescription() const {
7415 return T::getDescription();
7416 }
7417 };
7418
7419 public:
7420
7421 ReporterRegistrar( std::string const& name ) {
7422 getMutableRegistryHub().registerReporter( name, new ReporterFactory() );
7423 }
7424 };
7425 }
7426
7427 #define INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) \
7428 namespace{ Catch::LegacyReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); }
7429 #define INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) \
7430 namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); }
7431
7432 // #included from: ../internal/catch_xmlwriter.hpp
7433 #define TWOBLUECUBES_CATCH_XMLWRITER_HPP_INCLUDED
7434
7435 #include <sstream>
7436 #include <iostream>
7437 #include <string>
7438 #include <vector>
7439
7440 namespace Catch {
7441
7442 class XmlWriter {
7443 public:
7444
7445 class ScopedElement {
7446 public:
7447 ScopedElement( XmlWriter* writer )
7448 : m_writer( writer )
7449 {}
7450
7451 ScopedElement( ScopedElement const& other )
7452 : m_writer( other.m_writer ){
7453 other.m_writer = NULL;
7454 }
7455
7456 ~ScopedElement() {
7457 if( m_writer )
7458 m_writer->endElement();
7459 }
7460
7461 ScopedElement& writeText( std::string const& text, bool indent = true ) {
7462 m_writer->writeText( text, indent );
7463 return *this;
7464 }
7465
7466 template<typename T>
7467 ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
7468 m_writer->writeAttribute( name, attribute );
7469 return *this;
7470 }
7471
7472 private:
7473 mutable XmlWriter* m_writer;
7474 };
7475
7476 XmlWriter()
7477 : m_tagIsOpen( false ),
7478 m_needsNewline( false ),
7479 m_os( &std::cout )
7480 {}
7481
7482 XmlWriter( std::ostream& os )
7483 : m_tagIsOpen( false ),
7484 m_needsNewline( false ),
7485 m_os( &os )
7486 {}
7487
7488 ~XmlWriter() {
7489 while( !m_tags.empty() )
7490 endElement();
7491 }
7492
7493 # ifndef CATCH_CPP11_OR_GREATER
7494 XmlWriter& operator = ( XmlWriter const& other ) {
7495 XmlWriter temp( other );
7496 swap( temp );
7497 return *this;
7498 }
7499 # else
7500 XmlWriter( XmlWriter const& ) = default;
7501 XmlWriter( XmlWriter && ) = default;
7502 XmlWriter& operator = ( XmlWriter const& ) = default;
7503 XmlWriter& operator = ( XmlWriter && ) = default;
7504 # endif
7505
7506 void swap( XmlWriter& other ) {
7507 std::swap( m_tagIsOpen, other.m_tagIsOpen );
7508 std::swap( m_needsNewline, other.m_needsNewline );
7509 std::swap( m_tags, other.m_tags );
7510 std::swap( m_indent, other.m_indent );
7511 std::swap( m_os, other.m_os );
7512 }
7513
7514 XmlWriter& startElement( std::string const& name ) {
7515 ensureTagClosed();
7516 newlineIfNecessary();
7517 stream() << m_indent << "<" << name;
7518 m_tags.push_back( name );
7519 m_indent += " ";
7520 m_tagIsOpen = true;
7521 return *this;
7522 }
7523
7524 ScopedElement scopedElement( std::string const& name ) {
7525 ScopedElement scoped( this );
7526 startElement( name );
7527 return scoped;
7528 }
7529
7530 XmlWriter& endElement() {
7531 newlineIfNecessary();
7532 m_indent = m_indent.substr( 0, m_indent.size()-2 );
7533 if( m_tagIsOpen ) {
7534 stream() << "/>\n";
7535 m_tagIsOpen = false;
7536 }
7537 else {
7538 stream() << m_indent << "</" << m_tags.back() << ">\n";
7539 }
7540 m_tags.pop_back();
7541 return *this;
7542 }
7543
7544 XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ) {
7545 if( !name.empty() && !attribute.empty() ) {
7546 stream() << " " << name << "=\"";
7547 writeEncodedText( attribute );
7548 stream() << "\"";
7549 }
7550 return *this;
7551 }
7552
7553 XmlWriter& writeAttribute( std::string const& name, bool attribute ) {
7554 stream() << " " << name << "=\"" << ( attribute ? "true" : "false" ) << "\"";
7555 return *this;
7556 }
7557
7558 template<typename T>
7559 XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
7560 if( !name.empty() )
7561 stream() << " " << name << "=\"" << attribute << "\"";
7562 return *this;
7563 }
7564
7565 XmlWriter& writeText( std::string const& text, bool indent = true ) {
7566 if( !text.empty() ){
7567 bool tagWasOpen = m_tagIsOpen;
7568 ensureTagClosed();
7569 if( tagWasOpen && indent )
7570 stream() << m_indent;
7571 writeEncodedText( text );
7572 m_needsNewline = true;
7573 }
7574 return *this;
7575 }
7576
7577 XmlWriter& writeComment( std::string const& text ) {
7578 ensureTagClosed();
7579 stream() << m_indent << "<!--" << text << "-->";
7580 m_needsNewline = true;
7581 return *this;
7582 }
7583
7584 XmlWriter& writeBlankLine() {
7585 ensureTagClosed();
7586 stream() << "\n";
7587 return *this;
7588 }
7589
7590 private:
7591
7592 std::ostream& stream() {
7593 return *m_os;
7594 }
7595
7596 void ensureTagClosed() {
7597 if( m_tagIsOpen ) {
7598 stream() << ">\n";
7599 m_tagIsOpen = false;
7600 }
7601 }
7602
7603 void newlineIfNecessary() {
7604 if( m_needsNewline ) {
7605 stream() << "\n";
7606 m_needsNewline = false;
7607 }
7608 }
7609
7610 void writeEncodedText( std::string const& text ) {
7611 static const char* charsToEncode = "<&\"";
7612 std::string mtext = text;
7613 std::string::size_type pos = mtext.find_first_of( charsToEncode );
7614 while( pos != std::string::npos ) {
7615 stream() << mtext.substr( 0, pos );
7616
7617 switch( mtext[pos] ) {
7618 case '<':
7619 stream() << "&lt;";
7620 break;
7621 case '&':
7622 stream() << "&amp;";
7623 break;
7624 case '\"':
7625 stream() << "&quot;";
7626 break;
7627 }
7628 mtext = mtext.substr( pos+1 );
7629 pos = mtext.find_first_of( charsToEncode );
7630 }
7631 stream() << mtext;
7632 }
7633
7634 bool m_tagIsOpen;
7635 bool m_needsNewline;
7636 std::vector<std::string> m_tags;
7637 std::string m_indent;
7638 std::ostream* m_os;
7639 };
7640
7641 }
7642 namespace Catch {
7643 class XmlReporter : public SharedImpl<IReporter> {
7644 public:
7645 XmlReporter( ReporterConfig const& config ) : m_config( config ), m_sectionDepth( 0 ) {}
7646
7647 static std::string getDescription() {
7648 return "Reports test results as an XML document";
7649 }
7650 virtual ~XmlReporter();
7651
7652 private: // IReporter
7653
7654 virtual bool shouldRedirectStdout() const {
7655 return true;
7656 }
7657
7658 virtual void StartTesting() {
7659 m_xml = XmlWriter( m_config.stream() );
7660 m_xml.startElement( "Catch" );
7661 if( !m_config.fullConfig()->name().empty() )
7662 m_xml.writeAttribute( "name", m_config.fullConfig()->name() );
7663 }
7664
7665 virtual void EndTesting( const Totals& totals ) {
7666 m_xml.scopedElement( "OverallResults" )
7667 .writeAttribute( "successes", totals.assertions.passed )
7668 .writeAttribute( "failures", totals.assertions.failed );
7669 m_xml.endElement();
7670 }
7671
7672 virtual void StartGroup( const std::string& groupName ) {
7673 m_xml.startElement( "Group" )
7674 .writeAttribute( "name", groupName );
7675 }
7676
7677 virtual void EndGroup( const std::string&, const Totals& totals ) {
7678 m_xml.scopedElement( "OverallResults" )
7679 .writeAttribute( "successes", totals.assertions.passed )
7680 .writeAttribute( "failures", totals.assertions.failed );
7681 m_xml.endElement();
7682 }
7683
7684 virtual void StartSection( const std::string& sectionName, const std::string& description ) {
7685 if( m_sectionDepth++ > 0 ) {
7686 m_xml.startElement( "Section" )
7687 .writeAttribute( "name", trim( sectionName ) )
7688 .writeAttribute( "description", description );
7689 }
7690 }
7691 virtual void NoAssertionsInSection( const std::string& ) {}
7692 virtual void NoAssertionsInTestCase( const std::string& ) {}
7693
7694 virtual void EndSection( const std::string& /*sectionName*/, const Counts& assertions ) {
7695 if( --m_sectionDepth > 0 ) {
7696 m_xml.scopedElement( "OverallResults" )
7697 .writeAttribute( "successes", assertions.passed )
7698 .writeAttribute( "failures", assertions.failed );
7699 m_xml.endElement();
7700 }
7701 }
7702
7703 virtual void StartTestCase( const Catch::TestCaseInfo& testInfo ) {
7704 m_xml.startElement( "TestCase" ).writeAttribute( "name", trim( testInfo.name ) );
7705 m_currentTestSuccess = true;
7706 }
7707
7708 virtual void Result( const Catch::AssertionResult& assertionResult ) {
7709 if( !m_config.fullConfig()->includeSuccessfulResults() && assertionResult.getResultType() == ResultWas::Ok )
7710 return;
7711
7712 if( assertionResult.hasExpression() ) {
7713 m_xml.startElement( "Expression" )
7714 .writeAttribute( "success", assertionResult.succeeded() )
7715 .writeAttribute( "filename", assertionResult.getSourceInfo().file )
7716 .writeAttribute( "line", assertionResult.getSourceInfo().line );
7717
7718 m_xml.scopedElement( "Original" )
7719 .writeText( assertionResult.getExpression() );
7720 m_xml.scopedElement( "Expanded" )
7721 .writeText( assertionResult.getExpandedExpression() );
7722 m_currentTestSuccess &= assertionResult.succeeded();
7723 }
7724
7725 switch( assertionResult.getResultType() ) {
7726 case ResultWas::ThrewException:
7727 m_xml.scopedElement( "Exception" )
7728 .writeAttribute( "filename", assertionResult.getSourceInfo().file )
7729 .writeAttribute( "line", assertionResult.getSourceInfo().line )
7730 .writeText( assertionResult.getMessage() );
7731 m_currentTestSuccess = false;
7732 break;
7733 case ResultWas::Info:
7734 m_xml.scopedElement( "Info" )
7735 .writeText( assertionResult.getMessage() );
7736 break;
7737 case ResultWas::Warning:
7738 m_xml.scopedElement( "Warning" )
7739 .writeText( assertionResult.getMessage() );
7740 break;
7741 case ResultWas::ExplicitFailure:
7742 m_xml.scopedElement( "Failure" )
7743 .writeText( assertionResult.getMessage() );
7744 m_currentTestSuccess = false;
7745 break;
7746 case ResultWas::Unknown:
7747 case ResultWas::Ok:
7748 case ResultWas::FailureBit:
7749 case ResultWas::ExpressionFailed:
7750 case ResultWas::Exception:
7751 case ResultWas::DidntThrowException:
7752 break;
7753 }
7754 if( assertionResult.hasExpression() )
7755 m_xml.endElement();
7756 }
7757
7758 virtual void Aborted() {
7759 // !TBD
7760 }
7761
7762 virtual void EndTestCase( const Catch::TestCaseInfo&, const Totals&, const std::string&, const std::string& ) {
7763 m_xml.scopedElement( "OverallResult" ).writeAttribute( "success", m_currentTestSuccess );
7764 m_xml.endElement();
7765 }
7766
7767 private:
7768 ReporterConfig m_config;
7769 bool m_currentTestSuccess;
7770 XmlWriter m_xml;
7771 int m_sectionDepth;
7772 };
7773
7774 } // end namespace Catch
7775
7776 // #included from: ../reporters/catch_reporter_junit.hpp
7777 #define TWOBLUECUBES_CATCH_REPORTER_JUNIT_HPP_INCLUDED
7778
7779 #include <assert.h>
7780
7781 namespace Catch {
7782
7783 class JunitReporter : public CumulativeReporterBase {
7784 public:
7785 JunitReporter( ReporterConfig const& _config )
7786 : CumulativeReporterBase( _config ),
7787 xml( _config.stream() )
7788 {}
7789
7790 ~JunitReporter();
7791
7792 static std::string getDescription() {
7793 return "Reports test results in an XML format that looks like Ant's junitreport target";
7794 }
7795
7796 virtual void noMatchingTestCases( std::string const& /*spec*/ ) {}
7797
7798 virtual ReporterPreferences getPreferences() const {
7799 ReporterPreferences prefs;
7800 prefs.shouldRedirectStdOut = true;
7801 return prefs;
7802 }
7803
7804 virtual void testRunStarting( TestRunInfo const& runInfo ) {
7805 CumulativeReporterBase::testRunStarting( runInfo );
7806 xml.startElement( "testsuites" );
7807 }
7808
7809 virtual void testGroupStarting( GroupInfo const& groupInfo ) {
7810 suiteTimer.start();
7811 stdOutForSuite.str("");
7812 stdErrForSuite.str("");
7813 unexpectedExceptions = 0;
7814 CumulativeReporterBase::testGroupStarting( groupInfo );
7815 }
7816
7817 virtual bool assertionEnded( AssertionStats const& assertionStats ) {
7818 if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException )
7819 unexpectedExceptions++;
7820 return CumulativeReporterBase::assertionEnded( assertionStats );
7821 }
7822
7823 virtual void testCaseEnded( TestCaseStats const& testCaseStats ) {
7824 stdOutForSuite << testCaseStats.stdOut;
7825 stdErrForSuite << testCaseStats.stdErr;
7826 CumulativeReporterBase::testCaseEnded( testCaseStats );
7827 }
7828
7829 virtual void testGroupEnded( TestGroupStats const& testGroupStats ) {
7830 double suiteTime = suiteTimer.getElapsedSeconds();
7831 CumulativeReporterBase::testGroupEnded( testGroupStats );
7832 writeGroup( *m_testGroups.back(), suiteTime );
7833 }
7834
7835 virtual void testRunEndedCumulative() {
7836 xml.endElement();
7837 }
7838
7839 void writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
7840 XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
7841 TestGroupStats const& stats = groupNode.value;
7842 xml.writeAttribute( "name", stats.groupInfo.name );
7843 xml.writeAttribute( "errors", unexpectedExceptions );
7844 xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
7845 xml.writeAttribute( "tests", stats.totals.assertions.total() );
7846 xml.writeAttribute( "hostname", "tbd" ); // !TBD
7847 if( m_config->showDurations() == ShowDurations::Never )
7848 xml.writeAttribute( "time", "" );
7849 else
7850 xml.writeAttribute( "time", suiteTime );
7851 xml.writeAttribute( "timestamp", "tbd" ); // !TBD
7852
7853 // Write test cases
7854 for( TestGroupNode::ChildNodes::const_iterator
7855 it = groupNode.children.begin(), itEnd = groupNode.children.end();
7856 it != itEnd;
7857 ++it )
7858 writeTestCase( **it );
7859
7860 xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite.str() ), false );
7861 xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite.str() ), false );
7862 }
7863
7864 void writeTestCase( TestCaseNode const& testCaseNode ) {
7865 TestCaseStats const& stats = testCaseNode.value;
7866
7867 // All test cases have exactly one section - which represents the
7868 // test case itself. That section may have 0-n nested sections
7869 assert( testCaseNode.children.size() == 1 );
7870 SectionNode const& rootSection = *testCaseNode.children.front();
7871
7872 std::string className = stats.testInfo.className;
7873
7874 if( className.empty() ) {
7875 if( rootSection.childSections.empty() )
7876 className = "global";
7877 }
7878 writeSection( className, "", rootSection );
7879 }
7880
7881 void writeSection( std::string const& className,
7882 std::string const& rootName,
7883 SectionNode const& sectionNode ) {
7884 std::string name = trim( sectionNode.stats.sectionInfo.name );
7885 if( !rootName.empty() )
7886 name = rootName + "/" + name;
7887
7888 if( !sectionNode.assertions.empty() ||
7889 !sectionNode.stdOut.empty() ||
7890 !sectionNode.stdErr.empty() ) {
7891 XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
7892 if( className.empty() ) {
7893 xml.writeAttribute( "classname", name );
7894 xml.writeAttribute( "name", "root" );
7895 }
7896 else {
7897 xml.writeAttribute( "classname", className );
7898 xml.writeAttribute( "name", name );
7899 }
7900 xml.writeAttribute( "time", toString( sectionNode.stats.durationInSeconds ) );
7901
7902 writeAssertions( sectionNode );
7903
7904 if( !sectionNode.stdOut.empty() )
7905 xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
7906 if( !sectionNode.stdErr.empty() )
7907 xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
7908 }
7909 for( SectionNode::ChildSections::const_iterator
7910 it = sectionNode.childSections.begin(),
7911 itEnd = sectionNode.childSections.end();
7912 it != itEnd;
7913 ++it )
7914 if( className.empty() )
7915 writeSection( name, "", **it );
7916 else
7917 writeSection( className, name, **it );
7918 }
7919
7920 void writeAssertions( SectionNode const& sectionNode ) {
7921 for( SectionNode::Assertions::const_iterator
7922 it = sectionNode.assertions.begin(), itEnd = sectionNode.assertions.end();
7923 it != itEnd;
7924 ++it )
7925 writeAssertion( *it );
7926 }
7927 void writeAssertion( AssertionStats const& stats ) {
7928 AssertionResult const& result = stats.assertionResult;
7929 if( !result.isOk() ) {
7930 std::string elementName;
7931 switch( result.getResultType() ) {
7932 case ResultWas::ThrewException:
7933 elementName = "error";
7934 break;
7935 case ResultWas::ExplicitFailure:
7936 elementName = "failure";
7937 break;
7938 case ResultWas::ExpressionFailed:
7939 elementName = "failure";
7940 break;
7941 case ResultWas::DidntThrowException:
7942 elementName = "failure";
7943 break;
7944
7945 // We should never see these here:
7946 case ResultWas::Info:
7947 case ResultWas::Warning:
7948 case ResultWas::Ok:
7949 case ResultWas::Unknown:
7950 case ResultWas::FailureBit:
7951 case ResultWas::Exception:
7952 elementName = "internalError";
7953 break;
7954 }
7955
7956 XmlWriter::ScopedElement e = xml.scopedElement( elementName );
7957
7958 xml.writeAttribute( "message", result.getExpandedExpression() );
7959 xml.writeAttribute( "type", result.getTestMacroName() );
7960
7961 std::ostringstream oss;
7962 if( !result.getMessage().empty() )
7963 oss << result.getMessage() << "\n";
7964 for( std::vector<MessageInfo>::const_iterator
7965 it = stats.infoMessages.begin(),
7966 itEnd = stats.infoMessages.end();
7967 it != itEnd;
7968 ++it )
7969 if( it->type == ResultWas::Info )
7970 oss << it->message << "\n";
7971
7972 oss << "at " << result.getSourceInfo();
7973 xml.writeText( oss.str(), false );
7974 }
7975 }
7976
7977 XmlWriter xml;
7978 Timer suiteTimer;
7979 std::ostringstream stdOutForSuite;
7980 std::ostringstream stdErrForSuite;
7981 unsigned int unexpectedExceptions;
7982 };
7983
7984 INTERNAL_CATCH_REGISTER_REPORTER( "junit", JunitReporter )
7985
7986 } // end namespace Catch
7987
7988 // #included from: ../reporters/catch_reporter_console.hpp
7989 #define TWOBLUECUBES_CATCH_REPORTER_CONSOLE_HPP_INCLUDED
7990
7991 #include <cstring>
7992
7993 namespace Catch {
7994
7995 struct ConsoleReporter : StreamingReporterBase {
7996 ConsoleReporter( ReporterConfig const& _config )
7997 : StreamingReporterBase( _config ),
7998 m_headerPrinted( false ),
7999 m_atLeastOneTestCasePrinted( false )
8000 {}
8001
8002 virtual ~ConsoleReporter();
8003 static std::string getDescription() {
8004 return "Reports test results as plain lines of text";
8005 }
8006 virtual ReporterPreferences getPreferences() const {
8007 ReporterPreferences prefs;
8008 prefs.shouldRedirectStdOut = false;
8009 return prefs;
8010 }
8011
8012 virtual void noMatchingTestCases( std::string const& spec ) {
8013 stream << "No test cases matched '" << spec << "'" << std::endl;
8014 }
8015
8016 virtual void assertionStarting( AssertionInfo const& ) {
8017 }
8018
8019 virtual bool assertionEnded( AssertionStats const& _assertionStats ) {
8020 AssertionResult const& result = _assertionStats.assertionResult;
8021
8022 bool printInfoMessages = true;
8023
8024 // Drop out if result was successful and we're not printing those
8025 if( !m_config->includeSuccessfulResults() && result.isOk() ) {
8026 if( result.getResultType() != ResultWas::Warning )
8027 return false;
8028 printInfoMessages = false;
8029 }
8030
8031 lazyPrint();
8032
8033 AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
8034 printer.print();
8035 stream << std::endl;
8036 return true;
8037 }
8038
8039 virtual void sectionStarting( SectionInfo const& _sectionInfo ) {
8040 m_headerPrinted = false;
8041 StreamingReporterBase::sectionStarting( _sectionInfo );
8042 }
8043 virtual void sectionEnded( SectionStats const& _sectionStats ) {
8044 if( _sectionStats.missingAssertions ) {
8045 lazyPrint();
8046 Colour colour( Colour::ResultError );
8047 if( m_sectionStack.size() > 1 )
8048 stream << "\nNo assertions in section";
8049 else
8050 stream << "\nNo assertions in test case";
8051 stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
8052 }
8053 if( m_headerPrinted ) {
8054 if( m_config->showDurations() == ShowDurations::Always )
8055 stream << "Completed in " << _sectionStats.durationInSeconds << "s" << std::endl;
8056 m_headerPrinted = false;
8057 }
8058 else {
8059 if( m_config->showDurations() == ShowDurations::Always )
8060 stream << _sectionStats.sectionInfo.name << " completed in " << _sectionStats.durationInSeconds << "s" << std::endl;
8061 }
8062 StreamingReporterBase::sectionEnded( _sectionStats );
8063 }
8064
8065 virtual void testCaseEnded( TestCaseStats const& _testCaseStats ) {
8066 StreamingReporterBase::testCaseEnded( _testCaseStats );
8067 m_headerPrinted = false;
8068 }
8069 virtual void testGroupEnded( TestGroupStats const& _testGroupStats ) {
8070 if( currentGroupInfo.used ) {
8071 printSummaryDivider();
8072 stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
8073 printTotals( _testGroupStats.totals );
8074 stream << "\n" << std::endl;
8075 }
8076 StreamingReporterBase::testGroupEnded( _testGroupStats );
8077 }
8078 virtual void testRunEnded( TestRunStats const& _testRunStats ) {
8079 if( m_atLeastOneTestCasePrinted )
8080 printTotalsDivider();
8081 printTotals( _testRunStats.totals );
8082 stream << "\n" << std::endl;
8083 StreamingReporterBase::testRunEnded( _testRunStats );
8084 }
8085
8086 private:
8087
8088 class AssertionPrinter {
8089 void operator= ( AssertionPrinter const& );
8090 public:
8091 AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages )
8092 : stream( _stream ),
8093 stats( _stats ),
8094 result( _stats.assertionResult ),
8095 colour( Colour::None ),
8096 message( result.getMessage() ),
8097 messages( _stats.infoMessages ),
8098 printInfoMessages( _printInfoMessages )
8099 {
8100 switch( result.getResultType() ) {
8101 case ResultWas::Ok:
8102 colour = Colour::Success;
8103 passOrFail = "PASSED";
8104 //if( result.hasMessage() )
8105 if( _stats.infoMessages.size() == 1 )
8106 messageLabel = "with message";
8107 if( _stats.infoMessages.size() > 1 )
8108 messageLabel = "with messages";
8109 break;
8110 case ResultWas::ExpressionFailed:
8111 if( result.isOk() ) {
8112 colour = Colour::Success;
8113 passOrFail = "FAILED - but was ok";
8114 }
8115 else {
8116 colour = Colour::Error;
8117 passOrFail = "FAILED";
8118 }
8119 if( _stats.infoMessages.size() == 1 )
8120 messageLabel = "with message";
8121 if( _stats.infoMessages.size() > 1 )
8122 messageLabel = "with messages";
8123 break;
8124 case ResultWas::ThrewException:
8125 colour = Colour::Error;
8126 passOrFail = "FAILED";
8127 messageLabel = "due to unexpected exception with message";
8128 break;
8129 case ResultWas::DidntThrowException:
8130 colour = Colour::Error;
8131 passOrFail = "FAILED";
8132 messageLabel = "because no exception was thrown where one was expected";
8133 break;
8134 case ResultWas::Info:
8135 messageLabel = "info";
8136 break;
8137 case ResultWas::Warning:
8138 messageLabel = "warning";
8139 break;
8140 case ResultWas::ExplicitFailure:
8141 passOrFail = "FAILED";
8142 colour = Colour::Error;
8143 if( _stats.infoMessages.size() == 1 )
8144 messageLabel = "explicitly with message";
8145 if( _stats.infoMessages.size() > 1 )
8146 messageLabel = "explicitly with messages";
8147 break;
8148 // These cases are here to prevent compiler warnings
8149 case ResultWas::Unknown:
8150 case ResultWas::FailureBit:
8151 case ResultWas::Exception:
8152 passOrFail = "** internal error **";
8153 colour = Colour::Error;
8154 break;
8155 }
8156 }
8157
8158 void print() const {
8159 printSourceInfo();
8160 if( stats.totals.assertions.total() > 0 ) {
8161 if( result.isOk() )
8162 stream << "\n";
8163 printResultType();
8164 printOriginalExpression();
8165 printReconstructedExpression();
8166 }
8167 else {
8168 stream << "\n";
8169 }
8170 printMessage();
8171 }
8172
8173 private:
8174 void printResultType() const {
8175 if( !passOrFail.empty() ) {
8176 Colour colourGuard( colour );
8177 stream << passOrFail << ":\n";
8178 }
8179 }
8180 void printOriginalExpression() const {
8181 if( result.hasExpression() ) {
8182 Colour colourGuard( Colour::OriginalExpression );
8183 stream << " ";
8184 stream << result.getExpressionInMacro();
8185 stream << "\n";
8186 }
8187 }
8188 void printReconstructedExpression() const {
8189 if( result.hasExpandedExpression() ) {
8190 stream << "with expansion:\n";
8191 Colour colourGuard( Colour::ReconstructedExpression );
8192 stream << Text( result.getExpandedExpression(), TextAttributes().setIndent(2) ) << "\n";
8193 }
8194 }
8195 void printMessage() const {
8196 if( !messageLabel.empty() )
8197 stream << messageLabel << ":" << "\n";
8198 for( std::vector<MessageInfo>::const_iterator it = messages.begin(), itEnd = messages.end();
8199 it != itEnd;
8200 ++it ) {
8201 // If this assertion is a warning ignore any INFO messages
8202 if( printInfoMessages || it->type != ResultWas::Info )
8203 stream << Text( it->message, TextAttributes().setIndent(2) ) << "\n";
8204 }
8205 }
8206 void printSourceInfo() const {
8207 Colour colourGuard( Colour::FileName );
8208 stream << result.getSourceInfo() << ": ";
8209 }
8210
8211 std::ostream& stream;
8212 AssertionStats const& stats;
8213 AssertionResult const& result;
8214 Colour::Code colour;
8215 std::string passOrFail;
8216 std::string messageLabel;
8217 std::string message;
8218 std::vector<MessageInfo> messages;
8219 bool printInfoMessages;
8220 };
8221
8222 void lazyPrint() {
8223
8224 if( !currentTestRunInfo.used )
8225 lazyPrintRunInfo();
8226 if( !currentGroupInfo.used )
8227 lazyPrintGroupInfo();
8228
8229 if( !m_headerPrinted ) {
8230 printTestCaseAndSectionHeader();
8231 m_headerPrinted = true;
8232 }
8233 m_atLeastOneTestCasePrinted = true;
8234 }
8235 void lazyPrintRunInfo() {
8236 stream << "\n" << getLineOfChars<'~'>() << "\n";
8237 Colour colour( Colour::SecondaryText );
8238 stream << currentTestRunInfo->name
8239 << " is a Catch v" << libraryVersion.majorVersion << "."
8240 << libraryVersion.minorVersion << " b"
8241 << libraryVersion.buildNumber;
8242 if( libraryVersion.branchName != std::string( "master" ) )
8243 stream << " (" << libraryVersion.branchName << ")";
8244 stream << " host application.\n"
8245 << "Run with -? for options\n\n";
8246
8247 currentTestRunInfo.used = true;
8248 }
8249 void lazyPrintGroupInfo() {
8250 if( !currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1 ) {
8251 printClosedHeader( "Group: " + currentGroupInfo->name );
8252 currentGroupInfo.used = true;
8253 }
8254 }
8255 void printTestCaseAndSectionHeader() {
8256 assert( !m_sectionStack.empty() );
8257 printOpenHeader( currentTestCaseInfo->name );
8258
8259 if( m_sectionStack.size() > 1 ) {
8260 Colour colourGuard( Colour::Headers );
8261
8262 std::vector<SectionInfo>::const_iterator
8263 it = m_sectionStack.begin()+1, // Skip first section (test case)
8264 itEnd = m_sectionStack.end();
8265 for( ; it != itEnd; ++it )
8266 printHeaderString( it->name, 2 );
8267 }
8268
8269 SourceLineInfo lineInfo = m_sectionStack.front().lineInfo;
8270
8271 if( !lineInfo.empty() ){
8272 stream << getLineOfChars<'-'>() << "\n";
8273 Colour colourGuard( Colour::FileName );
8274 stream << lineInfo << "\n";
8275 }
8276 stream << getLineOfChars<'.'>() << "\n" << std::endl;
8277 }
8278
8279 void printClosedHeader( std::string const& _name ) {
8280 printOpenHeader( _name );
8281 stream << getLineOfChars<'.'>() << "\n";
8282 }
8283 void printOpenHeader( std::string const& _name ) {
8284 stream << getLineOfChars<'-'>() << "\n";
8285 {
8286 Colour colourGuard( Colour::Headers );
8287 printHeaderString( _name );
8288 }
8289 }
8290
8291 // if string has a : in first line will set indent to follow it on
8292 // subsequent lines
8293 void printHeaderString( std::string const& _string, std::size_t indent = 0 ) {
8294 std::size_t i = _string.find( ": " );
8295 if( i != std::string::npos )
8296 i+=2;
8297 else
8298 i = 0;
8299 stream << Text( _string, TextAttributes()
8300 .setIndent( indent+i)
8301 .setInitialIndent( indent ) ) << "\n";
8302 }
8303
8304 void printTotals( const Totals& totals ) {
8305 if( totals.testCases.total() == 0 ) {
8306 stream << "No tests ran";
8307 }
8308 else if( totals.assertions.total() == 0 ) {
8309 Colour colour( Colour::Yellow );
8310 printCounts( "test case", totals.testCases );
8311 stream << " (no assertions)";
8312 }
8313 else if( totals.assertions.failed ) {
8314 Colour colour( Colour::ResultError );
8315 printCounts( "test case", totals.testCases );
8316 if( totals.testCases.failed > 0 ) {
8317 stream << " (";
8318 printCounts( "assertion", totals.assertions );
8319 stream << ")";
8320 }
8321 }
8322 else {
8323 Colour colour( Colour::ResultSuccess );
8324 stream << "All tests passed ("
8325 << pluralise( totals.assertions.passed, "assertion" ) << " in "
8326 << pluralise( totals.testCases.passed, "test case" ) << ")";
8327 }
8328 }
8329 void printCounts( std::string const& label, Counts const& counts ) {
8330 if( counts.total() == 1 ) {
8331 stream << "1 " << label << " - ";
8332 if( counts.failed )
8333 stream << "failed";
8334 else
8335 stream << "passed";
8336 }
8337 else {
8338 stream << counts.total() << " " << label << "s ";
8339 if( counts.passed ) {
8340 if( counts.failed )
8341 stream << "- " << counts.failed << " failed";
8342 else if( counts.passed == 2 )
8343 stream << "- both passed";
8344 else
8345 stream << "- all passed";
8346 }
8347 else {
8348 if( counts.failed == 2 )
8349 stream << "- both failed";
8350 else
8351 stream << "- all failed";
8352 }
8353 }
8354 }
8355
8356 void printTotalsDivider() {
8357 stream << getLineOfChars<'='>() << "\n";
8358 }
8359 void printSummaryDivider() {
8360 stream << getLineOfChars<'-'>() << "\n";
8361 }
8362 template<char C>
8363 static char const* getLineOfChars() {
8364 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
8365 if( !*line ) {
8366 memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
8367 line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
8368 }
8369 return line;
8370 }
8371
8372 private:
8373 bool m_headerPrinted;
8374 bool m_atLeastOneTestCasePrinted;
8375 };
8376
8377 INTERNAL_CATCH_REGISTER_REPORTER( "console", ConsoleReporter )
8378
8379 } // end namespace Catch
8380
8381 // #included from: ../reporters/catch_reporter_compact.hpp
8382 #define TWOBLUECUBES_CATCH_REPORTER_COMPACT_HPP_INCLUDED
8383
8384 namespace Catch {
8385
8386 struct CompactReporter : StreamingReporterBase {
8387
8388 CompactReporter( ReporterConfig const& _config )
8389 : StreamingReporterBase( _config )
8390 {}
8391
8392 virtual ~CompactReporter();
8393
8394 static std::string getDescription() {
8395 return "Reports test results on a single line, suitable for IDEs";
8396 }
8397
8398 virtual ReporterPreferences getPreferences() const {
8399 ReporterPreferences prefs;
8400 prefs.shouldRedirectStdOut = false;
8401 return prefs;
8402 }
8403
8404 virtual void noMatchingTestCases( std::string const& spec ) {
8405 stream << "No test cases matched '" << spec << "'" << std::endl;
8406 }
8407
8408 virtual void assertionStarting( AssertionInfo const& ) {
8409 }
8410
8411 virtual bool assertionEnded( AssertionStats const& _assertionStats ) {
8412 AssertionResult const& result = _assertionStats.assertionResult;
8413
8414 bool printInfoMessages = true;
8415
8416 // Drop out if result was successful and we're not printing those
8417 if( !m_config->includeSuccessfulResults() && result.isOk() ) {
8418 if( result.getResultType() != ResultWas::Warning )
8419 return false;
8420 printInfoMessages = false;
8421 }
8422
8423 AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
8424 printer.print();
8425
8426 stream << std::endl;
8427 return true;
8428 }
8429
8430 virtual void testRunEnded( TestRunStats const& _testRunStats ) {
8431 printTotals( _testRunStats.totals );
8432 stream << "\n" << std::endl;
8433 StreamingReporterBase::testRunEnded( _testRunStats );
8434 }
8435
8436 private:
8437 class AssertionPrinter {
8438 void operator= ( AssertionPrinter const& );
8439 public:
8440 AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages )
8441 : stream( _stream )
8442 , stats( _stats )
8443 , result( _stats.assertionResult )
8444 , messages( _stats.infoMessages )
8445 , itMessage( _stats.infoMessages.begin() )
8446 , printInfoMessages( _printInfoMessages )
8447 {}
8448
8449 void print() {
8450 printSourceInfo();
8451
8452 itMessage = messages.begin();
8453
8454 switch( result.getResultType() ) {
8455 case ResultWas::Ok:
8456 printResultType( Colour::ResultSuccess, passedString() );
8457 printOriginalExpression();
8458 printReconstructedExpression();
8459 if ( ! result.hasExpression() )
8460 printRemainingMessages( Colour::None );
8461 else
8462 printRemainingMessages();
8463 break;
8464 case ResultWas::ExpressionFailed:
8465 if( result.isOk() )
8466 printResultType( Colour::ResultSuccess, failedString() + std::string( " - but was ok" ) );
8467 else
8468 printResultType( Colour::Error, failedString() );
8469 printOriginalExpression();
8470 printReconstructedExpression();
8471 printRemainingMessages();
8472 break;
8473 case ResultWas::ThrewException:
8474 printResultType( Colour::Error, failedString() );
8475 printIssue( "unexpected exception with message:" );
8476 printMessage();
8477 printExpressionWas();
8478 printRemainingMessages();
8479 break;
8480 case ResultWas::DidntThrowException:
8481 printResultType( Colour::Error, failedString() );
8482 printIssue( "expected exception, got none" );
8483 printExpressionWas();
8484 printRemainingMessages();
8485 break;
8486 case ResultWas::Info:
8487 printResultType( Colour::None, "info" );
8488 printMessage();
8489 printRemainingMessages();
8490 break;
8491 case ResultWas::Warning:
8492 printResultType( Colour::None, "warning" );
8493 printMessage();
8494 printRemainingMessages();
8495 break;
8496 case ResultWas::ExplicitFailure:
8497 printResultType( Colour::Error, failedString() );
8498 printIssue( "explicitly" );
8499 printRemainingMessages( Colour::None );
8500 break;
8501 // These cases are here to prevent compiler warnings
8502 case ResultWas::Unknown:
8503 case ResultWas::FailureBit:
8504 case ResultWas::Exception:
8505 printResultType( Colour::Error, "** internal error **" );
8506 break;
8507 }
8508 }
8509
8510 private:
8511 // Colour::LightGrey
8512
8513 static Colour dimColour() { return Colour::FileName; }
8514
8515 #ifdef CATCH_PLATFORM_MAC
8516 static const char* failedString() { return "FAILED"; }
8517 static const char* passedString() { return "PASSED"; }
8518 #else
8519 static const char* failedString() { return "failed"; }
8520 static const char* passedString() { return "passed"; }
8521 #endif
8522
8523 void printSourceInfo() const {
8524 Colour colourGuard( Colour::FileName );
8525 stream << result.getSourceInfo() << ":";
8526 }
8527
8528 void printResultType( Colour colour, std::string passOrFail ) const {
8529 if( !passOrFail.empty() ) {
8530 {
8531 Colour colourGuard( colour );
8532 stream << " " << passOrFail;
8533 }
8534 stream << ":";
8535 }
8536 }
8537
8538 void printIssue( std::string issue ) const {
8539 stream << " " << issue;
8540 }
8541
8542 void printExpressionWas() {
8543 if( result.hasExpression() ) {
8544 stream << ";";
8545 {
8546 Colour colour( dimColour() );
8547 stream << " expression was:";
8548 }
8549 printOriginalExpression();
8550 }
8551 }
8552
8553 void printOriginalExpression() const {
8554 if( result.hasExpression() ) {
8555 stream << " " << result.getExpression();
8556 }
8557 }
8558
8559 void printReconstructedExpression() const {
8560 if( result.hasExpandedExpression() ) {
8561 {
8562 Colour colour( dimColour() );
8563 stream << " for: ";
8564 }
8565 stream << result.getExpandedExpression();
8566 }
8567 }
8568
8569 void printMessage() {
8570 if ( itMessage != messages.end() ) {
8571 stream << " '" << itMessage->message << "'";
8572 ++itMessage;
8573 }
8574 }
8575
8576 void printRemainingMessages( Colour colour = dimColour() ) {
8577 if ( itMessage == messages.end() )
8578 return;
8579
8580 // using messages.end() directly yields compilation error:
8581 std::vector<MessageInfo>::const_iterator itEnd = messages.end();
8582 const std::size_t N = static_cast<std::size_t>( std::distance( itMessage, itEnd ) );
8583
8584 {
8585 Colour colourGuard( colour );
8586 stream << " with " << pluralise( N, "message" ) << ":";
8587 }
8588
8589 for(; itMessage != itEnd; ) {
8590 // If this assertion is a warning ignore any INFO messages
8591 if( printInfoMessages || itMessage->type != ResultWas::Info ) {
8592 stream << " '" << itMessage->message << "'";
8593 if ( ++itMessage != itEnd ) {
8594 Colour colourGuard( dimColour() );
8595 stream << " and";
8596 }
8597 }
8598 }
8599 }
8600
8601 private:
8602 std::ostream& stream;
8603 AssertionStats const& stats;
8604 AssertionResult const& result;
8605 std::vector<MessageInfo> messages;
8606 std::vector<MessageInfo>::const_iterator itMessage;
8607 bool printInfoMessages;
8608 };
8609
8610 // Colour, message variants:
8611 // - white: No tests ran.
8612 // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
8613 // - white: Passed [both/all] N test cases (no assertions).
8614 // - red: Failed N tests cases, failed M assertions.
8615 // - green: Passed [both/all] N tests cases with M assertions.
8616
8617 std::string bothOrAll( std::size_t count ) const {
8618 return count == 1 ? "" : count == 2 ? "both " : "all " ;
8619 }
8620
8621 void printTotals( const Totals& totals ) const {
8622 if( totals.testCases.total() == 0 ) {
8623 stream << "No tests ran.";
8624 }
8625 else if( totals.testCases.failed == totals.testCases.total() ) {
8626 Colour colour( Colour::ResultError );
8627 const std::string qualify_assertions_failed =
8628 totals.assertions.failed == totals.assertions.total() ?
8629 bothOrAll( totals.assertions.failed ) : "";
8630 stream <<
8631 "Failed " << bothOrAll( totals.testCases.failed )
8632 << pluralise( totals.testCases.failed, "test case" ) << ", "
8633 "failed " << qualify_assertions_failed <<
8634 pluralise( totals.assertions.failed, "assertion" ) << ".";
8635 }
8636 else if( totals.assertions.total() == 0 ) {
8637 stream <<
8638 "Passed " << bothOrAll( totals.testCases.total() )
8639 << pluralise( totals.testCases.total(), "test case" )
8640 << " (no assertions).";
8641 }
8642 else if( totals.assertions.failed ) {
8643 Colour colour( Colour::ResultError );
8644 stream <<
8645 "Failed " << pluralise( totals.testCases.failed, "test case" ) << ", "
8646 "failed " << pluralise( totals.assertions.failed, "assertion" ) << ".";
8647 }
8648 else {
8649 Colour colour( Colour::ResultSuccess );
8650 stream <<
8651 "Passed " << bothOrAll( totals.testCases.passed )
8652 << pluralise( totals.testCases.passed, "test case" ) <<
8653 " with " << pluralise( totals.assertions.passed, "assertion" ) << ".";
8654 }
8655 }
8656 };
8657
8658 INTERNAL_CATCH_REGISTER_REPORTER( "compact", CompactReporter )
8659
8660 } // end namespace Catch
8661
8662 namespace Catch {
8663 NonCopyable::~NonCopyable() {}
8664 IShared::~IShared() {}
8665 StreamBufBase::~StreamBufBase() CATCH_NOEXCEPT {}
8666 IContext::~IContext() {}
8667 IResultCapture::~IResultCapture() {}
8668 ITestCase::~ITestCase() {}
8669 ITestCaseRegistry::~ITestCaseRegistry() {}
8670 IRegistryHub::~IRegistryHub() {}
8671 IMutableRegistryHub::~IMutableRegistryHub() {}
8672 IExceptionTranslator::~IExceptionTranslator() {}
8673 IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() {}
8674 IReporter::~IReporter() {}
8675 IReporterFactory::~IReporterFactory() {}
8676 IReporterRegistry::~IReporterRegistry() {}
8677 IStreamingReporter::~IStreamingReporter() {}
8678 AssertionStats::~AssertionStats() {}
8679 SectionStats::~SectionStats() {}
8680 TestCaseStats::~TestCaseStats() {}
8681 TestGroupStats::~TestGroupStats() {}
8682 TestRunStats::~TestRunStats() {}
8683 CumulativeReporterBase::SectionNode::~SectionNode() {}
8684 CumulativeReporterBase::~CumulativeReporterBase() {}
8685
8686 StreamingReporterBase::~StreamingReporterBase() {}
8687 ConsoleReporter::~ConsoleReporter() {}
8688 CompactReporter::~CompactReporter() {}
8689 IRunner::~IRunner() {}
8690 IMutableContext::~IMutableContext() {}
8691 IConfig::~IConfig() {}
8692 XmlReporter::~XmlReporter() {}
8693 JunitReporter::~JunitReporter() {}
8694 TestRegistry::~TestRegistry() {}
8695 FreeFunctionTestCase::~FreeFunctionTestCase() {}
8696 IGeneratorInfo::~IGeneratorInfo() {}
8697 IGeneratorsForTest::~IGeneratorsForTest() {}
8698
8699 Matchers::Impl::StdString::Equals::~Equals() {}
8700 Matchers::Impl::StdString::Contains::~Contains() {}
8701 Matchers::Impl::StdString::StartsWith::~StartsWith() {}
8702 Matchers::Impl::StdString::EndsWith::~EndsWith() {}
8703
8704 void Config::dummy() {}
8705
8706 INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( "xml", XmlReporter )
8707 }
8708
8709 #ifdef __clang__
8710 #pragma clang diagnostic pop
8711 #endif
8712
8713 #endif
8714
8715 #ifdef CATCH_CONFIG_MAIN
8716 // #included from: internal/catch_default_main.hpp
8717 #define TWOBLUECUBES_CATCH_DEFAULT_MAIN_HPP_INCLUDED
8718
8719 #ifndef __OBJC__
8720
8721 // Standard C/C++ main entry point
8722 int main (int argc, char * const argv[]) {
8723 return Catch::Session().run( argc, argv );
8724 }
8725
8726 #else // __OBJC__
8727
8728 // Objective-C entry point
8729 int main (int argc, char * const argv[]) {
8730 #if !CATCH_ARC_ENABLED
8731 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
8732 #endif
8733
8734 Catch::registerTestMethods();
8735 int result = Catch::Session().run( argc, (char* const*)argv );
8736
8737 #if !CATCH_ARC_ENABLED
8738 [pool drain];
8739 #endif
8740
8741 return result;
8742 }
8743
8744 #endif // __OBJC__
8745
8746 #endif
8747
8748 #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
8749 # undef CLARA_CONFIG_MAIN
8750 #endif
8751
8752 //////
8753
8754 // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
8755 #ifdef CATCH_CONFIG_PREFIX_ALL
8756
8757 #define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE" )
8758 #define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::NegateResult, "CATCH_REQUIRE_FALSE" )
8759
8760 #define CATCH_REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, ..., Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THROWS" )
8761 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THROWS_AS" )
8762 #define CATCH_REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_NOTHROW" )
8763
8764 #define CATCH_CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK" )
8765 #define CATCH_CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::NegateResult, "CATCH_CHECK_FALSE" )
8766 #define CATCH_CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_IF" )
8767 #define CATCH_CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_ELSE" )
8768 #define CATCH_CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CATCH_CHECK_NOFAIL" )
8769
8770 #define CATCH_CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, ..., Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS" )
8771 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS_AS" )
8772 #define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_NOTHROW" )
8773
8774 #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THAT" )
8775 #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THAT" )
8776
8777 #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" )
8778 #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "CATCH_WARN", msg )
8779 #define CATCH_SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" )
8780 #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" )
8781 #define CATCH_SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" )
8782
8783 #ifdef CATCH_CONFIG_VARIADIC_MACROS
8784 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
8785 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
8786 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
8787 #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
8788 #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", __VA_ARGS__ )
8789 #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", __VA_ARGS__ )
8790 #else
8791 #define CATCH_TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description )
8792 #define CATCH_TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description )
8793 #define CATCH_METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description )
8794 #define CATCH_SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description )
8795 #define CATCH_FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", msg )
8796 #define CATCH_SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", msg )
8797 #endif
8798 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" )
8799
8800 #define CATCH_REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType )
8801 #define CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType )
8802
8803 #define CATCH_GENERATE( expr) INTERNAL_CATCH_GENERATE( expr )
8804
8805 // "BDD-style" convenience wrappers
8806 #ifdef CATCH_CONFIG_VARIADIC_MACROS
8807 #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
8808 #else
8809 #define CATCH_SCENARIO( name, tags ) CATCH_TEST_CASE( "Scenario: " name, tags )
8810 #endif
8811 #define CATCH_GIVEN( desc ) CATCH_SECTION( "Given: " desc, "" )
8812 #define CATCH_WHEN( desc ) CATCH_SECTION( " When: " desc, "" )
8813 #define CATCH_AND_WHEN( desc ) CATCH_SECTION( " And: " desc, "" )
8814 #define CATCH_THEN( desc ) CATCH_SECTION( " Then: " desc, "" )
8815 #define CATCH_AND_THEN( desc ) CATCH_SECTION( " And: " desc, "" )
8816
8817 // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
8818 #else
8819
8820 #define REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, "REQUIRE" )
8821 #define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::NegateResult, "REQUIRE_FALSE" )
8822
8823 #define REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, ..., Catch::ResultDisposition::Normal, "REQUIRE_THROWS" )
8824 #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "REQUIRE_THROWS_AS" )
8825 #define REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "REQUIRE_NOTHROW" )
8826
8827 #define CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK" )
8828 #define CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::NegateResult, "CHECK_FALSE" )
8829 #define CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_IF" )
8830 #define CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_ELSE" )
8831 #define CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CHECK_NOFAIL" )
8832
8833 #define CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, ..., Catch::ResultDisposition::ContinueOnFailure, "CHECK_THROWS" )
8834 #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THROWS_AS" )
8835 #define CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK_NOTHROW" )
8836
8837 #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THAT" )
8838 #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "REQUIRE_THAT" )
8839
8840 #define INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" )
8841 #define WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "WARN", msg )
8842 #define SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" )
8843 #define CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" )
8844 #define SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" )
8845
8846 #ifdef CATCH_CONFIG_VARIADIC_MACROS
8847 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
8848 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
8849 #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
8850 #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
8851 #define FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", __VA_ARGS__ )
8852 #define SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", __VA_ARGS__ )
8853 #else
8854 #define TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description )
8855 #define TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description )
8856 #define METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description )
8857 #define SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description )
8858 #define FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", msg )
8859 #define SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", msg )
8860 #endif
8861 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" )
8862
8863 #define REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType )
8864 #define REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType )
8865
8866 #define GENERATE( expr) INTERNAL_CATCH_GENERATE( expr )
8867
8868 #endif
8869
8870 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
8871
8872 // "BDD-style" convenience wrappers
8873 #ifdef CATCH_CONFIG_VARIADIC_MACROS
8874 #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
8875 #else
8876 #define SCENARIO( name, tags ) TEST_CASE( "Scenario: " name, tags )
8877 #endif
8878 #define GIVEN( desc ) SECTION( " Given: " desc, "" )
8879 #define WHEN( desc ) SECTION( " When: " desc, "" )
8880 #define AND_WHEN( desc ) SECTION( "And when: " desc, "" )
8881 #define THEN( desc ) SECTION( " Then: " desc, "" )
8882 #define AND_THEN( desc ) SECTION( " And: " desc, "" )
8883
8884 using Catch::Detail::Approx;
8885
8886 #ifdef __clang__
8887 #pragma clang diagnostic pop
8888 #endif
8889
8890 #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
8891