Debian Codegraph @

test/unit/cpp/catch/catch.hpp

raw
1 /*
2 * Catch v1.9.6
3 * Generated: 2017-06-27 12:19:54.557875
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 system_header
18 #elif defined __GNUC__
19 # pragma GCC system_header
20 #endif
21
22 // #included from: internal/catch_suppress_warnings.h
23
24 #ifdef __clang__
25 # ifdef __ICC // icpc defines the __clang__ macro
26 # pragma warning(push)
27 # pragma warning(disable: 161 1682)
28 # else // __ICC
29 # pragma clang diagnostic ignored "-Wglobal-constructors"
30 # pragma clang diagnostic ignored "-Wvariadic-macros"
31 # pragma clang diagnostic ignored "-Wc99-extensions"
32 # pragma clang diagnostic ignored "-Wunused-variable"
33 # pragma clang diagnostic push
34 # pragma clang diagnostic ignored "-Wpadded"
35 # pragma clang diagnostic ignored "-Wc++98-compat"
36 # pragma clang diagnostic ignored "-Wc++98-compat-pedantic"
37 # pragma clang diagnostic ignored "-Wswitch-enum"
38 # pragma clang diagnostic ignored "-Wcovered-switch-default"
39 # endif
40 #elif defined __GNUC__
41 # pragma GCC diagnostic ignored "-Wvariadic-macros"
42 # pragma GCC diagnostic ignored "-Wunused-variable"
43 # pragma GCC diagnostic ignored "-Wparentheses"
44
45 # pragma GCC diagnostic push
46 # pragma GCC diagnostic ignored "-Wpadded"
47 #endif
48 #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
49 # define CATCH_IMPL
50 #endif
51
52 #ifdef CATCH_IMPL
53 # ifndef CLARA_CONFIG_MAIN
54 # define CLARA_CONFIG_MAIN_NOT_DEFINED
55 # define CLARA_CONFIG_MAIN
56 # endif
57 #endif
58
59 // #included from: internal/catch_notimplemented_exception.h
60 #define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_H_INCLUDED
61
62 // #included from: catch_common.h
63 #define TWOBLUECUBES_CATCH_COMMON_H_INCLUDED
64
65 // #included from: catch_compiler_capabilities.h
66 #define TWOBLUECUBES_CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED
67
68 // Detect a number of compiler features - mostly C++11/14 conformance - by compiler
69 // The following features are defined:
70 //
71 // CATCH_CONFIG_CPP11_NULLPTR : is nullptr supported?
72 // CATCH_CONFIG_CPP11_NOEXCEPT : is noexcept supported?
73 // CATCH_CONFIG_CPP11_GENERATED_METHODS : The delete and default keywords for compiler generated methods
74 // CATCH_CONFIG_CPP11_IS_ENUM : std::is_enum is supported?
75 // CATCH_CONFIG_CPP11_TUPLE : std::tuple is supported
76 // CATCH_CONFIG_CPP11_LONG_LONG : is long long supported?
77 // CATCH_CONFIG_CPP11_OVERRIDE : is override supported?
78 // CATCH_CONFIG_CPP11_UNIQUE_PTR : is unique_ptr supported (otherwise use auto_ptr)
79 // CATCH_CONFIG_CPP11_SHUFFLE : is std::shuffle supported?
80 // CATCH_CONFIG_CPP11_TYPE_TRAITS : are type_traits and enable_if supported?
81
82 // CATCH_CONFIG_CPP11_OR_GREATER : Is C++11 supported?
83
84 // CATCH_CONFIG_VARIADIC_MACROS : are variadic macros supported?
85 // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
86 // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
87 // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
88 // ****************
89 // Note to maintainers: if new toggles are added please document them
90 // in configuration.md, too
91 // ****************
92
93 // In general each macro has a _NO_<feature name> form
94 // (e.g. CATCH_CONFIG_CPP11_NO_NULLPTR) which disables the feature.
95 // Many features, at point of detection, define an _INTERNAL_ macro, so they
96 // can be combined, en-mass, with the _NO_ forms later.
97
98 // All the C++11 features can be disabled with CATCH_CONFIG_NO_CPP11
99
100 #ifdef __cplusplus
101
102 # if __cplusplus >= 201103L
103 # define CATCH_CPP11_OR_GREATER
104 # endif
105
106 # if __cplusplus >= 201402L
107 # define CATCH_CPP14_OR_GREATER
108 # endif
109
110 #endif
111
112 #ifdef __clang__
113
114 # if __has_feature(cxx_nullptr)
115 # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
116 # endif
117
118 # if __has_feature(cxx_noexcept)
119 # define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
120 # endif
121
122 # if defined(CATCH_CPP11_OR_GREATER)
123 # define CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
124 _Pragma( "clang diagnostic push" ) \
125 _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" )
126 # define CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \
127 _Pragma( "clang diagnostic pop" )
128
129 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
130 _Pragma( "clang diagnostic push" ) \
131 _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
132 # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
133 _Pragma( "clang diagnostic pop" )
134 # endif
135
136 #endif // __clang__
137
138 ////////////////////////////////////////////////////////////////////////////////
139 // We know some environments not to support full POSIX signals
140 #if defined(__CYGWIN__) || defined(__QNX__)
141
142 # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
143 # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
144 # endif
145
146 #endif
147
148 ////////////////////////////////////////////////////////////////////////////////
149 // Cygwin
150 #ifdef __CYGWIN__
151
152 // Required for some versions of Cygwin to declare gettimeofday
153 // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
154 # define _BSD_SOURCE
155
156 #endif // __CYGWIN__
157
158 ////////////////////////////////////////////////////////////////////////////////
159 // Borland
160 #ifdef __BORLANDC__
161
162 #endif // __BORLANDC__
163
164 ////////////////////////////////////////////////////////////////////////////////
165 // EDG
166 #ifdef __EDG_VERSION__
167
168 #endif // __EDG_VERSION__
169
170 ////////////////////////////////////////////////////////////////////////////////
171 // Digital Mars
172 #ifdef __DMC__
173
174 #endif // __DMC__
175
176 ////////////////////////////////////////////////////////////////////////////////
177 // GCC
178 #ifdef __GNUC__
179
180 # if __GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__)
181 # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
182 # endif
183
184 // - otherwise more recent versions define __cplusplus >= 201103L
185 // and will get picked up below
186
187 #endif // __GNUC__
188
189 ////////////////////////////////////////////////////////////////////////////////
190 // Visual C++
191 #ifdef _MSC_VER
192
193 #define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
194
195 #if (_MSC_VER >= 1600)
196 # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
197 # define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR
198 #endif
199
200 #if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015))
201 #define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
202 #define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
203 #define CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE
204 #define CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS
205 #endif
206
207 #endif // _MSC_VER
208
209 ////////////////////////////////////////////////////////////////////////////////
210
211 // Use variadic macros if the compiler supports them
212 #if ( defined _MSC_VER && _MSC_VER > 1400 && !defined __EDGE__) || \
213 ( defined __WAVE__ && __WAVE_HAS_VARIADICS ) || \
214 ( defined __GNUC__ && __GNUC__ >= 3 ) || \
215 ( !defined __cplusplus && __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L )
216
217 #define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS
218
219 #endif
220
221 // Use __COUNTER__ if the compiler supports it
222 #if ( defined _MSC_VER && _MSC_VER >= 1300 ) || \
223 ( defined __GNUC__ && ( __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3 )) ) || \
224 ( defined __clang__ && __clang_major__ >= 3 )
225
226 #define CATCH_INTERNAL_CONFIG_COUNTER
227
228 #endif
229
230 ////////////////////////////////////////////////////////////////////////////////
231 // C++ language feature support
232
233 // catch all support for C++11
234 #if defined(CATCH_CPP11_OR_GREATER)
235
236 # if !defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR)
237 # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR
238 # endif
239
240 # ifndef CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
241 # define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT
242 # endif
243
244 # ifndef CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
245 # define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
246 # endif
247
248 # ifndef CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM
249 # define CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM
250 # endif
251
252 # ifndef CATCH_INTERNAL_CONFIG_CPP11_TUPLE
253 # define CATCH_INTERNAL_CONFIG_CPP11_TUPLE
254 # endif
255
256 # ifndef CATCH_INTERNAL_CONFIG_VARIADIC_MACROS
257 # define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS
258 # endif
259
260 # if !defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG)
261 # define CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG
262 # endif
263
264 # if !defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE)
265 # define CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE
266 # endif
267 # if !defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR)
268 # define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR
269 # endif
270 # if !defined(CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE)
271 # define CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE
272 # endif
273 # if !defined(CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS)
274 # define CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS
275 # endif
276
277 #endif // __cplusplus >= 201103L
278
279 // Now set the actual defines based on the above + anything the user has configured
280 #if defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NO_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_NO_CPP11)
281 # define CATCH_CONFIG_CPP11_NULLPTR
282 #endif
283 #if defined(CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_NO_CPP11)
284 # define CATCH_CONFIG_CPP11_NOEXCEPT
285 #endif
286 #if defined(CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_NO_CPP11)
287 # define CATCH_CONFIG_CPP11_GENERATED_METHODS
288 #endif
289 #if defined(CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_NO_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_NO_CPP11)
290 # define CATCH_CONFIG_CPP11_IS_ENUM
291 #endif
292 #if defined(CATCH_INTERNAL_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_CPP11_NO_TUPLE) && !defined(CATCH_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_NO_CPP11)
293 # define CATCH_CONFIG_CPP11_TUPLE
294 #endif
295 #if defined(CATCH_INTERNAL_CONFIG_VARIADIC_MACROS) && !defined(CATCH_CONFIG_NO_VARIADIC_MACROS) && !defined(CATCH_CONFIG_VARIADIC_MACROS)
296 # define CATCH_CONFIG_VARIADIC_MACROS
297 #endif
298 #if defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_CPP11_NO_LONG_LONG) && !defined(CATCH_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_NO_CPP11)
299 # define CATCH_CONFIG_CPP11_LONG_LONG
300 #endif
301 #if defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_CPP11_NO_OVERRIDE) && !defined(CATCH_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_NO_CPP11)
302 # define CATCH_CONFIG_CPP11_OVERRIDE
303 #endif
304 #if defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_NO_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_CPP11)
305 # define CATCH_CONFIG_CPP11_UNIQUE_PTR
306 #endif
307 // Use of __COUNTER__ is suppressed if __JETBRAINS_IDE__ is #defined (meaning we're being parsed by a JetBrains IDE for
308 // analytics) because, at time of writing, __COUNTER__ is not properly handled by it.
309 // This does not affect compilation
310 #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) && !defined(__JETBRAINS_IDE__)
311 # define CATCH_CONFIG_COUNTER
312 #endif
313 #if defined(CATCH_INTERNAL_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_NO_SHUFFLE) && !defined(CATCH_CONFIG_CPP11_SHUFFLE) && !defined(CATCH_CONFIG_NO_CPP11)
314 # define CATCH_CONFIG_CPP11_SHUFFLE
315 #endif
316 # if defined(CATCH_INTERNAL_CONFIG_CPP11_TYPE_TRAITS) && !defined(CATCH_CONFIG_CPP11_NO_TYPE_TRAITS) && !defined(CATCH_CONFIG_CPP11_TYPE_TRAITS) && !defined(CATCH_CONFIG_NO_CPP11)
317 # define CATCH_CONFIG_CPP11_TYPE_TRAITS
318 # endif
319 #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH)
320 # define CATCH_CONFIG_WINDOWS_SEH
321 #endif
322 // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
323 #if !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
324 # define CATCH_CONFIG_POSIX_SIGNALS
325 #endif
326
327 #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
328 # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
329 # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
330 #endif
331 #if !defined(CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS)
332 # define CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS
333 # define CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS
334 #endif
335
336 // noexcept support:
337 #if defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_NOEXCEPT)
338 # define CATCH_NOEXCEPT noexcept
339 # define CATCH_NOEXCEPT_IS(x) noexcept(x)
340 #else
341 # define CATCH_NOEXCEPT throw()
342 # define CATCH_NOEXCEPT_IS(x)
343 #endif
344
345 // nullptr support
346 #ifdef CATCH_CONFIG_CPP11_NULLPTR
347 # define CATCH_NULL nullptr
348 #else
349 # define CATCH_NULL NULL
350 #endif
351
352 // override support
353 #ifdef CATCH_CONFIG_CPP11_OVERRIDE
354 # define CATCH_OVERRIDE override
355 #else
356 # define CATCH_OVERRIDE
357 #endif
358
359 // unique_ptr support
360 #ifdef CATCH_CONFIG_CPP11_UNIQUE_PTR
361 # define CATCH_AUTO_PTR( T ) std::unique_ptr<T>
362 #else
363 # define CATCH_AUTO_PTR( T ) std::auto_ptr<T>
364 #endif
365
366 #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
367 #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
368 #ifdef CATCH_CONFIG_COUNTER
369 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
370 #else
371 # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
372 #endif
373
374 #define INTERNAL_CATCH_STRINGIFY2( expr ) #expr
375 #define INTERNAL_CATCH_STRINGIFY( expr ) INTERNAL_CATCH_STRINGIFY2( expr )
376
377 #include <sstream>
378 #include <algorithm>
379
380 namespace Catch {
381
382 struct IConfig;
383
384 struct CaseSensitive { enum Choice {
385 Yes,
386 No
387 }; };
388
389 class NonCopyable {
390 #ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
391 NonCopyable( NonCopyable const& ) = delete;
392 NonCopyable( NonCopyable && ) = delete;
393 NonCopyable& operator = ( NonCopyable const& ) = delete;
394 NonCopyable& operator = ( NonCopyable && ) = delete;
395 #else
396 NonCopyable( NonCopyable const& info );
397 NonCopyable& operator = ( NonCopyable const& );
398 #endif
399
400 protected:
401 NonCopyable() {}
402 virtual ~NonCopyable();
403 };
404
405 class SafeBool {
406 public:
407 typedef void (SafeBool::*type)() const;
408
409 static type makeSafe( bool value ) {
410 return value ? &SafeBool::trueValue : 0;
411 }
412 private:
413 void trueValue() const {}
414 };
415
416 template<typename ContainerT>
417 inline void deleteAll( ContainerT& container ) {
418 typename ContainerT::const_iterator it = container.begin();
419 typename ContainerT::const_iterator itEnd = container.end();
420 for(; it != itEnd; ++it )
421 delete *it;
422 }
423 template<typename AssociativeContainerT>
424 inline void deleteAllValues( AssociativeContainerT& container ) {
425 typename AssociativeContainerT::const_iterator it = container.begin();
426 typename AssociativeContainerT::const_iterator itEnd = container.end();
427 for(; it != itEnd; ++it )
428 delete it->second;
429 }
430
431 bool startsWith( std::string const& s, std::string const& prefix );
432 bool startsWith( std::string const& s, char prefix );
433 bool endsWith( std::string const& s, std::string const& suffix );
434 bool endsWith( std::string const& s, char suffix );
435 bool contains( std::string const& s, std::string const& infix );
436 void toLowerInPlace( std::string& s );
437 std::string toLower( std::string const& s );
438 std::string trim( std::string const& str );
439 bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
440
441 struct pluralise {
442 pluralise( std::size_t count, std::string const& label );
443
444 friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
445
446 std::size_t m_count;
447 std::string m_label;
448 };
449
450 struct SourceLineInfo {
451
452 SourceLineInfo();
453 SourceLineInfo( char const* _file, std::size_t _line );
454 # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
455 SourceLineInfo(SourceLineInfo const& other) = default;
456 SourceLineInfo( SourceLineInfo && ) = default;
457 SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
458 SourceLineInfo& operator = ( SourceLineInfo && ) = default;
459 # endif
460 bool empty() const;
461 bool operator == ( SourceLineInfo const& other ) const;
462 bool operator < ( SourceLineInfo const& other ) const;
463
464 char const* file;
465 std::size_t line;
466 };
467
468 std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
469
470 // This is just here to avoid compiler warnings with macro constants and boolean literals
471 inline bool isTrue( bool value ){ return value; }
472 inline bool alwaysTrue() { return true; }
473 inline bool alwaysFalse() { return false; }
474
475 void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo );
476
477 void seedRng( IConfig const& config );
478 unsigned int rngSeed();
479
480 // Use this in variadic streaming macros to allow
481 // >> +StreamEndStop
482 // as well as
483 // >> stuff +StreamEndStop
484 struct StreamEndStop {
485 std::string operator+() {
486 return std::string();
487 }
488 };
489 template<typename T>
490 T const& operator + ( T const& value, StreamEndStop ) {
491 return value;
492 }
493 }
494
495 #define CATCH_INTERNAL_LINEINFO ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
496 #define CATCH_INTERNAL_ERROR( msg ) ::Catch::throwLogicError( msg, CATCH_INTERNAL_LINEINFO );
497
498 namespace Catch {
499
500 class NotImplementedException : public std::exception
501 {
502 public:
503 NotImplementedException( SourceLineInfo const& lineInfo );
504 NotImplementedException( NotImplementedException const& ) {}
505
506 virtual ~NotImplementedException() CATCH_NOEXCEPT {}
507
508 virtual const char* what() const CATCH_NOEXCEPT;
509
510 private:
511 std::string m_what;
512 SourceLineInfo m_lineInfo;
513 };
514
515 } // end namespace Catch
516
517 ///////////////////////////////////////////////////////////////////////////////
518 #define CATCH_NOT_IMPLEMENTED throw Catch::NotImplementedException( CATCH_INTERNAL_LINEINFO )
519
520 // #included from: internal/catch_context.h
521 #define TWOBLUECUBES_CATCH_CONTEXT_H_INCLUDED
522
523 // #included from: catch_interfaces_generators.h
524 #define TWOBLUECUBES_CATCH_INTERFACES_GENERATORS_H_INCLUDED
525
526 #include <string>
527
528 namespace Catch {
529
530 struct IGeneratorInfo {
531 virtual ~IGeneratorInfo();
532 virtual bool moveNext() = 0;
533 virtual std::size_t getCurrentIndex() const = 0;
534 };
535
536 struct IGeneratorsForTest {
537 virtual ~IGeneratorsForTest();
538
539 virtual IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) = 0;
540 virtual bool moveNext() = 0;
541 };
542
543 IGeneratorsForTest* createGeneratorsForTest();
544
545 } // end namespace Catch
546
547 // #included from: catch_ptr.hpp
548 #define TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED
549
550 #ifdef __clang__
551 #pragma clang diagnostic push
552 #pragma clang diagnostic ignored "-Wpadded"
553 #endif
554
555 namespace Catch {
556
557 // An intrusive reference counting smart pointer.
558 // T must implement addRef() and release() methods
559 // typically implementing the IShared interface
560 template<typename T>
561 class Ptr {
562 public:
563 Ptr() : m_p( CATCH_NULL ){}
564 Ptr( T* p ) : m_p( p ){
565 if( m_p )
566 m_p->addRef();
567 }
568 Ptr( Ptr const& other ) : m_p( other.m_p ){
569 if( m_p )
570 m_p->addRef();
571 }
572 ~Ptr(){
573 if( m_p )
574 m_p->release();
575 }
576 void reset() {
577 if( m_p )
578 m_p->release();
579 m_p = CATCH_NULL;
580 }
581 Ptr& operator = ( T* p ){
582 Ptr temp( p );
583 swap( temp );
584 return *this;
585 }
586 Ptr& operator = ( Ptr const& other ){
587 Ptr temp( other );
588 swap( temp );
589 return *this;
590 }
591 void swap( Ptr& other ) { std::swap( m_p, other.m_p ); }
592 T* get() const{ return m_p; }
593 T& operator*() const { return *m_p; }
594 T* operator->() const { return m_p; }
595 bool operator !() const { return m_p == CATCH_NULL; }
596 operator SafeBool::type() const { return SafeBool::makeSafe( m_p != CATCH_NULL ); }
597
598 private:
599 T* m_p;
600 };
601
602 struct IShared : NonCopyable {
603 virtual ~IShared();
604 virtual void addRef() const = 0;
605 virtual void release() const = 0;
606 };
607
608 template<typename T = IShared>
609 struct SharedImpl : T {
610
611 SharedImpl() : m_rc( 0 ){}
612
613 virtual void addRef() const {
614 ++m_rc;
615 }
616 virtual void release() const {
617 if( --m_rc == 0 )
618 delete this;
619 }
620
621 mutable unsigned int m_rc;
622 };
623
624 } // end namespace Catch
625
626 #ifdef __clang__
627 #pragma clang diagnostic pop
628 #endif
629
630 namespace Catch {
631
632 class TestCase;
633 class Stream;
634 struct IResultCapture;
635 struct IRunner;
636 struct IGeneratorsForTest;
637 struct IConfig;
638
639 struct IContext
640 {
641 virtual ~IContext();
642
643 virtual IResultCapture* getResultCapture() = 0;
644 virtual IRunner* getRunner() = 0;
645 virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) = 0;
646 virtual bool advanceGeneratorsForCurrentTest() = 0;
647 virtual Ptr<IConfig const> getConfig() const = 0;
648 };
649
650 struct IMutableContext : IContext
651 {
652 virtual ~IMutableContext();
653 virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
654 virtual void setRunner( IRunner* runner ) = 0;
655 virtual void setConfig( Ptr<IConfig const> const& config ) = 0;
656 };
657
658 IContext& getCurrentContext();
659 IMutableContext& getCurrentMutableContext();
660 void cleanUpContext();
661 Stream createStream( std::string const& streamName );
662
663 }
664
665 // #included from: internal/catch_test_registry.hpp
666 #define TWOBLUECUBES_CATCH_TEST_REGISTRY_HPP_INCLUDED
667
668 // #included from: catch_interfaces_testcase.h
669 #define TWOBLUECUBES_CATCH_INTERFACES_TESTCASE_H_INCLUDED
670
671 #include <vector>
672
673 namespace Catch {
674
675 class TestSpec;
676
677 struct ITestCase : IShared {
678 virtual void invoke () const = 0;
679 protected:
680 virtual ~ITestCase();
681 };
682
683 class TestCase;
684 struct IConfig;
685
686 struct ITestCaseRegistry {
687 virtual ~ITestCaseRegistry();
688 virtual std::vector<TestCase> const& getAllTests() const = 0;
689 virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
690 };
691
692 bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
693 std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
694 std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
695
696 }
697
698 namespace Catch {
699
700 template<typename C>
701 class MethodTestCase : public SharedImpl<ITestCase> {
702
703 public:
704 MethodTestCase( void (C::*method)() ) : m_method( method ) {}
705
706 virtual void invoke() const {
707 C obj;
708 (obj.*m_method)();
709 }
710
711 private:
712 virtual ~MethodTestCase() {}
713
714 void (C::*m_method)();
715 };
716
717 typedef void(*TestFunction)();
718
719 struct NameAndDesc {
720 NameAndDesc( const char* _name = "", const char* _description= "" )
721 : name( _name ), description( _description )
722 {}
723
724 const char* name;
725 const char* description;
726 };
727
728 void registerTestCase
729 ( ITestCase* testCase,
730 char const* className,
731 NameAndDesc const& nameAndDesc,
732 SourceLineInfo const& lineInfo );
733
734 struct AutoReg {
735
736 AutoReg
737 ( TestFunction function,
738 SourceLineInfo const& lineInfo,
739 NameAndDesc const& nameAndDesc );
740
741 template<typename C>
742 AutoReg
743 ( void (C::*method)(),
744 char const* className,
745 NameAndDesc const& nameAndDesc,
746 SourceLineInfo const& lineInfo ) {
747
748 registerTestCase
749 ( new MethodTestCase<C>( method ),
750 className,
751 nameAndDesc,
752 lineInfo );
753 }
754
755 ~AutoReg();
756
757 private:
758 AutoReg( AutoReg const& );
759 void operator= ( AutoReg const& );
760 };
761
762 void registerTestCaseFunction
763 ( TestFunction function,
764 SourceLineInfo const& lineInfo,
765 NameAndDesc const& nameAndDesc );
766
767 } // end namespace Catch
768
769 #ifdef CATCH_CONFIG_VARIADIC_MACROS
770 ///////////////////////////////////////////////////////////////////////////////
771 #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
772 static void TestName(); \
773 CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
774 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); } \
775 CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \
776 static void TestName()
777 #define INTERNAL_CATCH_TESTCASE( ... ) \
778 INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
779
780 ///////////////////////////////////////////////////////////////////////////////
781 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
782 CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
783 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); } \
784 CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS
785
786 ///////////////////////////////////////////////////////////////////////////////
787 #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
788 CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
789 namespace{ \
790 struct TestName : ClassName{ \
791 void test(); \
792 }; \
793 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestName::test, #ClassName, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); \
794 } \
795 CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \
796 void TestName::test()
797 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
798 INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
799
800 ///////////////////////////////////////////////////////////////////////////////
801 #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
802 CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
803 Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); \
804 CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS
805
806 #else
807 ///////////////////////////////////////////////////////////////////////////////
808 #define INTERNAL_CATCH_TESTCASE2( TestName, Name, Desc ) \
809 static void TestName(); \
810 CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
811 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); }\
812 CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \
813 static void TestName()
814 #define INTERNAL_CATCH_TESTCASE( Name, Desc ) \
815 INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), Name, Desc )
816
817 ///////////////////////////////////////////////////////////////////////////////
818 #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, Name, Desc ) \
819 CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
820 namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, "&" #QualifiedMethod, Catch::NameAndDesc( Name, Desc ), CATCH_INTERNAL_LINEINFO ); } \
821 CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS
822
823 ///////////////////////////////////////////////////////////////////////////////
824 #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestCaseName, ClassName, TestName, Desc )\
825 CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
826 namespace{ \
827 struct TestCaseName : ClassName{ \
828 void test(); \
829 }; \
830 Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestCaseName::test, #ClassName, Catch::NameAndDesc( TestName, Desc ), CATCH_INTERNAL_LINEINFO ); \
831 } \
832 CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS \
833 void TestCaseName::test()
834 #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, TestName, Desc )\
835 INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, TestName, Desc )
836
837 ///////////////////////////////////////////////////////////////////////////////
838 #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, Name, Desc ) \
839 CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS \
840 Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); \
841 CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS
842
843 #endif
844
845 // #included from: internal/catch_capture.hpp
846 #define TWOBLUECUBES_CATCH_CAPTURE_HPP_INCLUDED
847
848 // #included from: catch_result_builder.h
849 #define TWOBLUECUBES_CATCH_RESULT_BUILDER_H_INCLUDED
850
851 // #included from: catch_result_type.h
852 #define TWOBLUECUBES_CATCH_RESULT_TYPE_H_INCLUDED
853
854 namespace Catch {
855
856 // ResultWas::OfType enum
857 struct ResultWas { enum OfType {
858 Unknown = -1,
859 Ok = 0,
860 Info = 1,
861 Warning = 2,
862
863 FailureBit = 0x10,
864
865 ExpressionFailed = FailureBit | 1,
866 ExplicitFailure = FailureBit | 2,
867
868 Exception = 0x100 | FailureBit,
869
870 ThrewException = Exception | 1,
871 DidntThrowException = Exception | 2,
872
873 FatalErrorCondition = 0x200 | FailureBit
874
875 }; };
876
877 inline bool isOk( ResultWas::OfType resultType ) {
878 return ( resultType & ResultWas::FailureBit ) == 0;
879 }
880 inline bool isJustInfo( int flags ) {
881 return flags == ResultWas::Info;
882 }
883
884 // ResultDisposition::Flags enum
885 struct ResultDisposition { enum Flags {
886 Normal = 0x01,
887
888 ContinueOnFailure = 0x02, // Failures fail test, but execution continues
889 FalseTest = 0x04, // Prefix expression with !
890 SuppressFail = 0x08 // Failures are reported but do not fail the test
891 }; };
892
893 inline ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
894 return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
895 }
896
897 inline bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
898 inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
899 inline bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
900
901 } // end namespace Catch
902
903 // #included from: catch_assertionresult.h
904 #define TWOBLUECUBES_CATCH_ASSERTIONRESULT_H_INCLUDED
905
906 #include <string>
907
908 namespace Catch {
909
910 struct STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison;
911
912 struct DecomposedExpression
913 {
914 virtual ~DecomposedExpression() {}
915 virtual bool isBinaryExpression() const {
916 return false;
917 }
918 virtual void reconstructExpression( std::string& dest ) const = 0;
919
920 // Only simple binary comparisons can be decomposed.
921 // If more complex check is required then wrap sub-expressions in parentheses.
922 template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator + ( T const& );
923 template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator - ( T const& );
924 template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator * ( T const& );
925 template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator / ( T const& );
926 template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator % ( T const& );
927 template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( T const& );
928 template<typename T> STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( T const& );
929
930 private:
931 DecomposedExpression& operator = (DecomposedExpression const&);
932 };
933
934 struct AssertionInfo
935 {
936 AssertionInfo() {}
937 AssertionInfo( char const * _macroName,
938 SourceLineInfo const& _lineInfo,
939 char const * _capturedExpression,
940 ResultDisposition::Flags _resultDisposition,
941 char const * _secondArg = "");
942
943 char const * macroName;
944 SourceLineInfo lineInfo;
945 char const * capturedExpression;
946 ResultDisposition::Flags resultDisposition;
947 char const * secondArg;
948 };
949
950 struct AssertionResultData
951 {
952 AssertionResultData() : decomposedExpression( CATCH_NULL )
953 , resultType( ResultWas::Unknown )
954 , negated( false )
955 , parenthesized( false ) {}
956
957 void negate( bool parenthesize ) {
958 negated = !negated;
959 parenthesized = parenthesize;
960 if( resultType == ResultWas::Ok )
961 resultType = ResultWas::ExpressionFailed;
962 else if( resultType == ResultWas::ExpressionFailed )
963 resultType = ResultWas::Ok;
964 }
965
966 std::string const& reconstructExpression() const {
967 if( decomposedExpression != CATCH_NULL ) {
968 decomposedExpression->reconstructExpression( reconstructedExpression );
969 if( parenthesized ) {
970 reconstructedExpression.insert( 0, 1, '(' );
971 reconstructedExpression.append( 1, ')' );
972 }
973 if( negated ) {
974 reconstructedExpression.insert( 0, 1, '!' );
975 }
976 decomposedExpression = CATCH_NULL;
977 }
978 return reconstructedExpression;
979 }
980
981 mutable DecomposedExpression const* decomposedExpression;
982 mutable std::string reconstructedExpression;
983 std::string message;
984 ResultWas::OfType resultType;
985 bool negated;
986 bool parenthesized;
987 };
988
989 class AssertionResult {
990 public:
991 AssertionResult();
992 AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
993 ~AssertionResult();
994 # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
995 AssertionResult( AssertionResult const& ) = default;
996 AssertionResult( AssertionResult && ) = default;
997 AssertionResult& operator = ( AssertionResult const& ) = default;
998 AssertionResult& operator = ( AssertionResult && ) = default;
999 # endif
1000
1001 bool isOk() const;
1002 bool succeeded() const;
1003 ResultWas::OfType getResultType() const;
1004 bool hasExpression() const;
1005 bool hasMessage() const;
1006 std::string getExpression() const;
1007 std::string getExpressionInMacro() const;
1008 bool hasExpandedExpression() const;
1009 std::string getExpandedExpression() const;
1010 std::string getMessage() const;
1011 SourceLineInfo getSourceInfo() const;
1012 std::string getTestMacroName() const;
1013 void discardDecomposedExpression() const;
1014 void expandDecomposedExpression() const;
1015
1016 protected:
1017 AssertionInfo m_info;
1018 AssertionResultData m_resultData;
1019 };
1020
1021 } // end namespace Catch
1022
1023 // #included from: catch_matchers.hpp
1024 #define TWOBLUECUBES_CATCH_MATCHERS_HPP_INCLUDED
1025
1026 namespace Catch {
1027 namespace Matchers {
1028 namespace Impl {
1029
1030 template<typename ArgT> struct MatchAllOf;
1031 template<typename ArgT> struct MatchAnyOf;
1032 template<typename ArgT> struct MatchNotOf;
1033
1034 class MatcherUntypedBase {
1035 public:
1036 std::string toString() const {
1037 if( m_cachedToString.empty() )
1038 m_cachedToString = describe();
1039 return m_cachedToString;
1040 }
1041
1042 protected:
1043 virtual ~MatcherUntypedBase();
1044 virtual std::string describe() const = 0;
1045 mutable std::string m_cachedToString;
1046 private:
1047 MatcherUntypedBase& operator = ( MatcherUntypedBase const& );
1048 };
1049
1050 template<typename ObjectT>
1051 struct MatcherMethod {
1052 virtual bool match( ObjectT const& arg ) const = 0;
1053 };
1054 template<typename PtrT>
1055 struct MatcherMethod<PtrT*> {
1056 virtual bool match( PtrT* arg ) const = 0;
1057 };
1058
1059 template<typename ObjectT, typename ComparatorT = ObjectT>
1060 struct MatcherBase : MatcherUntypedBase, MatcherMethod<ObjectT> {
1061
1062 MatchAllOf<ComparatorT> operator && ( MatcherBase const& other ) const;
1063 MatchAnyOf<ComparatorT> operator || ( MatcherBase const& other ) const;
1064 MatchNotOf<ComparatorT> operator ! () const;
1065 };
1066
1067 template<typename ArgT>
1068 struct MatchAllOf : MatcherBase<ArgT> {
1069 virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE {
1070 for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
1071 if (!m_matchers[i]->match(arg))
1072 return false;
1073 }
1074 return true;
1075 }
1076 virtual std::string describe() const CATCH_OVERRIDE {
1077 std::string description;
1078 description.reserve( 4 + m_matchers.size()*32 );
1079 description += "( ";
1080 for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
1081 if( i != 0 )
1082 description += " and ";
1083 description += m_matchers[i]->toString();
1084 }
1085 description += " )";
1086 return description;
1087 }
1088
1089 MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
1090 m_matchers.push_back( &other );
1091 return *this;
1092 }
1093
1094 std::vector<MatcherBase<ArgT> const*> m_matchers;
1095 };
1096 template<typename ArgT>
1097 struct MatchAnyOf : MatcherBase<ArgT> {
1098
1099 virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE {
1100 for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
1101 if (m_matchers[i]->match(arg))
1102 return true;
1103 }
1104 return false;
1105 }
1106 virtual std::string describe() const CATCH_OVERRIDE {
1107 std::string description;
1108 description.reserve( 4 + m_matchers.size()*32 );
1109 description += "( ";
1110 for( std::size_t i = 0; i < m_matchers.size(); ++i ) {
1111 if( i != 0 )
1112 description += " or ";
1113 description += m_matchers[i]->toString();
1114 }
1115 description += " )";
1116 return description;
1117 }
1118
1119 MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
1120 m_matchers.push_back( &other );
1121 return *this;
1122 }
1123
1124 std::vector<MatcherBase<ArgT> const*> m_matchers;
1125 };
1126
1127 template<typename ArgT>
1128 struct MatchNotOf : MatcherBase<ArgT> {
1129
1130 MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
1131
1132 virtual bool match( ArgT const& arg ) const CATCH_OVERRIDE {
1133 return !m_underlyingMatcher.match( arg );
1134 }
1135
1136 virtual std::string describe() const CATCH_OVERRIDE {
1137 return "not " + m_underlyingMatcher.toString();
1138 }
1139 MatcherBase<ArgT> const& m_underlyingMatcher;
1140 };
1141
1142 template<typename ObjectT, typename ComparatorT>
1143 MatchAllOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator && ( MatcherBase const& other ) const {
1144 return MatchAllOf<ComparatorT>() && *this && other;
1145 }
1146 template<typename ObjectT, typename ComparatorT>
1147 MatchAnyOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator || ( MatcherBase const& other ) const {
1148 return MatchAnyOf<ComparatorT>() || *this || other;
1149 }
1150 template<typename ObjectT, typename ComparatorT>
1151 MatchNotOf<ComparatorT> MatcherBase<ObjectT, ComparatorT>::operator ! () const {
1152 return MatchNotOf<ComparatorT>( *this );
1153 }
1154
1155 } // namespace Impl
1156
1157 // The following functions create the actual matcher objects.
1158 // This allows the types to be inferred
1159 // - deprecated: prefer ||, && and !
1160 template<typename T>
1161 inline Impl::MatchNotOf<T> Not( Impl::MatcherBase<T> const& underlyingMatcher ) {
1162 return Impl::MatchNotOf<T>( underlyingMatcher );
1163 }
1164 template<typename T>
1165 inline Impl::MatchAllOf<T> AllOf( Impl::MatcherBase<T> const& m1, Impl::MatcherBase<T> const& m2 ) {
1166 return Impl::MatchAllOf<T>() && m1 && m2;
1167 }
1168 template<typename T>
1169 inline Impl::MatchAllOf<T> AllOf( Impl::MatcherBase<T> const& m1, Impl::MatcherBase<T> const& m2, Impl::MatcherBase<T> const& m3 ) {
1170 return Impl::MatchAllOf<T>() && m1 && m2 && m3;
1171 }
1172 template<typename T>
1173 inline Impl::MatchAnyOf<T> AnyOf( Impl::MatcherBase<T> const& m1, Impl::MatcherBase<T> const& m2 ) {
1174 return Impl::MatchAnyOf<T>() || m1 || m2;
1175 }
1176 template<typename T>
1177 inline Impl::MatchAnyOf<T> AnyOf( Impl::MatcherBase<T> const& m1, Impl::MatcherBase<T> const& m2, Impl::MatcherBase<T> const& m3 ) {
1178 return Impl::MatchAnyOf<T>() || m1 || m2 || m3;
1179 }
1180
1181 } // namespace Matchers
1182
1183 using namespace Matchers;
1184 using Matchers::Impl::MatcherBase;
1185
1186 } // namespace Catch
1187
1188 namespace Catch {
1189
1190 struct TestFailureException{};
1191
1192 template<typename T> class ExpressionLhs;
1193
1194 struct CopyableStream {
1195 CopyableStream() {}
1196 CopyableStream( CopyableStream const& other ) {
1197 oss << other.oss.str();
1198 }
1199 CopyableStream& operator=( CopyableStream const& other ) {
1200 oss.str(std::string());
1201 oss << other.oss.str();
1202 return *this;
1203 }
1204 std::ostringstream oss;
1205 };
1206
1207 class ResultBuilder : public DecomposedExpression {
1208 public:
1209 ResultBuilder( char const* macroName,
1210 SourceLineInfo const& lineInfo,
1211 char const* capturedExpression,
1212 ResultDisposition::Flags resultDisposition,
1213 char const* secondArg = "" );
1214 ~ResultBuilder();
1215
1216 template<typename T>
1217 ExpressionLhs<T const&> operator <= ( T const& operand );
1218 ExpressionLhs<bool> operator <= ( bool value );
1219
1220 template<typename T>
1221 ResultBuilder& operator << ( T const& value ) {
1222 m_stream().oss << value;
1223 return *this;
1224 }
1225
1226 ResultBuilder& setResultType( ResultWas::OfType result );
1227 ResultBuilder& setResultType( bool result );
1228
1229 void endExpression( DecomposedExpression const& expr );
1230
1231 virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE;
1232
1233 AssertionResult build() const;
1234 AssertionResult build( DecomposedExpression const& expr ) const;
1235
1236 void useActiveException( ResultDisposition::Flags resultDisposition = ResultDisposition::Normal );
1237 void captureResult( ResultWas::OfType resultType );
1238 void captureExpression();
1239 void captureExpectedException( std::string const& expectedMessage );
1240 void captureExpectedException( Matchers::Impl::MatcherBase<std::string> const& matcher );
1241 void handleResult( AssertionResult const& result );
1242 void react();
1243 bool shouldDebugBreak() const;
1244 bool allowThrows() const;
1245
1246 template<typename ArgT, typename MatcherT>
1247 void captureMatch( ArgT const& arg, MatcherT const& matcher, char const* matcherString );
1248
1249 void setExceptionGuard();
1250 void unsetExceptionGuard();
1251
1252 private:
1253 AssertionInfo m_assertionInfo;
1254 AssertionResultData m_data;
1255
1256 static CopyableStream &m_stream()
1257 {
1258 static CopyableStream s;
1259 return s;
1260 }
1261
1262 bool m_shouldDebugBreak;
1263 bool m_shouldThrow;
1264 bool m_guardException;
1265 };
1266
1267 } // namespace Catch
1268
1269 // Include after due to circular dependency:
1270 // #included from: catch_expression_lhs.hpp
1271 #define TWOBLUECUBES_CATCH_EXPRESSION_LHS_HPP_INCLUDED
1272
1273 // #included from: catch_evaluate.hpp
1274 #define TWOBLUECUBES_CATCH_EVALUATE_HPP_INCLUDED
1275
1276 #ifdef _MSC_VER
1277 #pragma warning(push)
1278 #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
1279 #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
1280 #endif
1281
1282 #include <cstddef>
1283
1284 namespace Catch {
1285 namespace Internal {
1286
1287 enum Operator {
1288 IsEqualTo,
1289 IsNotEqualTo,
1290 IsLessThan,
1291 IsGreaterThan,
1292 IsLessThanOrEqualTo,
1293 IsGreaterThanOrEqualTo
1294 };
1295
1296 template<Operator Op> struct OperatorTraits { static const char* getName(){ return "*error*"; } };
1297 template<> struct OperatorTraits<IsEqualTo> { static const char* getName(){ return "=="; } };
1298 template<> struct OperatorTraits<IsNotEqualTo> { static const char* getName(){ return "!="; } };
1299 template<> struct OperatorTraits<IsLessThan> { static const char* getName(){ return "<"; } };
1300 template<> struct OperatorTraits<IsGreaterThan> { static const char* getName(){ return ">"; } };
1301 template<> struct OperatorTraits<IsLessThanOrEqualTo> { static const char* getName(){ return "<="; } };
1302 template<> struct OperatorTraits<IsGreaterThanOrEqualTo>{ static const char* getName(){ return ">="; } };
1303
1304 template<typename T>
1305 inline T& opCast(T const& t) { return const_cast<T&>(t); }
1306
1307 // nullptr_t support based on pull request #154 from Konstantin Baumann
1308 #ifdef CATCH_CONFIG_CPP11_NULLPTR
1309 inline std::nullptr_t opCast(std::nullptr_t) { return nullptr; }
1310 #endif // CATCH_CONFIG_CPP11_NULLPTR
1311
1312 // So the compare overloads can be operator agnostic we convey the operator as a template
1313 // enum, which is used to specialise an Evaluator for doing the comparison.
1314 template<typename T1, typename T2, Operator Op>
1315 class Evaluator{};
1316
1317 template<typename T1, typename T2>
1318 struct Evaluator<T1, T2, IsEqualTo> {
1319 static bool evaluate( T1 const& lhs, T2 const& rhs) {
1320 return bool( opCast( lhs ) == opCast( rhs ) );
1321 }
1322 };
1323 template<typename T1, typename T2>
1324 struct Evaluator<T1, T2, IsNotEqualTo> {
1325 static bool evaluate( T1 const& lhs, T2 const& rhs ) {
1326 return bool( opCast( lhs ) != opCast( rhs ) );
1327 }
1328 };
1329 template<typename T1, typename T2>
1330 struct Evaluator<T1, T2, IsLessThan> {
1331 static bool evaluate( T1 const& lhs, T2 const& rhs ) {
1332 return bool( opCast( lhs ) < opCast( rhs ) );
1333 }
1334 };
1335 template<typename T1, typename T2>
1336 struct Evaluator<T1, T2, IsGreaterThan> {
1337 static bool evaluate( T1 const& lhs, T2 const& rhs ) {
1338 return bool( opCast( lhs ) > opCast( rhs ) );
1339 }
1340 };
1341 template<typename T1, typename T2>
1342 struct Evaluator<T1, T2, IsGreaterThanOrEqualTo> {
1343 static bool evaluate( T1 const& lhs, T2 const& rhs ) {
1344 return bool( opCast( lhs ) >= opCast( rhs ) );
1345 }
1346 };
1347 template<typename T1, typename T2>
1348 struct Evaluator<T1, T2, IsLessThanOrEqualTo> {
1349 static bool evaluate( T1 const& lhs, T2 const& rhs ) {
1350 return bool( opCast( lhs ) <= opCast( rhs ) );
1351 }
1352 };
1353
1354 template<Operator Op, typename T1, typename T2>
1355 bool applyEvaluator( T1 const& lhs, T2 const& rhs ) {
1356 return Evaluator<T1, T2, Op>::evaluate( lhs, rhs );
1357 }
1358
1359 // This level of indirection allows us to specialise for integer types
1360 // to avoid signed/ unsigned warnings
1361
1362 // "base" overload
1363 template<Operator Op, typename T1, typename T2>
1364 bool compare( T1 const& lhs, T2 const& rhs ) {
1365 return Evaluator<T1, T2, Op>::evaluate( lhs, rhs );
1366 }
1367
1368 // unsigned X to int
1369 template<Operator Op> bool compare( unsigned int lhs, int rhs ) {
1370 return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) );
1371 }
1372 template<Operator Op> bool compare( unsigned long lhs, int rhs ) {
1373 return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) );
1374 }
1375 template<Operator Op> bool compare( unsigned char lhs, int rhs ) {
1376 return applyEvaluator<Op>( lhs, static_cast<unsigned int>( rhs ) );
1377 }
1378
1379 // unsigned X to long
1380 template<Operator Op> bool compare( unsigned int lhs, long rhs ) {
1381 return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) );
1382 }
1383 template<Operator Op> bool compare( unsigned long lhs, long rhs ) {
1384 return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) );
1385 }
1386 template<Operator Op> bool compare( unsigned char lhs, long rhs ) {
1387 return applyEvaluator<Op>( lhs, static_cast<unsigned long>( rhs ) );
1388 }
1389
1390 // int to unsigned X
1391 template<Operator Op> bool compare( int lhs, unsigned int rhs ) {
1392 return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs );
1393 }
1394 template<Operator Op> bool compare( int lhs, unsigned long rhs ) {
1395 return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs );
1396 }
1397 template<Operator Op> bool compare( int lhs, unsigned char rhs ) {
1398 return applyEvaluator<Op>( static_cast<unsigned int>( lhs ), rhs );
1399 }
1400
1401 // long to unsigned X
1402 template<Operator Op> bool compare( long lhs, unsigned int rhs ) {
1403 return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
1404 }
1405 template<Operator Op> bool compare( long lhs, unsigned long rhs ) {
1406 return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
1407 }
1408 template<Operator Op> bool compare( long lhs, unsigned char rhs ) {
1409 return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
1410 }
1411
1412 // pointer to long (when comparing against NULL)
1413 template<Operator Op, typename T> bool compare( long lhs, T* rhs ) {
1414 return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs );
1415 }
1416 template<Operator Op, typename T> bool compare( T* lhs, long rhs ) {
1417 return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) );
1418 }
1419
1420 // pointer to int (when comparing against NULL)
1421 template<Operator Op, typename T> bool compare( int lhs, T* rhs ) {
1422 return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs );
1423 }
1424 template<Operator Op, typename T> bool compare( T* lhs, int rhs ) {
1425 return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) );
1426 }
1427
1428 #ifdef CATCH_CONFIG_CPP11_LONG_LONG
1429 // long long to unsigned X
1430 template<Operator Op> bool compare( long long lhs, unsigned int rhs ) {
1431 return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
1432 }
1433 template<Operator Op> bool compare( long long lhs, unsigned long rhs ) {
1434 return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
1435 }
1436 template<Operator Op> bool compare( long long lhs, unsigned long long rhs ) {
1437 return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
1438 }
1439 template<Operator Op> bool compare( long long lhs, unsigned char rhs ) {
1440 return applyEvaluator<Op>( static_cast<unsigned long>( lhs ), rhs );
1441 }
1442
1443 // unsigned long long to X
1444 template<Operator Op> bool compare( unsigned long long lhs, int rhs ) {
1445 return applyEvaluator<Op>( static_cast<long>( lhs ), rhs );
1446 }
1447 template<Operator Op> bool compare( unsigned long long lhs, long rhs ) {
1448 return applyEvaluator<Op>( static_cast<long>( lhs ), rhs );
1449 }
1450 template<Operator Op> bool compare( unsigned long long lhs, long long rhs ) {
1451 return applyEvaluator<Op>( static_cast<long>( lhs ), rhs );
1452 }
1453 template<Operator Op> bool compare( unsigned long long lhs, char rhs ) {
1454 return applyEvaluator<Op>( static_cast<long>( lhs ), rhs );
1455 }
1456
1457 // pointer to long long (when comparing against NULL)
1458 template<Operator Op, typename T> bool compare( long long lhs, T* rhs ) {
1459 return Evaluator<T*, T*, Op>::evaluate( reinterpret_cast<T*>( lhs ), rhs );
1460 }
1461 template<Operator Op, typename T> bool compare( T* lhs, long long rhs ) {
1462 return Evaluator<T*, T*, Op>::evaluate( lhs, reinterpret_cast<T*>( rhs ) );
1463 }
1464 #endif // CATCH_CONFIG_CPP11_LONG_LONG
1465
1466 #ifdef CATCH_CONFIG_CPP11_NULLPTR
1467 // pointer to nullptr_t (when comparing against nullptr)
1468 template<Operator Op, typename T> bool compare( std::nullptr_t, T* rhs ) {
1469 return Evaluator<T*, T*, Op>::evaluate( nullptr, rhs );
1470 }
1471 template<Operator Op, typename T> bool compare( T* lhs, std::nullptr_t ) {
1472 return Evaluator<T*, T*, Op>::evaluate( lhs, nullptr );
1473 }
1474 #endif // CATCH_CONFIG_CPP11_NULLPTR
1475
1476 } // end of namespace Internal
1477 } // end of namespace Catch
1478
1479 #ifdef _MSC_VER
1480 #pragma warning(pop)
1481 #endif
1482
1483 // #included from: catch_tostring.h
1484 #define TWOBLUECUBES_CATCH_TOSTRING_H_INCLUDED
1485
1486 #include <sstream>
1487 #include <iomanip>
1488 #include <limits>
1489 #include <vector>
1490 #include <cstddef>
1491
1492 #ifdef __OBJC__
1493 // #included from: catch_objc_arc.hpp
1494 #define TWOBLUECUBES_CATCH_OBJC_ARC_HPP_INCLUDED
1495
1496 #import <Foundation/Foundation.h>
1497
1498 #ifdef __has_feature
1499 #define CATCH_ARC_ENABLED __has_feature(objc_arc)
1500 #else
1501 #define CATCH_ARC_ENABLED 0
1502 #endif
1503
1504 void arcSafeRelease( NSObject* obj );
1505 id performOptionalSelector( id obj, SEL sel );
1506
1507 #if !CATCH_ARC_ENABLED
1508 inline void arcSafeRelease( NSObject* obj ) {
1509 [obj release];
1510 }
1511 inline id performOptionalSelector( id obj, SEL sel ) {
1512 if( [obj respondsToSelector: sel] )
1513 return [obj performSelector: sel];
1514 return nil;
1515 }
1516 #define CATCH_UNSAFE_UNRETAINED
1517 #define CATCH_ARC_STRONG
1518 #else
1519 inline void arcSafeRelease( NSObject* ){}
1520 inline id performOptionalSelector( id obj, SEL sel ) {
1521 #ifdef __clang__
1522 #pragma clang diagnostic push
1523 #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
1524 #endif
1525 if( [obj respondsToSelector: sel] )
1526 return [obj performSelector: sel];
1527 #ifdef __clang__
1528 #pragma clang diagnostic pop
1529 #endif
1530 return nil;
1531 }
1532 #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
1533 #define CATCH_ARC_STRONG __strong
1534 #endif
1535
1536 #endif
1537
1538 #ifdef CATCH_CONFIG_CPP11_TUPLE
1539 #include <tuple>
1540 #endif
1541
1542 #ifdef CATCH_CONFIG_CPP11_IS_ENUM
1543 #include <type_traits>
1544 #endif
1545
1546 namespace Catch {
1547
1548 // Why we're here.
1549 template<typename T>
1550 std::string toString( T const& value );
1551
1552 // Built in overloads
1553
1554 std::string toString( std::string const& value );
1555 std::string toString( std::wstring const& value );
1556 std::string toString( const char* const value );
1557 std::string toString( char* const value );
1558 std::string toString( const wchar_t* const value );
1559 std::string toString( wchar_t* const value );
1560 std::string toString( int value );
1561 std::string toString( unsigned long value );
1562 std::string toString( unsigned int value );
1563 std::string toString( const double value );
1564 std::string toString( const float value );
1565 std::string toString( bool value );
1566 std::string toString( char value );
1567 std::string toString( signed char value );
1568 std::string toString( unsigned char value );
1569
1570 #ifdef CATCH_CONFIG_CPP11_LONG_LONG
1571 std::string toString( long long value );
1572 std::string toString( unsigned long long value );
1573 #endif
1574
1575 #ifdef CATCH_CONFIG_CPP11_NULLPTR
1576 std::string toString( std::nullptr_t );
1577 #endif
1578
1579 #ifdef __OBJC__
1580 std::string toString( NSString const * const& nsstring );
1581 std::string toString( NSString * CATCH_ARC_STRONG & nsstring );
1582 std::string toString( NSObject* const& nsObject );
1583 #endif
1584
1585 namespace Detail {
1586
1587 extern const std::string unprintableString;
1588
1589 #if !defined(CATCH_CONFIG_CPP11_STREAM_INSERTABLE_CHECK)
1590 struct BorgType {
1591 template<typename T> BorgType( T const& );
1592 };
1593
1594 struct TrueType { char sizer[1]; };
1595 struct FalseType { char sizer[2]; };
1596
1597 TrueType& testStreamable( std::ostream& );
1598 FalseType testStreamable( FalseType );
1599
1600 FalseType operator<<( std::ostream const&, BorgType const& );
1601
1602 template<typename T>
1603 struct IsStreamInsertable {
1604 static std::ostream &s;
1605 static T const&t;
1606 enum { value = sizeof( testStreamable(s << t) ) == sizeof( TrueType ) };
1607 };
1608 #else
1609 template<typename T>
1610 class IsStreamInsertable {
1611 template<typename SS, typename TT>
1612 static auto test(int)
1613 -> decltype( std::declval<SS&>() << std::declval<TT>(), std::true_type() );
1614
1615 template<typename, typename>
1616 static auto test(...) -> std::false_type;
1617
1618 public:
1619 static const bool value = decltype(test<std::ostream,const T&>(0))::value;
1620 };
1621 #endif
1622
1623 #if defined(CATCH_CONFIG_CPP11_IS_ENUM)
1624 template<typename T,
1625 bool IsEnum = std::is_enum<T>::value
1626 >
1627 struct EnumStringMaker
1628 {
1629 static std::string convert( T const& ) { return unprintableString; }
1630 };
1631
1632 template<typename T>
1633 struct EnumStringMaker<T,true>
1634 {
1635 static std::string convert( T const& v )
1636 {
1637 return ::Catch::toString(
1638 static_cast<typename std::underlying_type<T>::type>(v)
1639 );
1640 }
1641 };
1642 #endif
1643 template<bool C>
1644 struct StringMakerBase {
1645 #if defined(CATCH_CONFIG_CPP11_IS_ENUM)
1646 template<typename T>
1647 static std::string convert( T const& v )
1648 {
1649 return EnumStringMaker<T>::convert( v );
1650 }
1651 #else
1652 template<typename T>
1653 static std::string convert( T const& ) { return unprintableString; }
1654 #endif
1655 };
1656
1657 template<>
1658 struct StringMakerBase<true> {
1659 template<typename T>
1660 static std::string convert( T const& _value ) {
1661 std::ostringstream oss;
1662 oss << _value;
1663 return oss.str();
1664 }
1665 };
1666
1667 std::string rawMemoryToString( const void *object, std::size_t size );
1668
1669 template<typename T>
1670 inline std::string rawMemoryToString( const T& object ) {
1671 return rawMemoryToString( &object, sizeof(object) );
1672 }
1673
1674 } // end namespace Detail
1675
1676 template<typename T>
1677 struct StringMaker :
1678 Detail::StringMakerBase<Detail::IsStreamInsertable<T>::value> {};
1679
1680 template<typename T>
1681 struct StringMaker<T*> {
1682 template<typename U>
1683 static std::string convert( U* p ) {
1684 if( !p )
1685 return "NULL";
1686 else
1687 return Detail::rawMemoryToString( p );
1688 }
1689 };
1690
1691 template<typename R, typename C>
1692 struct StringMaker<R C::*> {
1693 static std::string convert( R C::* p ) {
1694 if( !p )
1695 return "NULL";
1696 else
1697 return Detail::rawMemoryToString( p );
1698 }
1699 };
1700
1701 namespace Detail {
1702 template<typename InputIterator>
1703 std::string rangeToString( InputIterator first, InputIterator last );
1704 }
1705
1706 //template<typename T, typename Allocator>
1707 //struct StringMaker<std::vector<T, Allocator> > {
1708 // static std::string convert( std::vector<T,Allocator> const& v ) {
1709 // return Detail::rangeToString( v.begin(), v.end() );
1710 // }
1711 //};
1712
1713 template<typename T, typename Allocator>
1714 std::string toString( std::vector<T,Allocator> const& v ) {
1715 return Detail::rangeToString( v.begin(), v.end() );
1716 }
1717
1718 #ifdef CATCH_CONFIG_CPP11_TUPLE
1719
1720 // toString for tuples
1721 namespace TupleDetail {
1722 template<
1723 typename Tuple,
1724 std::size_t N = 0,
1725 bool = (N < std::tuple_size<Tuple>::value)
1726 >
1727 struct ElementPrinter {
1728 static void print( const Tuple& tuple, std::ostream& os )
1729 {
1730 os << ( N ? ", " : " " )
1731 << Catch::toString(std::get<N>(tuple));
1732 ElementPrinter<Tuple,N+1>::print(tuple,os);
1733 }
1734 };
1735
1736 template<
1737 typename Tuple,
1738 std::size_t N
1739 >
1740 struct ElementPrinter<Tuple,N,false> {
1741 static void print( const Tuple&, std::ostream& ) {}
1742 };
1743
1744 }
1745
1746 template<typename ...Types>
1747 struct StringMaker<std::tuple<Types...>> {
1748
1749 static std::string convert( const std::tuple<Types...>& tuple )
1750 {
1751 std::ostringstream os;
1752 os << '{';
1753 TupleDetail::ElementPrinter<std::tuple<Types...>>::print( tuple, os );
1754 os << " }";
1755 return os.str();
1756 }
1757 };
1758 #endif // CATCH_CONFIG_CPP11_TUPLE
1759
1760 namespace Detail {
1761 template<typename T>
1762 std::string makeString( T const& value ) {
1763 return StringMaker<T>::convert( value );
1764 }
1765 } // end namespace Detail
1766
1767 /// \brief converts any type to a string
1768 ///
1769 /// The default template forwards on to ostringstream - except when an
1770 /// ostringstream overload does not exist - in which case it attempts to detect
1771 /// that and writes {?}.
1772 /// Overload (not specialise) this template for custom typs that you don't want
1773 /// to provide an ostream overload for.
1774 template<typename T>
1775 std::string toString( T const& value ) {
1776 return StringMaker<T>::convert( value );
1777 }
1778
1779 namespace Detail {
1780 template<typename InputIterator>
1781 std::string rangeToString( InputIterator first, InputIterator last ) {
1782 std::ostringstream oss;
1783 oss << "{ ";
1784 if( first != last ) {
1785 oss << Catch::toString( *first );
1786 for( ++first ; first != last ; ++first )
1787 oss << ", " << Catch::toString( *first );
1788 }
1789 oss << " }";
1790 return oss.str();
1791 }
1792 }
1793
1794 } // end namespace Catch
1795
1796 namespace Catch {
1797
1798 template<typename LhsT, Internal::Operator Op, typename RhsT>
1799 class BinaryExpression;
1800
1801 template<typename ArgT, typename MatcherT>
1802 class MatchExpression;
1803
1804 // Wraps the LHS of an expression and overloads comparison operators
1805 // for also capturing those and RHS (if any)
1806 template<typename T>
1807 class ExpressionLhs : public DecomposedExpression {
1808 public:
1809 ExpressionLhs( ResultBuilder& rb, T lhs ) : m_rb( rb ), m_lhs( lhs ), m_truthy(false) {}
1810
1811 ExpressionLhs& operator = ( const ExpressionLhs& );
1812
1813 template<typename RhsT>
1814 BinaryExpression<T, Internal::IsEqualTo, RhsT const&>
1815 operator == ( RhsT const& rhs ) {
1816 return captureExpression<Internal::IsEqualTo>( rhs );
1817 }
1818
1819 template<typename RhsT>
1820 BinaryExpression<T, Internal::IsNotEqualTo, RhsT const&>
1821 operator != ( RhsT const& rhs ) {
1822 return captureExpression<Internal::IsNotEqualTo>( rhs );
1823 }
1824
1825 template<typename RhsT>
1826 BinaryExpression<T, Internal::IsLessThan, RhsT const&>
1827 operator < ( RhsT const& rhs ) {
1828 return captureExpression<Internal::IsLessThan>( rhs );
1829 }
1830
1831 template<typename RhsT>
1832 BinaryExpression<T, Internal::IsGreaterThan, RhsT const&>
1833 operator > ( RhsT const& rhs ) {
1834 return captureExpression<Internal::IsGreaterThan>( rhs );
1835 }
1836
1837 template<typename RhsT>
1838 BinaryExpression<T, Internal::IsLessThanOrEqualTo, RhsT const&>
1839 operator <= ( RhsT const& rhs ) {
1840 return captureExpression<Internal::IsLessThanOrEqualTo>( rhs );
1841 }
1842
1843 template<typename RhsT>
1844 BinaryExpression<T, Internal::IsGreaterThanOrEqualTo, RhsT const&>
1845 operator >= ( RhsT const& rhs ) {
1846 return captureExpression<Internal::IsGreaterThanOrEqualTo>( rhs );
1847 }
1848
1849 BinaryExpression<T, Internal::IsEqualTo, bool> operator == ( bool rhs ) {
1850 return captureExpression<Internal::IsEqualTo>( rhs );
1851 }
1852
1853 BinaryExpression<T, Internal::IsNotEqualTo, bool> operator != ( bool rhs ) {
1854 return captureExpression<Internal::IsNotEqualTo>( rhs );
1855 }
1856
1857 void endExpression() {
1858 m_truthy = m_lhs ? true : false;
1859 m_rb
1860 .setResultType( m_truthy )
1861 .endExpression( *this );
1862 }
1863
1864 virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE {
1865 dest = Catch::toString( m_lhs );
1866 }
1867
1868 private:
1869 template<Internal::Operator Op, typename RhsT>
1870 BinaryExpression<T, Op, RhsT&> captureExpression( RhsT& rhs ) const {
1871 return BinaryExpression<T, Op, RhsT&>( m_rb, m_lhs, rhs );
1872 }
1873
1874 template<Internal::Operator Op>
1875 BinaryExpression<T, Op, bool> captureExpression( bool rhs ) const {
1876 return BinaryExpression<T, Op, bool>( m_rb, m_lhs, rhs );
1877 }
1878
1879 private:
1880 ResultBuilder& m_rb;
1881 T m_lhs;
1882 bool m_truthy;
1883 };
1884
1885 template<typename LhsT, Internal::Operator Op, typename RhsT>
1886 class BinaryExpression : public DecomposedExpression {
1887 public:
1888 BinaryExpression( ResultBuilder& rb, LhsT lhs, RhsT rhs )
1889 : m_rb( rb ), m_lhs( lhs ), m_rhs( rhs ) {}
1890
1891 BinaryExpression& operator = ( BinaryExpression& );
1892
1893 void endExpression() const {
1894 m_rb
1895 .setResultType( Internal::compare<Op>( m_lhs, m_rhs ) )
1896 .endExpression( *this );
1897 }
1898
1899 virtual bool isBinaryExpression() const CATCH_OVERRIDE {
1900 return true;
1901 }
1902
1903 virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE {
1904 std::string lhs = Catch::toString( m_lhs );
1905 std::string rhs = Catch::toString( m_rhs );
1906 char delim = lhs.size() + rhs.size() < 40 &&
1907 lhs.find('\n') == std::string::npos &&
1908 rhs.find('\n') == std::string::npos ? ' ' : '\n';
1909 dest.reserve( 7 + lhs.size() + rhs.size() );
1910 // 2 for spaces around operator
1911 // 2 for operator
1912 // 2 for parentheses (conditionally added later)
1913 // 1 for negation (conditionally added later)
1914 dest = lhs;
1915 dest += delim;
1916 dest += Internal::OperatorTraits<Op>::getName();
1917 dest += delim;
1918 dest += rhs;
1919 }
1920
1921 private:
1922 ResultBuilder& m_rb;
1923 LhsT m_lhs;
1924 RhsT m_rhs;
1925 };
1926
1927 template<typename ArgT, typename MatcherT>
1928 class MatchExpression : public DecomposedExpression {
1929 public:
1930 MatchExpression( ArgT arg, MatcherT matcher, char const* matcherString )
1931 : m_arg( arg ), m_matcher( matcher ), m_matcherString( matcherString ) {}
1932
1933 virtual bool isBinaryExpression() const CATCH_OVERRIDE {
1934 return true;
1935 }
1936
1937 virtual void reconstructExpression( std::string& dest ) const CATCH_OVERRIDE {
1938 std::string matcherAsString = m_matcher.toString();
1939 dest = Catch::toString( m_arg );
1940 dest += ' ';
1941 if( matcherAsString == Detail::unprintableString )
1942 dest += m_matcherString;
1943 else
1944 dest += matcherAsString;
1945 }
1946
1947 private:
1948 ArgT m_arg;
1949 MatcherT m_matcher;
1950 char const* m_matcherString;
1951 };
1952
1953 } // end namespace Catch
1954
1955
1956 namespace Catch {
1957
1958 template<typename T>
1959 inline ExpressionLhs<T const&> ResultBuilder::operator <= ( T const& operand ) {
1960 return ExpressionLhs<T const&>( *this, operand );
1961 }
1962
1963 inline ExpressionLhs<bool> ResultBuilder::operator <= ( bool value ) {
1964 return ExpressionLhs<bool>( *this, value );
1965 }
1966
1967 template<typename ArgT, typename MatcherT>
1968 inline void ResultBuilder::captureMatch( ArgT const& arg, MatcherT const& matcher,
1969 char const* matcherString ) {
1970 MatchExpression<ArgT const&, MatcherT const&> expr( arg, matcher, matcherString );
1971 setResultType( matcher.match( arg ) );
1972 endExpression( expr );
1973 }
1974
1975 } // namespace Catch
1976
1977 // #included from: catch_message.h
1978 #define TWOBLUECUBES_CATCH_MESSAGE_H_INCLUDED
1979
1980 #include <string>
1981
1982 namespace Catch {
1983
1984 struct MessageInfo {
1985 MessageInfo( std::string const& _macroName,
1986 SourceLineInfo const& _lineInfo,
1987 ResultWas::OfType _type );
1988
1989 std::string macroName;
1990 SourceLineInfo lineInfo;
1991 ResultWas::OfType type;
1992 std::string message;
1993 unsigned int sequence;
1994
1995 bool operator == ( MessageInfo const& other ) const {
1996 return sequence == other.sequence;
1997 }
1998 bool operator < ( MessageInfo const& other ) const {
1999 return sequence < other.sequence;
2000 }
2001 private:
2002 static unsigned int globalCount;
2003 };
2004
2005 struct MessageBuilder {
2006 MessageBuilder( std::string const& macroName,
2007 SourceLineInfo const& lineInfo,
2008 ResultWas::OfType type )
2009 : m_info( macroName, lineInfo, type )
2010 {}
2011
2012 template<typename T>
2013 MessageBuilder& operator << ( T const& value ) {
2014 m_stream << value;
2015 return *this;
2016 }
2017
2018 MessageInfo m_info;
2019 std::ostringstream m_stream;
2020 };
2021
2022 class ScopedMessage {
2023 public:
2024 ScopedMessage( MessageBuilder const& builder );
2025 ScopedMessage( ScopedMessage const& other );
2026 ~ScopedMessage();
2027
2028 MessageInfo m_info;
2029 };
2030
2031 } // end namespace Catch
2032
2033 // #included from: catch_interfaces_capture.h
2034 #define TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED
2035
2036 #include <string>
2037
2038 namespace Catch {
2039
2040 class TestCase;
2041 class AssertionResult;
2042 struct AssertionInfo;
2043 struct SectionInfo;
2044 struct SectionEndInfo;
2045 struct MessageInfo;
2046 class ScopedMessageBuilder;
2047 struct Counts;
2048
2049 struct IResultCapture {
2050
2051 virtual ~IResultCapture();
2052
2053 virtual void assertionEnded( AssertionResult const& result ) = 0;
2054 virtual bool sectionStarted( SectionInfo const& sectionInfo,
2055 Counts& assertions ) = 0;
2056 virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
2057 virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
2058 virtual void pushScopedMessage( MessageInfo const& message ) = 0;
2059 virtual void popScopedMessage( MessageInfo const& message ) = 0;
2060
2061 virtual std::string getCurrentTestName() const = 0;
2062 virtual const AssertionResult* getLastResult() const = 0;
2063
2064 virtual void exceptionEarlyReported() = 0;
2065
2066 virtual void handleFatalErrorCondition( std::string const& message ) = 0;
2067 };
2068
2069 IResultCapture& getResultCapture();
2070 }
2071
2072 // #included from: catch_debugger.h
2073 #define TWOBLUECUBES_CATCH_DEBUGGER_H_INCLUDED
2074
2075 // #included from: catch_platform.h
2076 #define TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED
2077
2078 #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED)
2079 # define CATCH_PLATFORM_MAC
2080 #elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED)
2081 # define CATCH_PLATFORM_IPHONE
2082 #elif defined(linux) || defined(__linux) || defined(__linux__)
2083 # define CATCH_PLATFORM_LINUX
2084 #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
2085 # define CATCH_PLATFORM_WINDOWS
2086 # if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
2087 # define CATCH_DEFINES_NOMINMAX
2088 # endif
2089 # if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
2090 # define CATCH_DEFINES_WIN32_LEAN_AND_MEAN
2091 # endif
2092 #endif
2093
2094 #include <string>
2095
2096 namespace Catch{
2097
2098 bool isDebuggerActive();
2099 void writeToDebugConsole( std::string const& text );
2100 }
2101
2102 #ifdef CATCH_PLATFORM_MAC
2103
2104 // The following code snippet based on:
2105 // http://cocoawithlove.com/2008/03/break-into-debugger.html
2106 #if defined(__ppc64__) || defined(__ppc__)
2107 #define CATCH_TRAP() \
2108 __asm__("li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n" \
2109 : : : "memory","r0","r3","r4" )
2110 #else
2111 #define CATCH_TRAP() __asm__("int $3\n" : : )
2112 #endif
2113
2114 #elif defined(CATCH_PLATFORM_LINUX)
2115 // If we can use inline assembler, do it because this allows us to break
2116 // directly at the location of the failing check instead of breaking inside
2117 // raise() called from it, i.e. one stack frame below.
2118 #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
2119 #define CATCH_TRAP() asm volatile ("int $3")
2120 #else // Fall back to the generic way.
2121 #include <signal.h>
2122
2123 #define CATCH_TRAP() raise(SIGTRAP)
2124 #endif
2125 #elif defined(_MSC_VER)
2126 #define CATCH_TRAP() __debugbreak()
2127 #elif defined(__MINGW32__)
2128 extern "C" __declspec(dllimport) void __stdcall DebugBreak();
2129 #define CATCH_TRAP() DebugBreak()
2130 #endif
2131
2132 #ifdef CATCH_TRAP
2133 #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
2134 #else
2135 #define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue();
2136 #endif
2137
2138 // #included from: catch_interfaces_runner.h
2139 #define TWOBLUECUBES_CATCH_INTERFACES_RUNNER_H_INCLUDED
2140
2141 namespace Catch {
2142 class TestCase;
2143
2144 struct IRunner {
2145 virtual ~IRunner();
2146 virtual bool aborting() const = 0;
2147 };
2148 }
2149
2150 #if defined(CATCH_CONFIG_FAST_COMPILE)
2151 ///////////////////////////////////////////////////////////////////////////////
2152 // We can speedup compilation significantly by breaking into debugger lower in
2153 // the callstack, because then we don't have to expand CATCH_BREAK_INTO_DEBUGGER
2154 // macro in each assertion
2155 #define INTERNAL_CATCH_REACT( resultBuilder ) \
2156 resultBuilder.react();
2157
2158 ///////////////////////////////////////////////////////////////////////////////
2159 // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
2160 // macros.
2161 // This can potentially cause false negative, if the test code catches
2162 // the exception before it propagates back up to the runner.
2163 #define INTERNAL_CATCH_TEST_NO_TRY( macroName, resultDisposition, expr ) \
2164 do { \
2165 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
2166 __catchResult.setExceptionGuard(); \
2167 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
2168 ( __catchResult <= expr ).endExpression(); \
2169 CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
2170 __catchResult.unsetExceptionGuard(); \
2171 INTERNAL_CATCH_REACT( __catchResult ) \
2172 } while( Catch::isTrue( false && static_cast<bool>( !!(expr) ) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look
2173 // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
2174
2175 #define INTERNAL_CHECK_THAT_NO_TRY( macroName, matcher, resultDisposition, arg ) \
2176 do { \
2177 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg ", " #matcher, resultDisposition ); \
2178 __catchResult.setExceptionGuard(); \
2179 __catchResult.captureMatch( arg, matcher, #matcher ); \
2180 __catchResult.unsetExceptionGuard(); \
2181 INTERNAL_CATCH_REACT( __catchResult ) \
2182 } while( Catch::alwaysFalse() )
2183
2184 #else
2185 ///////////////////////////////////////////////////////////////////////////////
2186 // In the event of a failure works out if the debugger needs to be invoked
2187 // and/or an exception thrown and takes appropriate action.
2188 // This needs to be done as a macro so the debugger will stop in the user
2189 // source code rather than in Catch library code
2190 #define INTERNAL_CATCH_REACT( resultBuilder ) \
2191 if( resultBuilder.shouldDebugBreak() ) CATCH_BREAK_INTO_DEBUGGER(); \
2192 resultBuilder.react();
2193 #endif
2194
2195 ///////////////////////////////////////////////////////////////////////////////
2196 #define INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ) \
2197 do { \
2198 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
2199 try { \
2200 CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
2201 ( __catchResult <= expr ).endExpression(); \
2202 CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
2203 } \
2204 catch( ... ) { \
2205 __catchResult.useActiveException( resultDisposition ); \
2206 } \
2207 INTERNAL_CATCH_REACT( __catchResult ) \
2208 } while( Catch::isTrue( false && static_cast<bool>( !!(expr) ) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look
2209 // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
2210
2211 ///////////////////////////////////////////////////////////////////////////////
2212 #define INTERNAL_CATCH_IF( macroName, resultDisposition, expr ) \
2213 INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ); \
2214 if( Catch::getResultCapture().getLastResult()->succeeded() )
2215
2216 ///////////////////////////////////////////////////////////////////////////////
2217 #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, expr ) \
2218 INTERNAL_CATCH_TEST( macroName, resultDisposition, expr ); \
2219 if( !Catch::getResultCapture().getLastResult()->succeeded() )
2220
2221 ///////////////////////////////////////////////////////////////////////////////
2222 #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, expr ) \
2223 do { \
2224 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \
2225 try { \
2226 static_cast<void>(expr); \
2227 __catchResult.captureResult( Catch::ResultWas::Ok ); \
2228 } \
2229 catch( ... ) { \
2230 __catchResult.useActiveException( resultDisposition ); \
2231 } \
2232 INTERNAL_CATCH_REACT( __catchResult ) \
2233 } while( Catch::alwaysFalse() )
2234
2235 ///////////////////////////////////////////////////////////////////////////////
2236 #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, matcher, expr ) \
2237 do { \
2238 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition, #matcher ); \
2239 if( __catchResult.allowThrows() ) \
2240 try { \
2241 static_cast<void>(expr); \
2242 __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \
2243 } \
2244 catch( ... ) { \
2245 __catchResult.captureExpectedException( matcher ); \
2246 } \
2247 else \
2248 __catchResult.captureResult( Catch::ResultWas::Ok ); \
2249 INTERNAL_CATCH_REACT( __catchResult ) \
2250 } while( Catch::alwaysFalse() )
2251
2252 ///////////////////////////////////////////////////////////////////////////////
2253 #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
2254 do { \
2255 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr ", " #exceptionType, resultDisposition ); \
2256 if( __catchResult.allowThrows() ) \
2257 try { \
2258 static_cast<void>(expr); \
2259 __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \
2260 } \
2261 catch( exceptionType ) { \
2262 __catchResult.captureResult( Catch::ResultWas::Ok ); \
2263 } \
2264 catch( ... ) { \
2265 __catchResult.useActiveException( resultDisposition ); \
2266 } \
2267 else \
2268 __catchResult.captureResult( Catch::ResultWas::Ok ); \
2269 INTERNAL_CATCH_REACT( __catchResult ) \
2270 } while( Catch::alwaysFalse() )
2271
2272 ///////////////////////////////////////////////////////////////////////////////
2273 #ifdef CATCH_CONFIG_VARIADIC_MACROS
2274 #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
2275 do { \
2276 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
2277 __catchResult << __VA_ARGS__ + ::Catch::StreamEndStop(); \
2278 __catchResult.captureResult( messageType ); \
2279 INTERNAL_CATCH_REACT( __catchResult ) \
2280 } while( Catch::alwaysFalse() )
2281 #else
2282 #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, log ) \
2283 do { \
2284 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
2285 __catchResult << log + ::Catch::StreamEndStop(); \
2286 __catchResult.captureResult( messageType ); \
2287 INTERNAL_CATCH_REACT( __catchResult ) \
2288 } while( Catch::alwaysFalse() )
2289 #endif
2290
2291 ///////////////////////////////////////////////////////////////////////////////
2292 #define INTERNAL_CATCH_INFO( macroName, log ) \
2293 Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage ) = Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log;
2294
2295 ///////////////////////////////////////////////////////////////////////////////
2296 #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
2297 do { \
2298 Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg ", " #matcher, resultDisposition ); \
2299 try { \
2300 __catchResult.captureMatch( arg, matcher, #matcher ); \
2301 } catch( ... ) { \
2302 __catchResult.useActiveException( resultDisposition | Catch::ResultDisposition::ContinueOnFailure ); \
2303 } \
2304 INTERNAL_CATCH_REACT( __catchResult ) \
2305 } while( Catch::alwaysFalse() )
2306
2307 // #included from: internal/catch_section.h
2308 #define TWOBLUECUBES_CATCH_SECTION_H_INCLUDED
2309
2310 // #included from: catch_section_info.h
2311 #define TWOBLUECUBES_CATCH_SECTION_INFO_H_INCLUDED
2312
2313 // #included from: catch_totals.hpp
2314 #define TWOBLUECUBES_CATCH_TOTALS_HPP_INCLUDED
2315
2316 #include <cstddef>
2317
2318 namespace Catch {
2319
2320 struct Counts {
2321 Counts() : passed( 0 ), failed( 0 ), failedButOk( 0 ) {}
2322
2323 Counts operator - ( Counts const& other ) const {
2324 Counts diff;
2325 diff.passed = passed - other.passed;
2326 diff.failed = failed - other.failed;
2327 diff.failedButOk = failedButOk - other.failedButOk;
2328 return diff;
2329 }
2330 Counts& operator += ( Counts const& other ) {
2331 passed += other.passed;
2332 failed += other.failed;
2333 failedButOk += other.failedButOk;
2334 return *this;
2335 }
2336
2337 std::size_t total() const {
2338 return passed + failed + failedButOk;
2339 }
2340 bool allPassed() const {
2341 return failed == 0 && failedButOk == 0;
2342 }
2343 bool allOk() const {
2344 return failed == 0;
2345 }
2346
2347 std::size_t passed;
2348 std::size_t failed;
2349 std::size_t failedButOk;
2350 };
2351
2352 struct Totals {
2353
2354 Totals operator - ( Totals const& other ) const {
2355 Totals diff;
2356 diff.assertions = assertions - other.assertions;
2357 diff.testCases = testCases - other.testCases;
2358 return diff;
2359 }
2360
2361 Totals delta( Totals const& prevTotals ) const {
2362 Totals diff = *this - prevTotals;
2363 if( diff.assertions.failed > 0 )
2364 ++diff.testCases.failed;
2365 else if( diff.assertions.failedButOk > 0 )
2366 ++diff.testCases.failedButOk;
2367 else
2368 ++diff.testCases.passed;
2369 return diff;
2370 }
2371
2372 Totals& operator += ( Totals const& other ) {
2373 assertions += other.assertions;
2374 testCases += other.testCases;
2375 return *this;
2376 }
2377
2378 Counts assertions;
2379 Counts testCases;
2380 };
2381 }
2382
2383 #include <string>
2384
2385 namespace Catch {
2386
2387 struct SectionInfo {
2388 SectionInfo
2389 ( SourceLineInfo const& _lineInfo,
2390 std::string const& _name,
2391 std::string const& _description = std::string() );
2392
2393 std::string name;
2394 std::string description;
2395 SourceLineInfo lineInfo;
2396 };
2397
2398 struct SectionEndInfo {
2399 SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds )
2400 : sectionInfo( _sectionInfo ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds )
2401 {}
2402
2403 SectionInfo sectionInfo;
2404 Counts prevAssertions;
2405 double durationInSeconds;
2406 };
2407
2408 } // end namespace Catch
2409
2410 // #included from: catch_timer.h
2411 #define TWOBLUECUBES_CATCH_TIMER_H_INCLUDED
2412
2413 #ifdef _MSC_VER
2414
2415 namespace Catch {
2416 typedef unsigned long long UInt64;
2417 }
2418 #else
2419 #include <stdint.h>
2420 namespace Catch {
2421 typedef uint64_t UInt64;
2422 }
2423 #endif
2424
2425 namespace Catch {
2426 class Timer {
2427 public:
2428 Timer() : m_ticks( 0 ) {}
2429 void start();
2430 unsigned int getElapsedMicroseconds() const;
2431 unsigned int getElapsedMilliseconds() const;
2432 double getElapsedSeconds() const;
2433
2434 private:
2435 UInt64 m_ticks;
2436 };
2437
2438 } // namespace Catch
2439
2440 #include <string>
2441
2442 namespace Catch {
2443
2444 class Section : NonCopyable {
2445 public:
2446 Section( SectionInfo const& info );
2447 ~Section();
2448
2449 // This indicates whether the section should be executed or not
2450 operator bool() const;
2451
2452 private:
2453 SectionInfo m_info;
2454
2455 std::string m_name;
2456 Counts m_assertions;
2457 bool m_sectionIncluded;
2458 Timer m_timer;
2459 };
2460
2461 } // end namespace Catch
2462
2463 #ifdef CATCH_CONFIG_VARIADIC_MACROS
2464 #define INTERNAL_CATCH_SECTION( ... ) \
2465 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) )
2466 #else
2467 #define INTERNAL_CATCH_SECTION( name, desc ) \
2468 if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, name, desc ) )
2469 #endif
2470
2471 // #included from: internal/catch_generators.hpp
2472 #define TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED
2473
2474 #include <vector>
2475 #include <string>
2476 #include <stdlib.h>
2477
2478 namespace Catch {
2479
2480 template<typename T>
2481 struct IGenerator {
2482 virtual ~IGenerator() {}
2483 virtual T getValue( std::size_t index ) const = 0;
2484 virtual std::size_t size () const = 0;
2485 };
2486
2487 template<typename T>
2488 class BetweenGenerator : public IGenerator<T> {
2489 public:
2490 BetweenGenerator( T from, T to ) : m_from( from ), m_to( to ){}
2491
2492 virtual T getValue( std::size_t index ) const {
2493 return m_from+static_cast<int>( index );
2494 }
2495
2496 virtual std::size_t size() const {
2497 return static_cast<std::size_t>( 1+m_to-m_from );
2498 }
2499
2500 private:
2501
2502 T m_from;
2503 T m_to;
2504 };
2505
2506 template<typename T>
2507 class ValuesGenerator : public IGenerator<T> {
2508 public:
2509 ValuesGenerator(){}
2510
2511 void add( T value ) {
2512 m_values.push_back( value );
2513 }
2514
2515 virtual T getValue( std::size_t index ) const {
2516 return m_values[index];
2517 }
2518
2519 virtual std::size_t size() const {
2520 return m_values.size();
2521 }
2522
2523 private:
2524 std::vector<T> m_values;
2525 };
2526
2527 template<typename T>
2528 class CompositeGenerator {
2529 public:
2530 CompositeGenerator() : m_totalSize( 0 ) {}
2531
2532 // *** Move semantics, similar to auto_ptr ***
2533 CompositeGenerator( CompositeGenerator& other )
2534 : m_fileInfo( other.m_fileInfo ),
2535 m_totalSize( 0 )
2536 {
2537 move( other );
2538 }
2539
2540 CompositeGenerator& setFileInfo( const char* fileInfo ) {
2541 m_fileInfo = fileInfo;
2542 return *this;
2543 }
2544
2545 ~CompositeGenerator() {
2546 deleteAll( m_composed );
2547 }
2548
2549 operator T () const {
2550 size_t overallIndex = getCurrentContext().getGeneratorIndex( m_fileInfo, m_totalSize );
2551
2552 typename std::vector<const IGenerator<T>*>::const_iterator it = m_composed.begin();
2553 typename std::vector<const IGenerator<T>*>::const_iterator itEnd = m_composed.end();
2554 for( size_t index = 0; it != itEnd; ++it )
2555 {
2556 const IGenerator<T>* generator = *it;
2557 if( overallIndex >= index && overallIndex < index + generator->size() )
2558 {
2559 return generator->getValue( overallIndex-index );
2560 }
2561 index += generator->size();
2562 }
2563 CATCH_INTERNAL_ERROR( "Indexed past end of generated range" );
2564 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
2565 }
2566
2567 void add( const IGenerator<T>* generator ) {
2568 m_totalSize += generator->size();
2569 m_composed.push_back( generator );
2570 }
2571
2572 CompositeGenerator& then( CompositeGenerator& other ) {
2573 move( other );
2574 return *this;
2575 }
2576
2577 CompositeGenerator& then( T value ) {
2578 ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>();
2579 valuesGen->add( value );
2580 add( valuesGen );
2581 return *this;
2582 }
2583
2584 private:
2585
2586 void move( CompositeGenerator& other ) {
2587 m_composed.insert( m_composed.end(), other.m_composed.begin(), other.m_composed.end() );
2588 m_totalSize += other.m_totalSize;
2589 other.m_composed.clear();
2590 }
2591
2592 std::vector<const IGenerator<T>*> m_composed;
2593 std::string m_fileInfo;
2594 size_t m_totalSize;
2595 };
2596
2597 namespace Generators
2598 {
2599 template<typename T>
2600 CompositeGenerator<T> between( T from, T to ) {
2601 CompositeGenerator<T> generators;
2602 generators.add( new BetweenGenerator<T>( from, to ) );
2603 return generators;
2604 }
2605
2606 template<typename T>
2607 CompositeGenerator<T> values( T val1, T val2 ) {
2608 CompositeGenerator<T> generators;
2609 ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>();
2610 valuesGen->add( val1 );
2611 valuesGen->add( val2 );
2612 generators.add( valuesGen );
2613 return generators;
2614 }
2615
2616 template<typename T>
2617 CompositeGenerator<T> values( T val1, T val2, T val3 ){
2618 CompositeGenerator<T> generators;
2619 ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>();
2620 valuesGen->add( val1 );
2621 valuesGen->add( val2 );
2622 valuesGen->add( val3 );
2623 generators.add( valuesGen );
2624 return generators;
2625 }
2626
2627 template<typename T>
2628 CompositeGenerator<T> values( T val1, T val2, T val3, T val4 ) {
2629 CompositeGenerator<T> generators;
2630 ValuesGenerator<T>* valuesGen = new ValuesGenerator<T>();
2631 valuesGen->add( val1 );
2632 valuesGen->add( val2 );
2633 valuesGen->add( val3 );
2634 valuesGen->add( val4 );
2635 generators.add( valuesGen );
2636 return generators;
2637 }
2638
2639 } // end namespace Generators
2640
2641 using namespace Generators;
2642
2643 } // end namespace Catch
2644
2645 #define INTERNAL_CATCH_LINESTR2( line ) #line
2646 #define INTERNAL_CATCH_LINESTR( line ) INTERNAL_CATCH_LINESTR2( line )
2647
2648 #define INTERNAL_CATCH_GENERATE( expr ) expr.setFileInfo( __FILE__ "(" INTERNAL_CATCH_LINESTR( __LINE__ ) ")" )
2649
2650 // #included from: internal/catch_interfaces_exception.h
2651 #define TWOBLUECUBES_CATCH_INTERFACES_EXCEPTION_H_INCLUDED
2652
2653 #include <string>
2654 #include <vector>
2655
2656 // #included from: catch_interfaces_registry_hub.h
2657 #define TWOBLUECUBES_CATCH_INTERFACES_REGISTRY_HUB_H_INCLUDED
2658
2659 #include <string>
2660
2661 namespace Catch {
2662
2663 class TestCase;
2664 struct ITestCaseRegistry;
2665 struct IExceptionTranslatorRegistry;
2666 struct IExceptionTranslator;
2667 struct IReporterRegistry;
2668 struct IReporterFactory;
2669 struct ITagAliasRegistry;
2670
2671 struct IRegistryHub {
2672 virtual ~IRegistryHub();
2673
2674 virtual IReporterRegistry const& getReporterRegistry() const = 0;
2675 virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
2676 virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
2677
2678 virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0;
2679 };
2680
2681 struct IMutableRegistryHub {
2682 virtual ~IMutableRegistryHub();
2683 virtual void registerReporter( std::string const& name, Ptr<IReporterFactory> const& factory ) = 0;
2684 virtual void registerListener( Ptr<IReporterFactory> const& factory ) = 0;
2685 virtual void registerTest( TestCase const& testInfo ) = 0;
2686 virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
2687 virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
2688 };
2689
2690 IRegistryHub& getRegistryHub();
2691 IMutableRegistryHub& getMutableRegistryHub();
2692 void cleanUp();
2693 std::string translateActiveException();
2694
2695 }
2696
2697 namespace Catch {
2698
2699 typedef std::string(*exceptionTranslateFunction)();
2700
2701 struct IExceptionTranslator;
2702 typedef std::vector<const IExceptionTranslator*> ExceptionTranslators;
2703
2704 struct IExceptionTranslator {
2705 virtual ~IExceptionTranslator();
2706 virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
2707 };
2708
2709 struct IExceptionTranslatorRegistry {
2710 virtual ~IExceptionTranslatorRegistry();
2711
2712 virtual std::string translateActiveException() const = 0;
2713 };
2714
2715 class ExceptionTranslatorRegistrar {
2716 template<typename T>
2717 class ExceptionTranslator : public IExceptionTranslator {
2718 public:
2719
2720 ExceptionTranslator( std::string(*translateFunction)( T& ) )
2721 : m_translateFunction( translateFunction )
2722 {}
2723
2724 virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const CATCH_OVERRIDE {
2725 try {
2726 if( it == itEnd )
2727 throw;
2728 else
2729 return (*it)->translate( it+1, itEnd );
2730 }
2731 catch( T& ex ) {
2732 return m_translateFunction( ex );
2733 }
2734 }
2735
2736 protected:
2737 std::string(*m_translateFunction)( T& );
2738 };
2739
2740 public:
2741 template<typename T>
2742 ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
2743 getMutableRegistryHub().registerTranslator
2744 ( new ExceptionTranslator<T>( translateFunction ) );
2745 }
2746 };
2747 }
2748
2749 ///////////////////////////////////////////////////////////////////////////////
2750 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
2751 static std::string translatorName( signature ); \
2752 namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); }\
2753 static std::string translatorName( signature )
2754
2755 #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
2756
2757 // #included from: internal/catch_approx.hpp
2758 #define TWOBLUECUBES_CATCH_APPROX_HPP_INCLUDED
2759
2760 #include <cmath>
2761 #include <limits>
2762
2763 #if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS)
2764 #include <type_traits>
2765 #endif
2766
2767 namespace Catch {
2768 namespace Detail {
2769
2770 class Approx {
2771 public:
2772 explicit Approx ( double value )
2773 : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
2774 m_margin( 0.0 ),
2775 m_scale( 1.0 ),
2776 m_value( value )
2777 {}
2778
2779 Approx( Approx const& other )
2780 : m_epsilon( other.m_epsilon ),
2781 m_margin( other.m_margin ),
2782 m_scale( other.m_scale ),
2783 m_value( other.m_value )
2784 {}
2785
2786 static Approx custom() {
2787 return Approx( 0 );
2788 }
2789
2790 #if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS)
2791
2792 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2793 Approx operator()( T value ) {
2794 Approx approx( static_cast<double>(value) );
2795 approx.epsilon( m_epsilon );
2796 approx.margin( m_margin );
2797 approx.scale( m_scale );
2798 return approx;
2799 }
2800
2801 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2802 explicit Approx( T value ): Approx(static_cast<double>(value))
2803 {}
2804
2805 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2806 friend bool operator == ( const T& lhs, Approx const& rhs ) {
2807 // Thanks to Richard Harris for his help refining this formula
2808 auto lhs_v = double(lhs);
2809 bool relativeOK = std::fabs(lhs_v - rhs.m_value) < rhs.m_epsilon * (rhs.m_scale + (std::max)(std::fabs(lhs_v), std::fabs(rhs.m_value)));
2810 if (relativeOK) {
2811 return true;
2812 }
2813 return std::fabs(lhs_v - rhs.m_value) < rhs.m_margin;
2814 }
2815
2816 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2817 friend bool operator == ( Approx const& lhs, const T& rhs ) {
2818 return operator==( rhs, lhs );
2819 }
2820
2821 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2822 friend bool operator != ( T lhs, Approx const& rhs ) {
2823 return !operator==( lhs, rhs );
2824 }
2825
2826 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2827 friend bool operator != ( Approx const& lhs, T rhs ) {
2828 return !operator==( rhs, lhs );
2829 }
2830
2831 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2832 friend bool operator <= ( T lhs, Approx const& rhs ) {
2833 return double(lhs) < rhs.m_value || lhs == rhs;
2834 }
2835
2836 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2837 friend bool operator <= ( Approx const& lhs, T rhs ) {
2838 return lhs.m_value < double(rhs) || lhs == rhs;
2839 }
2840
2841 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2842 friend bool operator >= ( T lhs, Approx const& rhs ) {
2843 return double(lhs) > rhs.m_value || lhs == rhs;
2844 }
2845
2846 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2847 friend bool operator >= ( Approx const& lhs, T rhs ) {
2848 return lhs.m_value > double(rhs) || lhs == rhs;
2849 }
2850
2851 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2852 Approx& epsilon( T newEpsilon ) {
2853 m_epsilon = double(newEpsilon);
2854 return *this;
2855 }
2856
2857 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2858 Approx& margin( T newMargin ) {
2859 m_margin = double(newMargin);
2860 return *this;
2861 }
2862
2863 template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
2864 Approx& scale( T newScale ) {
2865 m_scale = double(newScale);
2866 return *this;
2867 }
2868
2869 #else
2870
2871 Approx operator()( double value ) {
2872 Approx approx( value );
2873 approx.epsilon( m_epsilon );
2874 approx.margin( m_margin );
2875 approx.scale( m_scale );
2876 return approx;
2877 }
2878
2879 friend bool operator == ( double lhs, Approx const& rhs ) {
2880 // Thanks to Richard Harris for his help refining this formula
2881 bool relativeOK = std::fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( std::fabs(lhs), std::fabs(rhs.m_value) ) );
2882 if (relativeOK) {
2883 return true;
2884 }
2885 return std::fabs(lhs - rhs.m_value) < rhs.m_margin;
2886 }
2887
2888 friend bool operator == ( Approx const& lhs, double rhs ) {
2889 return operator==( rhs, lhs );
2890 }
2891
2892 friend bool operator != ( double lhs, Approx const& rhs ) {
2893 return !operator==( lhs, rhs );
2894 }
2895
2896 friend bool operator != ( Approx const& lhs, double rhs ) {
2897 return !operator==( rhs, lhs );
2898 }
2899
2900 friend bool operator <= ( double lhs, Approx const& rhs ) {
2901 return lhs < rhs.m_value || lhs == rhs;
2902 }
2903
2904 friend bool operator <= ( Approx const& lhs, double rhs ) {
2905 return lhs.m_value < rhs || lhs == rhs;
2906 }
2907
2908 friend bool operator >= ( double lhs, Approx const& rhs ) {
2909 return lhs > rhs.m_value || lhs == rhs;
2910 }
2911
2912 friend bool operator >= ( Approx const& lhs, double rhs ) {
2913 return lhs.m_value > rhs || lhs == rhs;
2914 }
2915
2916 Approx& epsilon( double newEpsilon ) {
2917 m_epsilon = newEpsilon;
2918 return *this;
2919 }
2920
2921 Approx& margin( double newMargin ) {
2922 m_margin = newMargin;
2923 return *this;
2924 }
2925
2926 Approx& scale( double newScale ) {
2927 m_scale = newScale;
2928 return *this;
2929 }
2930 #endif
2931
2932 std::string toString() const {
2933 std::ostringstream oss;
2934 oss << "Approx( " << Catch::toString( m_value ) << " )";
2935 return oss.str();
2936 }
2937
2938 private:
2939 double m_epsilon;
2940 double m_margin;
2941 double m_scale;
2942 double m_value;
2943 };
2944 }
2945
2946 template<>
2947 inline std::string toString<Detail::Approx>( Detail::Approx const& value ) {
2948 return value.toString();
2949 }
2950
2951 } // end namespace Catch
2952
2953 // #included from: internal/catch_matchers_string.h
2954 #define TWOBLUECUBES_CATCH_MATCHERS_STRING_H_INCLUDED
2955
2956 namespace Catch {
2957 namespace Matchers {
2958
2959 namespace StdString {
2960
2961 struct CasedString
2962 {
2963 CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
2964 std::string adjustString( std::string const& str ) const;
2965 std::string caseSensitivitySuffix() const;
2966
2967 CaseSensitive::Choice m_caseSensitivity;
2968 std::string m_str;
2969 };
2970
2971 struct StringMatcherBase : MatcherBase<std::string> {
2972 StringMatcherBase( std::string const& operation, CasedString const& comparator );
2973 virtual std::string describe() const CATCH_OVERRIDE;
2974
2975 CasedString m_comparator;
2976 std::string m_operation;
2977 };
2978
2979 struct EqualsMatcher : StringMatcherBase {
2980 EqualsMatcher( CasedString const& comparator );
2981 virtual bool match( std::string const& source ) const CATCH_OVERRIDE;
2982 };
2983 struct ContainsMatcher : StringMatcherBase {
2984 ContainsMatcher( CasedString const& comparator );
2985 virtual bool match( std::string const& source ) const CATCH_OVERRIDE;
2986 };
2987 struct StartsWithMatcher : StringMatcherBase {
2988 StartsWithMatcher( CasedString const& comparator );
2989 virtual bool match( std::string const& source ) const CATCH_OVERRIDE;
2990 };
2991 struct EndsWithMatcher : StringMatcherBase {
2992 EndsWithMatcher( CasedString const& comparator );
2993 virtual bool match( std::string const& source ) const CATCH_OVERRIDE;
2994 };
2995
2996 } // namespace StdString
2997
2998 // The following functions create the actual matcher objects.
2999 // This allows the types to be inferred
3000
3001 StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3002 StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3003 StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3004 StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
3005
3006 } // namespace Matchers
3007 } // namespace Catch
3008
3009 // #included from: internal/catch_matchers_vector.h
3010 #define TWOBLUECUBES_CATCH_MATCHERS_VECTOR_H_INCLUDED
3011
3012 namespace Catch {
3013 namespace Matchers {
3014
3015 namespace Vector {
3016
3017 template<typename T>
3018 struct ContainsElementMatcher : MatcherBase<std::vector<T>, T> {
3019
3020 ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
3021
3022 bool match(std::vector<T> const &v) const CATCH_OVERRIDE {
3023 return std::find(v.begin(), v.end(), m_comparator) != v.end();
3024 }
3025
3026 virtual std::string describe() const CATCH_OVERRIDE {
3027 return "Contains: " + Catch::toString( m_comparator );
3028 }
3029
3030 T const& m_comparator;
3031 };
3032
3033 template<typename T>
3034 struct ContainsMatcher : MatcherBase<std::vector<T>, std::vector<T> > {
3035
3036 ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
3037
3038 bool match(std::vector<T> const &v) const CATCH_OVERRIDE {
3039 // !TBD: see note in EqualsMatcher
3040 if (m_comparator.size() > v.size())
3041 return false;
3042 for (size_t i = 0; i < m_comparator.size(); ++i)
3043 if (std::find(v.begin(), v.end(), m_comparator[i]) == v.end())
3044 return false;
3045 return true;
3046 }
3047 virtual std::string describe() const CATCH_OVERRIDE {
3048 return "Contains: " + Catch::toString( m_comparator );
3049 }
3050
3051 std::vector<T> const& m_comparator;
3052 };
3053
3054 template<typename T>
3055 struct EqualsMatcher : MatcherBase<std::vector<T>, std::vector<T> > {
3056
3057 EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
3058
3059 bool match(std::vector<T> const &v) const CATCH_OVERRIDE {
3060 // !TBD: This currently works if all elements can be compared using !=
3061 // - a more general approach would be via a compare template that defaults
3062 // to using !=. but could be specialised for, e.g. std::vector<T> etc
3063 // - then just call that directly
3064 if (m_comparator.size() != v.size())
3065 return false;
3066 for (size_t i = 0; i < v.size(); ++i)
3067 if (m_comparator[i] != v[i])
3068 return false;
3069 return true;
3070 }
3071 virtual std::string describe() const CATCH_OVERRIDE {
3072 return "Equals: " + Catch::toString( m_comparator );
3073 }
3074 std::vector<T> const& m_comparator;
3075 };
3076
3077 } // namespace Vector
3078
3079 // The following functions create the actual matcher objects.
3080 // This allows the types to be inferred
3081
3082 template<typename T>
3083 Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
3084 return Vector::ContainsMatcher<T>( comparator );
3085 }
3086
3087 template<typename T>
3088 Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
3089 return Vector::ContainsElementMatcher<T>( comparator );
3090 }
3091
3092 template<typename T>
3093 Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
3094 return Vector::EqualsMatcher<T>( comparator );
3095 }
3096
3097 } // namespace Matchers
3098 } // namespace Catch
3099
3100 // #included from: internal/catch_interfaces_tag_alias_registry.h
3101 #define TWOBLUECUBES_CATCH_INTERFACES_TAG_ALIAS_REGISTRY_H_INCLUDED
3102
3103 // #included from: catch_tag_alias.h
3104 #define TWOBLUECUBES_CATCH_TAG_ALIAS_H_INCLUDED
3105
3106 #include <string>
3107
3108 namespace Catch {
3109
3110 struct TagAlias {
3111 TagAlias( std::string const& _tag, SourceLineInfo _lineInfo ) : tag( _tag ), lineInfo( _lineInfo ) {}
3112
3113 std::string tag;
3114 SourceLineInfo lineInfo;
3115 };
3116
3117 struct RegistrarForTagAliases {
3118 RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
3119 };
3120
3121 } // end namespace Catch
3122
3123 #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); }
3124 // #included from: catch_option.hpp
3125 #define TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED
3126
3127 namespace Catch {
3128
3129 // An optional type
3130 template<typename T>
3131 class Option {
3132 public:
3133 Option() : nullableValue( CATCH_NULL ) {}
3134 Option( T const& _value )
3135 : nullableValue( new( storage ) T( _value ) )
3136 {}
3137 Option( Option const& _other )
3138 : nullableValue( _other ? new( storage ) T( *_other ) : CATCH_NULL )
3139 {}
3140
3141 ~Option() {
3142 reset();
3143 }
3144
3145 Option& operator= ( Option const& _other ) {
3146 if( &_other != this ) {
3147 reset();
3148 if( _other )
3149 nullableValue = new( storage ) T( *_other );
3150 }
3151 return *this;
3152 }
3153 Option& operator = ( T const& _value ) {
3154 reset();
3155 nullableValue = new( storage ) T( _value );
3156 return *this;
3157 }
3158
3159 void reset() {
3160 if( nullableValue )
3161 nullableValue->~T();
3162 nullableValue = CATCH_NULL;
3163 }
3164
3165 T& operator*() { return *nullableValue; }
3166 T const& operator*() const { return *nullableValue; }
3167 T* operator->() { return nullableValue; }
3168 const T* operator->() const { return nullableValue; }
3169
3170 T valueOr( T const& defaultValue ) const {
3171 return nullableValue ? *nullableValue : defaultValue;
3172 }
3173
3174 bool some() const { return nullableValue != CATCH_NULL; }
3175 bool none() const { return nullableValue == CATCH_NULL; }
3176
3177 bool operator !() const { return nullableValue == CATCH_NULL; }
3178 operator SafeBool::type() const {
3179 return SafeBool::makeSafe( some() );
3180 }
3181
3182 private:
3183 T *nullableValue;
3184 union {
3185 char storage[sizeof(T)];
3186
3187 // These are here to force alignment for the storage
3188 long double dummy1;
3189 void (*dummy2)();
3190 long double dummy3;
3191 #ifdef CATCH_CONFIG_CPP11_LONG_LONG
3192 long long dummy4;
3193 #endif
3194 };
3195 };
3196
3197 } // end namespace Catch
3198
3199 namespace Catch {
3200
3201 struct ITagAliasRegistry {
3202 virtual ~ITagAliasRegistry();
3203 virtual Option<TagAlias> find( std::string const& alias ) const = 0;
3204 virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
3205
3206 static ITagAliasRegistry const& get();
3207 };
3208
3209 } // end namespace Catch
3210
3211 // These files are included here so the single_include script doesn't put them
3212 // in the conditionally compiled sections
3213 // #included from: internal/catch_test_case_info.h
3214 #define TWOBLUECUBES_CATCH_TEST_CASE_INFO_H_INCLUDED
3215
3216 #include <string>
3217 #include <set>
3218
3219 #ifdef __clang__
3220 #pragma clang diagnostic push
3221 #pragma clang diagnostic ignored "-Wpadded"
3222 #endif
3223
3224 namespace Catch {
3225
3226 struct ITestCase;
3227
3228 struct TestCaseInfo {
3229 enum SpecialProperties{
3230 None = 0,
3231 IsHidden = 1 << 1,
3232 ShouldFail = 1 << 2,
3233 MayFail = 1 << 3,
3234 Throws = 1 << 4,
3235 NonPortable = 1 << 5
3236 };
3237
3238 TestCaseInfo( std::string const& _name,
3239 std::string const& _className,
3240 std::string const& _description,
3241 std::set<std::string> const& _tags,
3242 SourceLineInfo const& _lineInfo );
3243
3244 TestCaseInfo( TestCaseInfo const& other );
3245
3246 friend void setTags( TestCaseInfo& testCaseInfo, std::set<std::string> const& tags );
3247
3248 bool isHidden() const;
3249 bool throws() const;
3250 bool okToFail() const;
3251 bool expectedToFail() const;
3252
3253 std::string name;
3254 std::string className;
3255 std::string description;
3256 std::set<std::string> tags;
3257 std::set<std::string> lcaseTags;
3258 std::string tagsAsString;
3259 SourceLineInfo lineInfo;
3260 SpecialProperties properties;
3261 };
3262
3263 class TestCase : public TestCaseInfo {
3264 public:
3265
3266 TestCase( ITestCase* testCase, TestCaseInfo const& info );
3267 TestCase( TestCase const& other );
3268
3269 TestCase withName( std::string const& _newName ) const;
3270
3271 void invoke() const;
3272
3273 TestCaseInfo const& getTestCaseInfo() const;
3274
3275 void swap( TestCase& other );
3276 bool operator == ( TestCase const& other ) const;
3277 bool operator < ( TestCase const& other ) const;
3278 TestCase& operator = ( TestCase const& other );
3279
3280 private:
3281 Ptr<ITestCase> test;
3282 };
3283
3284 TestCase makeTestCase( ITestCase* testCase,
3285 std::string const& className,
3286 std::string const& name,
3287 std::string const& description,
3288 SourceLineInfo const& lineInfo );
3289 }
3290
3291 #ifdef __clang__
3292 #pragma clang diagnostic pop
3293 #endif
3294
3295
3296 #ifdef __OBJC__
3297 // #included from: internal/catch_objc.hpp
3298 #define TWOBLUECUBES_CATCH_OBJC_HPP_INCLUDED
3299
3300 #import <objc/runtime.h>
3301
3302 #include <string>
3303
3304 // NB. Any general catch headers included here must be included
3305 // in catch.hpp first to make sure they are included by the single
3306 // header for non obj-usage
3307
3308 ///////////////////////////////////////////////////////////////////////////////
3309 // This protocol is really only here for (self) documenting purposes, since
3310 // all its methods are optional.
3311 @protocol OcFixture
3312
3313 @optional
3314
3315 -(void) setUp;
3316 -(void) tearDown;
3317
3318 @end
3319
3320 namespace Catch {
3321
3322 class OcMethod : public SharedImpl<ITestCase> {
3323
3324 public:
3325 OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
3326
3327 virtual void invoke() const {
3328 id obj = [[m_cls alloc] init];
3329
3330 performOptionalSelector( obj, @selector(setUp) );
3331 performOptionalSelector( obj, m_sel );
3332 performOptionalSelector( obj, @selector(tearDown) );
3333
3334 arcSafeRelease( obj );
3335 }
3336 private:
3337 virtual ~OcMethod() {}
3338
3339 Class m_cls;
3340 SEL m_sel;
3341 };
3342
3343 namespace Detail{
3344
3345 inline std::string getAnnotation( Class cls,
3346 std::string const& annotationName,
3347 std::string const& testCaseName ) {
3348 NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
3349 SEL sel = NSSelectorFromString( selStr );
3350 arcSafeRelease( selStr );
3351 id value = performOptionalSelector( cls, sel );
3352 if( value )
3353 return [(NSString*)value UTF8String];
3354 return "";
3355 }
3356 }
3357
3358 inline size_t registerTestMethods() {
3359 size_t noTestMethods = 0;
3360 int noClasses = objc_getClassList( CATCH_NULL, 0 );
3361
3362 Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
3363 objc_getClassList( classes, noClasses );
3364
3365 for( int c = 0; c < noClasses; c++ ) {
3366 Class cls = classes[c];
3367 {
3368 u_int count;
3369 Method* methods = class_copyMethodList( cls, &count );
3370 for( u_int m = 0; m < count ; m++ ) {
3371 SEL selector = method_getName(methods[m]);
3372 std::string methodName = sel_getName(selector);
3373 if( startsWith( methodName, "Catch_TestCase_" ) ) {
3374 std::string testCaseName = methodName.substr( 15 );
3375 std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
3376 std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
3377 const char* className = class_getName( cls );
3378
3379 getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo() ) );
3380 noTestMethods++;
3381 }
3382 }
3383 free(methods);
3384 }
3385 }
3386 return noTestMethods;
3387 }
3388
3389 namespace Matchers {
3390 namespace Impl {
3391 namespace NSStringMatchers {
3392
3393 struct StringHolder : MatcherBase<NSString*>{
3394 StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
3395 StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
3396 StringHolder() {
3397 arcSafeRelease( m_substr );
3398 }
3399
3400 virtual bool match( NSString* arg ) const CATCH_OVERRIDE {
3401 return false;
3402 }
3403
3404 NSString* m_substr;
3405 };
3406
3407 struct Equals : StringHolder {
3408 Equals( NSString* substr ) : StringHolder( substr ){}
3409
3410 virtual bool match( NSString* str ) const CATCH_OVERRIDE {
3411 return (str != nil || m_substr == nil ) &&
3412 [str isEqualToString:m_substr];
3413 }
3414
3415 virtual std::string describe() const CATCH_OVERRIDE {
3416 return "equals string: " + Catch::toString( m_substr );
3417 }
3418 };
3419
3420 struct Contains : StringHolder {
3421 Contains( NSString* substr ) : StringHolder( substr ){}
3422
3423 virtual bool match( NSString* str ) const {
3424 return (str != nil || m_substr == nil ) &&
3425 [str rangeOfString:m_substr].location != NSNotFound;
3426 }
3427
3428 virtual std::string describe() const CATCH_OVERRIDE {
3429 return "contains string: " + Catch::toString( m_substr );
3430 }
3431 };
3432
3433 struct StartsWith : StringHolder {
3434 StartsWith( NSString* substr ) : StringHolder( substr ){}
3435
3436 virtual bool match( NSString* str ) const {
3437 return (str != nil || m_substr == nil ) &&
3438 [str rangeOfString:m_substr].location == 0;
3439 }
3440
3441 virtual std::string describe() const CATCH_OVERRIDE {
3442 return "starts with: " + Catch::toString( m_substr );
3443 }
3444 };
3445 struct EndsWith : StringHolder {
3446 EndsWith( NSString* substr ) : StringHolder( substr ){}
3447
3448 virtual bool match( NSString* str ) const {
3449 return (str != nil || m_substr == nil ) &&
3450 [str rangeOfString:m_substr].location == [str length] - [m_substr length];
3451 }
3452
3453 virtual std::string describe() const CATCH_OVERRIDE {
3454 return "ends with: " + Catch::toString( m_substr );
3455 }
3456 };
3457
3458 } // namespace NSStringMatchers
3459 } // namespace Impl
3460
3461 inline Impl::NSStringMatchers::Equals
3462 Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
3463
3464 inline Impl::NSStringMatchers::Contains
3465 Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
3466
3467 inline Impl::NSStringMatchers::StartsWith
3468 StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
3469
3470 inline Impl::NSStringMatchers::EndsWith
3471 EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
3472
3473 } // namespace Matchers
3474
3475 using namespace Matchers;
3476
3477 } // namespace Catch
3478
3479 ///////////////////////////////////////////////////////////////////////////////
3480 #define OC_TEST_CASE( name, desc )\
3481 +(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Name_test ) \
3482 {\
3483 return @ name; \
3484 }\
3485 +(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Description_test ) \
3486 { \
3487 return @ desc; \
3488 } \
3489 -(void) INTERNAL_CATCH_UNIQUE_NAME( Catch_TestCase_test )
3490
3491 #endif
3492
3493 #ifdef CATCH_IMPL
3494
3495 // !TBD: Move the leak detector code into a separate header
3496 #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
3497 #include <crtdbg.h>
3498 class LeakDetector {
3499 public:
3500 LeakDetector() {
3501 int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
3502 flag |= _CRTDBG_LEAK_CHECK_DF;
3503 flag |= _CRTDBG_ALLOC_MEM_DF;
3504 _CrtSetDbgFlag(flag);
3505 _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
3506 _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
3507 // Change this to leaking allocation's number to break there
3508 _CrtSetBreakAlloc(-1);
3509 }
3510 };
3511 #else
3512 class LeakDetector {};
3513 #endif
3514
3515 LeakDetector leakDetector;
3516
3517 // #included from: internal/catch_impl.hpp
3518 #define TWOBLUECUBES_CATCH_IMPL_HPP_INCLUDED
3519
3520 // Collect all the implementation files together here
3521 // These are the equivalent of what would usually be cpp files
3522
3523 #ifdef __clang__
3524 #pragma clang diagnostic push
3525 #pragma clang diagnostic ignored "-Wweak-vtables"
3526 #endif
3527
3528 // #included from: ../catch_session.hpp
3529 #define TWOBLUECUBES_CATCH_RUNNER_HPP_INCLUDED
3530
3531 // #included from: internal/catch_commandline.hpp
3532 #define TWOBLUECUBES_CATCH_COMMANDLINE_HPP_INCLUDED
3533
3534 // #included from: catch_config.hpp
3535 #define TWOBLUECUBES_CATCH_CONFIG_HPP_INCLUDED
3536
3537 // #included from: catch_test_spec_parser.hpp
3538 #define TWOBLUECUBES_CATCH_TEST_SPEC_PARSER_HPP_INCLUDED
3539
3540 #ifdef __clang__
3541 #pragma clang diagnostic push
3542 #pragma clang diagnostic ignored "-Wpadded"
3543 #endif
3544
3545 // #included from: catch_test_spec.hpp
3546 #define TWOBLUECUBES_CATCH_TEST_SPEC_HPP_INCLUDED
3547
3548 #ifdef __clang__
3549 #pragma clang diagnostic push
3550 #pragma clang diagnostic ignored "-Wpadded"
3551 #endif
3552
3553 // #included from: catch_wildcard_pattern.hpp
3554 #define TWOBLUECUBES_CATCH_WILDCARD_PATTERN_HPP_INCLUDED
3555
3556 #include <stdexcept>
3557
3558 namespace Catch
3559 {
3560 class WildcardPattern {
3561 enum WildcardPosition {
3562 NoWildcard = 0,
3563 WildcardAtStart = 1,
3564 WildcardAtEnd = 2,
3565 WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
3566 };
3567
3568 public:
3569
3570 WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity )
3571 : m_caseSensitivity( caseSensitivity ),
3572 m_wildcard( NoWildcard ),
3573 m_pattern( adjustCase( pattern ) )
3574 {
3575 if( startsWith( m_pattern, '*' ) ) {
3576 m_pattern = m_pattern.substr( 1 );
3577 m_wildcard = WildcardAtStart;
3578 }
3579 if( endsWith( m_pattern, '*' ) ) {
3580 m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
3581 m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
3582 }
3583 }
3584 virtual ~WildcardPattern();
3585 virtual bool matches( std::string const& str ) const {
3586 switch( m_wildcard ) {
3587 case NoWildcard:
3588 return m_pattern == adjustCase( str );
3589 case WildcardAtStart:
3590 return endsWith( adjustCase( str ), m_pattern );
3591 case WildcardAtEnd:
3592 return startsWith( adjustCase( str ), m_pattern );
3593 case WildcardAtBothEnds:
3594 return contains( adjustCase( str ), m_pattern );
3595 }
3596
3597 #ifdef __clang__
3598 #pragma clang diagnostic push
3599 #pragma clang diagnostic ignored "-Wunreachable-code"
3600 #endif
3601 throw std::logic_error( "Unknown enum" );
3602 #ifdef __clang__
3603 #pragma clang diagnostic pop
3604 #endif
3605 }
3606 private:
3607 std::string adjustCase( std::string const& str ) const {
3608 return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
3609 }
3610 CaseSensitive::Choice m_caseSensitivity;
3611 WildcardPosition m_wildcard;
3612 std::string m_pattern;
3613 };
3614 }
3615
3616 #include <string>
3617 #include <vector>
3618
3619 namespace Catch {
3620
3621 class TestSpec {
3622 struct Pattern : SharedImpl<> {
3623 virtual ~Pattern();
3624 virtual bool matches( TestCaseInfo const& testCase ) const = 0;
3625 };
3626 class NamePattern : public Pattern {
3627 public:
3628 NamePattern( std::string const& name )
3629 : m_wildcardPattern( toLower( name ), CaseSensitive::No )
3630 {}
3631 virtual ~NamePattern();
3632 virtual bool matches( TestCaseInfo const& testCase ) const {
3633 return m_wildcardPattern.matches( toLower( testCase.name ) );
3634 }
3635 private:
3636 WildcardPattern m_wildcardPattern;
3637 };
3638
3639 class TagPattern : public Pattern {
3640 public:
3641 TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
3642 virtual ~TagPattern();
3643 virtual bool matches( TestCaseInfo const& testCase ) const {
3644 return testCase.lcaseTags.find( m_tag ) != testCase.lcaseTags.end();
3645 }
3646 private:
3647 std::string m_tag;
3648 };
3649
3650 class ExcludedPattern : public Pattern {
3651 public:
3652 ExcludedPattern( Ptr<Pattern> const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
3653 virtual ~ExcludedPattern();
3654 virtual bool matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
3655 private:
3656 Ptr<Pattern> m_underlyingPattern;
3657 };
3658
3659 struct Filter {
3660 std::vector<Ptr<Pattern> > m_patterns;
3661
3662 bool matches( TestCaseInfo const& testCase ) const {
3663 // All patterns in a filter must match for the filter to be a match
3664 for( std::vector<Ptr<Pattern> >::const_iterator it = m_patterns.begin(), itEnd = m_patterns.end(); it != itEnd; ++it ) {
3665 if( !(*it)->matches( testCase ) )
3666 return false;
3667 }
3668 return true;
3669 }
3670 };
3671
3672 public:
3673 bool hasFilters() const {
3674 return !m_filters.empty();
3675 }
3676 bool matches( TestCaseInfo const& testCase ) const {
3677 // A TestSpec matches if any filter matches
3678 for( std::vector<Filter>::const_iterator it = m_filters.begin(), itEnd = m_filters.end(); it != itEnd; ++it )
3679 if( it->matches( testCase ) )
3680 return true;
3681 return false;
3682 }
3683
3684 private:
3685 std::vector<Filter> m_filters;
3686
3687 friend class TestSpecParser;
3688 };
3689 }
3690
3691 #ifdef __clang__
3692 #pragma clang diagnostic pop
3693 #endif
3694
3695 namespace Catch {
3696
3697 class TestSpecParser {
3698 enum Mode{ None, Name, QuotedName, Tag, EscapedName };
3699 Mode m_mode;
3700 bool m_exclusion;
3701 std::size_t m_start, m_pos;
3702 std::string m_arg;
3703 std::vector<std::size_t> m_escapeChars;
3704 TestSpec::Filter m_currentFilter;
3705 TestSpec m_testSpec;
3706 ITagAliasRegistry const* m_tagAliases;
3707
3708 public:
3709 TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
3710
3711 TestSpecParser& parse( std::string const& arg ) {
3712 m_mode = None;
3713 m_exclusion = false;
3714 m_start = std::string::npos;
3715 m_arg = m_tagAliases->expandAliases( arg );
3716 m_escapeChars.clear();
3717 for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
3718 visitChar( m_arg[m_pos] );
3719 if( m_mode == Name )
3720 addPattern<TestSpec::NamePattern>();
3721 return *this;
3722 }
3723 TestSpec testSpec() {
3724 addFilter();
3725 return m_testSpec;
3726 }
3727 private:
3728 void visitChar( char c ) {
3729 if( m_mode == None ) {
3730 switch( c ) {
3731 case ' ': return;
3732 case '~': m_exclusion = true; return;
3733 case '[': return startNewMode( Tag, ++m_pos );
3734 case '"': return startNewMode( QuotedName, ++m_pos );
3735 case '\\': return escape();
3736 default: startNewMode( Name, m_pos ); break;
3737 }
3738 }
3739 if( m_mode == Name ) {
3740 if( c == ',' ) {
3741 addPattern<TestSpec::NamePattern>();
3742 addFilter();
3743 }
3744 else if( c == '[' ) {
3745 if( subString() == "exclude:" )
3746 m_exclusion = true;
3747 else
3748 addPattern<TestSpec::NamePattern>();
3749 startNewMode( Tag, ++m_pos );
3750 }
3751 else if( c == '\\' )
3752 escape();
3753 }
3754 else if( m_mode == EscapedName )
3755 m_mode = Name;
3756 else if( m_mode == QuotedName && c == '"' )
3757 addPattern<TestSpec::NamePattern>();
3758 else if( m_mode == Tag && c == ']' )
3759 addPattern<TestSpec::TagPattern>();
3760 }
3761 void startNewMode( Mode mode, std::size_t start ) {
3762 m_mode = mode;
3763 m_start = start;
3764 }
3765 void escape() {
3766 if( m_mode == None )
3767 m_start = m_pos;
3768 m_mode = EscapedName;
3769 m_escapeChars.push_back( m_pos );
3770 }
3771 std::string subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
3772 template<typename T>
3773 void addPattern() {
3774 std::string token = subString();
3775 for( size_t i = 0; i < m_escapeChars.size(); ++i )
3776 token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
3777 m_escapeChars.clear();
3778 if( startsWith( token, "exclude:" ) ) {
3779 m_exclusion = true;
3780 token = token.substr( 8 );
3781 }
3782 if( !token.empty() ) {
3783 Ptr<TestSpec::Pattern> pattern = new T( token );
3784 if( m_exclusion )
3785 pattern = new TestSpec::ExcludedPattern( pattern );
3786 m_currentFilter.m_patterns.push_back( pattern );
3787 }
3788 m_exclusion = false;
3789 m_mode = None;
3790 }
3791 void addFilter() {
3792 if( !m_currentFilter.m_patterns.empty() ) {
3793 m_testSpec.m_filters.push_back( m_currentFilter );
3794 m_currentFilter = TestSpec::Filter();
3795 }
3796 }
3797 };
3798 inline TestSpec parseTestSpec( std::string const& arg ) {
3799 return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
3800 }
3801
3802 } // namespace Catch
3803
3804 #ifdef __clang__
3805 #pragma clang diagnostic pop
3806 #endif
3807
3808 // #included from: catch_interfaces_config.h
3809 #define TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED
3810
3811 #include <iosfwd>
3812 #include <string>
3813 #include <vector>
3814
3815 namespace Catch {
3816
3817 struct Verbosity { enum Level {
3818 NoOutput = 0,
3819 Quiet,
3820 Normal
3821 }; };
3822
3823 struct WarnAbout { enum What {
3824 Nothing = 0x00,
3825 NoAssertions = 0x01
3826 }; };
3827
3828 struct ShowDurations { enum OrNot {
3829 DefaultForReporter,
3830 Always,
3831 Never
3832 }; };
3833 struct RunTests { enum InWhatOrder {
3834 InDeclarationOrder,
3835 InLexicographicalOrder,
3836 InRandomOrder
3837 }; };
3838 struct UseColour { enum YesOrNo {
3839 Auto,
3840 Yes,
3841 No
3842 }; };
3843
3844 class TestSpec;
3845
3846 struct IConfig : IShared {
3847
3848 virtual ~IConfig();
3849
3850 virtual bool allowThrows() const = 0;
3851 virtual std::ostream& stream() const = 0;
3852 virtual std::string name() const = 0;
3853 virtual bool includeSuccessfulResults() const = 0;
3854 virtual bool shouldDebugBreak() const = 0;
3855 virtual bool warnAboutMissingAssertions() const = 0;
3856 virtual int abortAfter() const = 0;
3857 virtual bool showInvisibles() const = 0;
3858 virtual ShowDurations::OrNot showDurations() const = 0;
3859 virtual TestSpec const& testSpec() const = 0;
3860 virtual RunTests::InWhatOrder runOrder() const = 0;
3861 virtual unsigned int rngSeed() const = 0;
3862 virtual UseColour::YesOrNo useColour() const = 0;
3863 virtual std::vector<std::string> const& getSectionsToRun() const = 0;
3864
3865 };
3866 }
3867
3868 // #included from: catch_stream.h
3869 #define TWOBLUECUBES_CATCH_STREAM_H_INCLUDED
3870
3871 // #included from: catch_streambuf.h
3872 #define TWOBLUECUBES_CATCH_STREAMBUF_H_INCLUDED
3873
3874 #include <streambuf>
3875
3876 namespace Catch {
3877
3878 class StreamBufBase : public std::streambuf {
3879 public:
3880 virtual ~StreamBufBase() CATCH_NOEXCEPT;
3881 };
3882 }
3883
3884 #include <streambuf>
3885 #include <ostream>
3886 #include <fstream>
3887 #include <memory>
3888
3889 namespace Catch {
3890
3891 std::ostream& cout();
3892 std::ostream& cerr();
3893
3894 struct IStream {
3895 virtual ~IStream() CATCH_NOEXCEPT;
3896 virtual std::ostream& stream() const = 0;
3897 };
3898
3899 class FileStream : public IStream {
3900 mutable std::ofstream m_ofs;
3901 public:
3902 FileStream( std::string const& filename );
3903 virtual ~FileStream() CATCH_NOEXCEPT;
3904 public: // IStream
3905 virtual std::ostream& stream() const CATCH_OVERRIDE;
3906 };
3907
3908 class CoutStream : public IStream {
3909 mutable std::ostream m_os;
3910 public:
3911 CoutStream();
3912 virtual ~CoutStream() CATCH_NOEXCEPT;
3913
3914 public: // IStream
3915 virtual std::ostream& stream() const CATCH_OVERRIDE;
3916 };
3917
3918 class DebugOutStream : public IStream {
3919 CATCH_AUTO_PTR( StreamBufBase ) m_streamBuf;
3920 mutable std::ostream m_os;
3921 public:
3922 DebugOutStream();
3923 virtual ~DebugOutStream() CATCH_NOEXCEPT;
3924
3925 public: // IStream
3926 virtual std::ostream& stream() const CATCH_OVERRIDE;
3927 };
3928 }
3929
3930 #include <memory>
3931 #include <vector>
3932 #include <string>
3933 #include <stdexcept>
3934
3935 #ifndef CATCH_CONFIG_CONSOLE_WIDTH
3936 #define CATCH_CONFIG_CONSOLE_WIDTH 80
3937 #endif
3938
3939 namespace Catch {
3940
3941 struct ConfigData {
3942
3943 ConfigData()
3944 : listTests( false ),
3945 listTags( false ),
3946 listReporters( false ),
3947 listTestNamesOnly( false ),
3948 listExtraInfo( false ),
3949 showSuccessfulTests( false ),
3950 shouldDebugBreak( false ),
3951 noThrow( false ),
3952 showHelp( false ),
3953 showInvisibles( false ),
3954 filenamesAsTags( false ),
3955 abortAfter( -1 ),
3956 rngSeed( 0 ),
3957 verbosity( Verbosity::Normal ),
3958 warnings( WarnAbout::Nothing ),
3959 showDurations( ShowDurations::DefaultForReporter ),
3960 runOrder( RunTests::InDeclarationOrder ),
3961 useColour( UseColour::Auto )
3962 {}
3963
3964 bool listTests;
3965 bool listTags;
3966 bool listReporters;
3967 bool listTestNamesOnly;
3968 bool listExtraInfo;
3969
3970 bool showSuccessfulTests;
3971 bool shouldDebugBreak;
3972 bool noThrow;
3973 bool showHelp;
3974 bool showInvisibles;
3975 bool filenamesAsTags;
3976
3977 int abortAfter;
3978 unsigned int rngSeed;
3979
3980 Verbosity::Level verbosity;
3981 WarnAbout::What warnings;
3982 ShowDurations::OrNot showDurations;
3983 RunTests::InWhatOrder runOrder;
3984 UseColour::YesOrNo useColour;
3985
3986 std::string outputFilename;
3987 std::string name;
3988 std::string processName;
3989
3990 std::vector<std::string> reporterNames;
3991 std::vector<std::string> testsOrTags;
3992 std::vector<std::string> sectionsToRun;
3993 };
3994
3995 class Config : public SharedImpl<IConfig> {
3996 private:
3997 Config( Config const& other );
3998 Config& operator = ( Config const& other );
3999 virtual void dummy();
4000 public:
4001
4002 Config()
4003 {}
4004
4005 Config( ConfigData const& data )
4006 : m_data( data ),
4007 m_stream( openStream() )
4008 {
4009 if( !data.testsOrTags.empty() ) {
4010 TestSpecParser parser( ITagAliasRegistry::get() );
4011 for( std::size_t i = 0; i < data.testsOrTags.size(); ++i )
4012 parser.parse( data.testsOrTags[i] );
4013 m_testSpec = parser.testSpec();
4014 }
4015 }
4016
4017 virtual ~Config() {}
4018
4019 std::string const& getFilename() const {
4020 return m_data.outputFilename ;
4021 }
4022
4023 bool listTests() const { return m_data.listTests; }
4024 bool listTestNamesOnly() const { return m_data.listTestNamesOnly; }
4025 bool listTags() const { return m_data.listTags; }
4026 bool listReporters() const { return m_data.listReporters; }
4027 bool listExtraInfo() const { return m_data.listExtraInfo; }
4028
4029 std::string getProcessName() const { return m_data.processName; }
4030
4031 std::vector<std::string> const& getReporterNames() const { return m_data.reporterNames; }
4032 std::vector<std::string> const& getSectionsToRun() const CATCH_OVERRIDE { return m_data.sectionsToRun; }
4033
4034 virtual TestSpec const& testSpec() const CATCH_OVERRIDE { return m_testSpec; }
4035
4036 bool showHelp() const { return m_data.showHelp; }
4037
4038 // IConfig interface
4039 virtual bool allowThrows() const CATCH_OVERRIDE { return !m_data.noThrow; }
4040 virtual std::ostream& stream() const CATCH_OVERRIDE { return m_stream->stream(); }
4041 virtual std::string name() const CATCH_OVERRIDE { return m_data.name.empty() ? m_data.processName : m_data.name; }
4042 virtual bool includeSuccessfulResults() const CATCH_OVERRIDE { return m_data.showSuccessfulTests; }
4043 virtual bool warnAboutMissingAssertions() const CATCH_OVERRIDE { return m_data.warnings & WarnAbout::NoAssertions; }
4044 virtual ShowDurations::OrNot showDurations() const CATCH_OVERRIDE { return m_data.showDurations; }
4045 virtual RunTests::InWhatOrder runOrder() const CATCH_OVERRIDE { return m_data.runOrder; }
4046 virtual unsigned int rngSeed() const CATCH_OVERRIDE { return m_data.rngSeed; }
4047 virtual UseColour::YesOrNo useColour() const CATCH_OVERRIDE { return m_data.useColour; }
4048 virtual bool shouldDebugBreak() const CATCH_OVERRIDE { return m_data.shouldDebugBreak; }
4049 virtual int abortAfter() const CATCH_OVERRIDE { return m_data.abortAfter; }
4050 virtual bool showInvisibles() const CATCH_OVERRIDE { return m_data.showInvisibles; }
4051
4052 private:
4053
4054 IStream const* openStream() {
4055 if( m_data.outputFilename.empty() )
4056 return new CoutStream();
4057 else if( m_data.outputFilename[0] == '%' ) {
4058 if( m_data.outputFilename == "%debug" )
4059 return new DebugOutStream();
4060 else
4061 throw std::domain_error( "Unrecognised stream: " + m_data.outputFilename );
4062 }
4063 else
4064 return new FileStream( m_data.outputFilename );
4065 }
4066 ConfigData m_data;
4067
4068 CATCH_AUTO_PTR( IStream const ) m_stream;
4069 TestSpec m_testSpec;
4070 };
4071
4072 } // end namespace Catch
4073
4074 // #included from: catch_clara.h
4075 #define TWOBLUECUBES_CATCH_CLARA_H_INCLUDED
4076
4077 // Use Catch's value for console width (store Clara's off to the side, if present)
4078 #ifdef CLARA_CONFIG_CONSOLE_WIDTH
4079 #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CLARA_CONFIG_CONSOLE_WIDTH
4080 #undef CLARA_CONFIG_CONSOLE_WIDTH
4081 #endif
4082 #define CLARA_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH
4083
4084 // Declare Clara inside the Catch namespace
4085 #define STITCH_CLARA_OPEN_NAMESPACE namespace Catch {
4086 // #included from: ../external/clara.h
4087
4088 // Version 0.0.2.4
4089
4090 // Only use header guard if we are not using an outer namespace
4091 #if !defined(TWOBLUECUBES_CLARA_H_INCLUDED) || defined(STITCH_CLARA_OPEN_NAMESPACE)
4092
4093 #ifndef STITCH_CLARA_OPEN_NAMESPACE
4094 #define TWOBLUECUBES_CLARA_H_INCLUDED
4095 #define STITCH_CLARA_OPEN_NAMESPACE
4096 #define STITCH_CLARA_CLOSE_NAMESPACE
4097 #else
4098 #define STITCH_CLARA_CLOSE_NAMESPACE }
4099 #endif
4100
4101 #define STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE STITCH_CLARA_OPEN_NAMESPACE
4102
4103 // ----------- #included from tbc_text_format.h -----------
4104
4105 // Only use header guard if we are not using an outer namespace
4106 #if !defined(TBC_TEXT_FORMAT_H_INCLUDED) || defined(STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE)
4107 #ifndef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE
4108 #define TBC_TEXT_FORMAT_H_INCLUDED
4109 #endif
4110
4111 #include <string>
4112 #include <vector>
4113 #include <sstream>
4114 #include <algorithm>
4115 #include <cctype>
4116
4117 // Use optional outer namespace
4118 #ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE
4119 namespace STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE {
4120 #endif
4121
4122 namespace Tbc {
4123
4124 #ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH
4125 const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH;
4126 #else
4127 const unsigned int consoleWidth = 80;
4128 #endif
4129
4130 struct TextAttributes {
4131 TextAttributes()
4132 : initialIndent( std::string::npos ),
4133 indent( 0 ),
4134 width( consoleWidth-1 ),
4135 tabChar( '\t' )
4136 {}
4137
4138 TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; }
4139 TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; }
4140 TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; }
4141 TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; }
4142
4143 std::size_t initialIndent; // indent of first line, or npos
4144 std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos
4145 std::size_t width; // maximum width of text, including indent. Longer text will wrap
4146 char tabChar; // If this char is seen the indent is changed to current pos
4147 };
4148
4149 class Text {
4150 public:
4151 Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() )
4152 : attr( _attr )
4153 {
4154 std::string wrappableChars = " [({.,/|\\-";
4155 std::size_t indent = _attr.initialIndent != std::string::npos
4156 ? _attr.initialIndent
4157 : _attr.indent;
4158 std::string remainder = _str;
4159
4160 while( !remainder.empty() ) {
4161 if( lines.size() >= 1000 ) {
4162 lines.push_back( "... message truncated due to excessive size" );
4163 return;
4164 }
4165 std::size_t tabPos = std::string::npos;
4166 std::size_t width = (std::min)( remainder.size(), _attr.width - indent );
4167 std::size_t pos = remainder.find_first_of( '\n' );
4168 if( pos <= width ) {
4169 width = pos;
4170 }
4171 pos = remainder.find_last_of( _attr.tabChar, width );
4172 if( pos != std::string::npos ) {
4173 tabPos = pos;
4174 if( remainder[width] == '\n' )
4175 width--;
4176 remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 );
4177 }
4178
4179 if( width == remainder.size() ) {
4180 spliceLine( indent, remainder, width );
4181 }
4182 else if( remainder[width] == '\n' ) {
4183 spliceLine( indent, remainder, width );
4184 if( width <= 1 || remainder.size() != 1 )
4185 remainder = remainder.substr( 1 );
4186 indent = _attr.indent;
4187 }
4188 else {
4189 pos = remainder.find_last_of( wrappableChars, width );
4190 if( pos != std::string::npos && pos > 0 ) {
4191 spliceLine( indent, remainder, pos );
4192 if( remainder[0] == ' ' )
4193 remainder = remainder.substr( 1 );
4194 }
4195 else {
4196 spliceLine( indent, remainder, width-1 );
4197 lines.back() += "-";
4198 }
4199 if( lines.size() == 1 )
4200 indent = _attr.indent;
4201 if( tabPos != std::string::npos )
4202 indent += tabPos;
4203 }
4204 }
4205 }
4206
4207 void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) {
4208 lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) );
4209 _remainder = _remainder.substr( _pos );
4210 }
4211
4212 typedef std::vector<std::string>::const_iterator const_iterator;
4213
4214 const_iterator begin() const { return lines.begin(); }
4215 const_iterator end() const { return lines.end(); }
4216 std::string const& last() const { return lines.back(); }
4217 std::size_t size() const { return lines.size(); }
4218 std::string const& operator[]( std::size_t _index ) const { return lines[_index]; }
4219 std::string toString() const {
4220 std::ostringstream oss;
4221 oss << *this;
4222 return oss.str();
4223 }
4224
4225 inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) {
4226 for( Text::const_iterator it = _text.begin(), itEnd = _text.end();
4227 it != itEnd; ++it ) {
4228 if( it != _text.begin() )
4229 _stream << "\n";
4230 _stream << *it;
4231 }
4232 return _stream;
4233 }
4234
4235 private:
4236 std::string str;
4237 TextAttributes attr;
4238 std::vector<std::string> lines;
4239 };
4240
4241 } // end namespace Tbc
4242
4243 #ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE
4244 } // end outer namespace
4245 #endif
4246
4247 #endif // TBC_TEXT_FORMAT_H_INCLUDED
4248
4249 // ----------- end of #include from tbc_text_format.h -----------
4250 // ........... back in clara.h
4251
4252 #undef STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE
4253
4254 // ----------- #included from clara_compilers.h -----------
4255
4256 #ifndef TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED
4257 #define TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED
4258
4259 // Detect a number of compiler features - mostly C++11/14 conformance - by compiler
4260 // The following features are defined:
4261 //
4262 // CLARA_CONFIG_CPP11_NULLPTR : is nullptr supported?
4263 // CLARA_CONFIG_CPP11_NOEXCEPT : is noexcept supported?
4264 // CLARA_CONFIG_CPP11_GENERATED_METHODS : The delete and default keywords for compiler generated methods
4265 // CLARA_CONFIG_CPP11_OVERRIDE : is override supported?
4266 // CLARA_CONFIG_CPP11_UNIQUE_PTR : is unique_ptr supported (otherwise use auto_ptr)
4267
4268 // CLARA_CONFIG_CPP11_OR_GREATER : Is C++11 supported?
4269
4270 // CLARA_CONFIG_VARIADIC_MACROS : are variadic macros supported?
4271
4272 // In general each macro has a _NO_<feature name> form
4273 // (e.g. CLARA_CONFIG_CPP11_NO_NULLPTR) which disables the feature.
4274 // Many features, at point of detection, define an _INTERNAL_ macro, so they
4275 // can be combined, en-mass, with the _NO_ forms later.
4276
4277 // All the C++11 features can be disabled with CLARA_CONFIG_NO_CPP11
4278
4279 #ifdef __clang__
4280
4281 #if __has_feature(cxx_nullptr)
4282 #define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR
4283 #endif
4284
4285 #if __has_feature(cxx_noexcept)
4286 #define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT
4287 #endif
4288
4289 #endif // __clang__
4290
4291 ////////////////////////////////////////////////////////////////////////////////
4292 // GCC
4293 #ifdef __GNUC__
4294
4295 #if __GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__)
4296 #define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR
4297 #endif
4298
4299 // - otherwise more recent versions define __cplusplus >= 201103L
4300 // and will get picked up below
4301
4302 #endif // __GNUC__
4303
4304 ////////////////////////////////////////////////////////////////////////////////
4305 // Visual C++
4306 #ifdef _MSC_VER
4307
4308 #if (_MSC_VER >= 1600)
4309 #define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR
4310 #define CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR
4311 #endif
4312
4313 #if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015))
4314 #define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT
4315 #define CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
4316 #endif
4317
4318 #endif // _MSC_VER
4319
4320 ////////////////////////////////////////////////////////////////////////////////
4321 // C++ language feature support
4322
4323 // catch all support for C++11
4324 #if defined(__cplusplus) && __cplusplus >= 201103L
4325
4326 #define CLARA_CPP11_OR_GREATER
4327
4328 #if !defined(CLARA_INTERNAL_CONFIG_CPP11_NULLPTR)
4329 #define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR
4330 #endif
4331
4332 #ifndef CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT
4333 #define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT
4334 #endif
4335
4336 #ifndef CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
4337 #define CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS
4338 #endif
4339
4340 #if !defined(CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE)
4341 #define CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE
4342 #endif
4343 #if !defined(CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR)
4344 #define CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR
4345 #endif
4346
4347 #endif // __cplusplus >= 201103L
4348
4349 // Now set the actual defines based on the above + anything the user has configured
4350 #if defined(CLARA_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CLARA_CONFIG_CPP11_NO_NULLPTR) && !defined(CLARA_CONFIG_CPP11_NULLPTR) && !defined(CLARA_CONFIG_NO_CPP11)
4351 #define CLARA_CONFIG_CPP11_NULLPTR
4352 #endif
4353 #if defined(CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CLARA_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_CONFIG_NO_CPP11)
4354 #define CLARA_CONFIG_CPP11_NOEXCEPT
4355 #endif
4356 #if defined(CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CLARA_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CLARA_CONFIG_CPP11_GENERATED_METHODS) && !defined(CLARA_CONFIG_NO_CPP11)
4357 #define CLARA_CONFIG_CPP11_GENERATED_METHODS
4358 #endif
4359 #if defined(CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CLARA_CONFIG_NO_OVERRIDE) && !defined(CLARA_CONFIG_CPP11_OVERRIDE) && !defined(CLARA_CONFIG_NO_CPP11)
4360 #define CLARA_CONFIG_CPP11_OVERRIDE
4361 #endif
4362 #if defined(CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CLARA_CONFIG_NO_UNIQUE_PTR) && !defined(CLARA_CONFIG_CPP11_UNIQUE_PTR) && !defined(CLARA_CONFIG_NO_CPP11)
4363 #define CLARA_CONFIG_CPP11_UNIQUE_PTR
4364 #endif
4365
4366 // noexcept support:
4367 #if defined(CLARA_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_NOEXCEPT)
4368 #define CLARA_NOEXCEPT noexcept
4369 # define CLARA_NOEXCEPT_IS(x) noexcept(x)
4370 #else
4371 #define CLARA_NOEXCEPT throw()
4372 # define CLARA_NOEXCEPT_IS(x)
4373 #endif
4374
4375 // nullptr support
4376 #ifdef CLARA_CONFIG_CPP11_NULLPTR
4377 #define CLARA_NULL nullptr
4378 #else
4379 #define CLARA_NULL NULL
4380 #endif
4381
4382 // override support
4383 #ifdef CLARA_CONFIG_CPP11_OVERRIDE
4384 #define CLARA_OVERRIDE override
4385 #else
4386 #define CLARA_OVERRIDE
4387 #endif
4388
4389 // unique_ptr support
4390 #ifdef CLARA_CONFIG_CPP11_UNIQUE_PTR
4391 # define CLARA_AUTO_PTR( T ) std::unique_ptr<T>
4392 #else
4393 # define CLARA_AUTO_PTR( T ) std::auto_ptr<T>
4394 #endif
4395
4396 #endif // TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED
4397
4398 // ----------- end of #include from clara_compilers.h -----------
4399 // ........... back in clara.h
4400
4401 #include <map>
4402 #include <stdexcept>
4403 #include <memory>
4404
4405 #if defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
4406 #define CLARA_PLATFORM_WINDOWS
4407 #endif
4408
4409 // Use optional outer namespace
4410 #ifdef STITCH_CLARA_OPEN_NAMESPACE
4411 STITCH_CLARA_OPEN_NAMESPACE
4412 #endif
4413
4414 namespace Clara {
4415
4416 struct UnpositionalTag {};
4417
4418 extern UnpositionalTag _;
4419
4420 #ifdef CLARA_CONFIG_MAIN
4421 UnpositionalTag _;
4422 #endif
4423
4424 namespace Detail {
4425
4426 #ifdef CLARA_CONSOLE_WIDTH
4427 const unsigned int consoleWidth = CLARA_CONFIG_CONSOLE_WIDTH;
4428 #else
4429 const unsigned int consoleWidth = 80;
4430 #endif
4431
4432 using namespace Tbc;
4433
4434 inline bool startsWith( std::string const& str, std::string const& prefix ) {
4435 return str.size() >= prefix.size() && str.substr( 0, prefix.size() ) == prefix;
4436 }
4437
4438 template<typename T> struct RemoveConstRef{ typedef T type; };
4439 template<typename T> struct RemoveConstRef<T&>{ typedef T type; };
4440 template<typename T> struct RemoveConstRef<T const&>{ typedef T type; };
4441 template<typename T> struct RemoveConstRef<T const>{ typedef T type; };
4442
4443 template<typename T> struct IsBool { static const bool value = false; };
4444 template<> struct IsBool<bool> { static const bool value = true; };
4445
4446 template<typename T>
4447 void convertInto( std::string const& _source, T& _dest ) {
4448 std::stringstream ss;
4449 ss << _source;
4450 ss >> _dest;
4451 if( ss.fail() )
4452 throw std::runtime_error( "Unable to convert " + _source + " to destination type" );
4453 }
4454 inline void convertInto( std::string const& _source, std::string& _dest ) {
4455 _dest = _source;
4456 }
4457 char toLowerCh(char c) {
4458 return static_cast<char>( std::tolower( c ) );
4459 }
4460 inline void convertInto( std::string const& _source, bool& _dest ) {
4461 std::string sourceLC = _source;
4462 std::transform( sourceLC.begin(), sourceLC.end(), sourceLC.begin(), toLowerCh );
4463 if( sourceLC == "y" || sourceLC == "1" || sourceLC == "true" || sourceLC == "yes" || sourceLC == "on" )
4464 _dest = true;
4465 else if( sourceLC == "n" || sourceLC == "0" || sourceLC == "false" || sourceLC == "no" || sourceLC == "off" )
4466 _dest = false;
4467 else
4468 throw std::runtime_error( "Expected a boolean value but did not recognise:\n '" + _source + "'" );
4469 }
4470
4471 template<typename ConfigT>
4472 struct IArgFunction {
4473 virtual ~IArgFunction() {}
4474 #ifdef CLARA_CONFIG_CPP11_GENERATED_METHODS
4475 IArgFunction() = default;
4476 IArgFunction( IArgFunction const& ) = default;
4477 #endif
4478 virtual void set( ConfigT& config, std::string const& value ) const = 0;
4479 virtual bool takesArg() const = 0;
4480 virtual IArgFunction* clone() const = 0;
4481 };
4482
4483 template<typename ConfigT>
4484 class BoundArgFunction {
4485 public:
4486 BoundArgFunction() : functionObj( CLARA_NULL ) {}
4487 BoundArgFunction( IArgFunction<ConfigT>* _functionObj ) : functionObj( _functionObj ) {}
4488 BoundArgFunction( BoundArgFunction const& other ) : functionObj( other.functionObj ? other.functionObj->clone() : CLARA_NULL ) {}
4489 BoundArgFunction& operator = ( BoundArgFunction const& other ) {
4490 IArgFunction<ConfigT>* newFunctionObj = other.functionObj ? other.functionObj->clone() : CLARA_NULL;
4491 delete functionObj;
4492 functionObj = newFunctionObj;
4493 return *this;
4494 }
4495 ~BoundArgFunction() { delete functionObj; }
4496
4497 void set( ConfigT& config, std::string const& value ) const {
4498 functionObj->set( config, value );
4499 }
4500 bool takesArg() const { return functionObj->takesArg(); }
4501
4502 bool isSet() const {
4503 return functionObj != CLARA_NULL;
4504 }
4505 private:
4506 IArgFunction<ConfigT>* functionObj;
4507 };
4508
4509 template<typename C>
4510 struct NullBinder : IArgFunction<C>{
4511 virtual void set( C&, std::string const& ) const {}
4512 virtual bool takesArg() const { return true; }
4513 virtual IArgFunction<C>* clone() const { return new NullBinder( *this ); }
4514 };
4515
4516 template<typename C, typename M>
4517 struct BoundDataMember : IArgFunction<C>{
4518 BoundDataMember( M C::* _member ) : member( _member ) {}
4519 virtual void set( C& p, std::string const& stringValue ) const {
4520 convertInto( stringValue, p.*member );
4521 }
4522 virtual bool takesArg() const { return !IsBool<M>::value; }
4523 virtual IArgFunction<C>* clone() const { return new BoundDataMember( *this ); }
4524 M C::* member;
4525 };
4526 template<typename C, typename M>
4527 struct BoundUnaryMethod : IArgFunction<C>{
4528 BoundUnaryMethod( void (C::*_member)( M ) ) : member( _member ) {}
4529 virtual void set( C& p, std::string const& stringValue ) const {
4530 typename RemoveConstRef<M>::type value;
4531 convertInto( stringValue, value );
4532 (p.*member)( value );
4533 }
4534 virtual bool takesArg() const { return !IsBool<M>::value; }
4535 virtual IArgFunction<C>* clone() const { return new BoundUnaryMethod( *this ); }
4536 void (C::*member)( M );
4537 };
4538 template<typename C>
4539 struct BoundNullaryMethod : IArgFunction<C>{
4540 BoundNullaryMethod( void (C::*_member)() ) : member( _member ) {}
4541 virtual void set( C& p, std::string const& stringValue ) const {
4542 bool value;
4543 convertInto( stringValue, value );
4544 if( value )
4545 (p.*member)();
4546 }
4547 virtual bool takesArg() const { return false; }
4548 virtual IArgFunction<C>* clone() const { return new BoundNullaryMethod( *this ); }
4549 void (C::*member)();
4550 };
4551
4552 template<typename C>
4553 struct BoundUnaryFunction : IArgFunction<C>{
4554 BoundUnaryFunction( void (*_function)( C& ) ) : function( _function ) {}
4555 virtual void set( C& obj, std::string const& stringValue ) const {
4556 bool value;
4557 convertInto( stringValue, value );
4558 if( value )
4559 function( obj );
4560 }
4561 virtual bool takesArg() const { return false; }
4562 virtual IArgFunction<C>* clone() const { return new BoundUnaryFunction( *this ); }
4563 void (*function)( C& );
4564 };
4565
4566 template<typename C, typename T>
4567 struct BoundBinaryFunction : IArgFunction<C>{
4568 BoundBinaryFunction( void (*_function)( C&, T ) ) : function( _function ) {}
4569 virtual void set( C& obj, std::string const& stringValue ) const {
4570 typename RemoveConstRef<T>::type value;
4571 convertInto( stringValue, value );
4572 function( obj, value );
4573 }
4574 virtual bool takesArg() const { return !IsBool<T>::value; }
4575 virtual IArgFunction<C>* clone() const { return new BoundBinaryFunction( *this ); }
4576 void (*function)( C&, T );
4577 };
4578
4579 } // namespace Detail
4580
4581 inline std::vector<std::string> argsToVector( int argc, char const* const* const argv ) {
4582 std::vector<std::string> args( static_cast<std::size_t>( argc ) );
4583 for( std::size_t i = 0; i < static_cast<std::size_t>( argc ); ++i )
4584 args[i] = argv[i];
4585
4586 return args;
4587 }
4588
4589 class Parser {
4590 enum Mode { None, MaybeShortOpt, SlashOpt, ShortOpt, LongOpt, Positional };
4591 Mode mode;
4592 std::size_t from;
4593 bool inQuotes;
4594 public:
4595
4596 struct Token {
4597 enum Type { Positional, ShortOpt, LongOpt };
4598 Token( Type _type, std::string const& _data ) : type( _type ), data( _data ) {}
4599 Type type;
4600 std::string data;
4601 };
4602
4603 Parser() : mode( None ), from( 0 ), inQuotes( false ){}
4604
4605 void parseIntoTokens( std::vector<std::string> const& args, std::vector<Token>& tokens ) {
4606 const std::string doubleDash = "--";
4607 for( std::size_t i = 1; i < args.size() && args[i] != doubleDash; ++i )
4608 parseIntoTokens( args[i], tokens);
4609 }
4610
4611 void parseIntoTokens( std::string const& arg, std::vector<Token>& tokens ) {
4612 for( std::size_t i = 0; i < arg.size(); ++i ) {
4613 char c = arg[i];
4614 if( c == '"' )
4615 inQuotes = !inQuotes;
4616 mode = handleMode( i, c, arg, tokens );
4617 }
4618 mode = handleMode( arg.size(), '\0', arg, tokens );
4619 }
4620 Mode handleMode( std::size_t i, char c, std::string const& arg, std::vector<Token>& tokens ) {
4621 switch( mode ) {
4622 case None: return handleNone( i, c );
4623 case MaybeShortOpt: return handleMaybeShortOpt( i, c );
4624 case ShortOpt:
4625 case LongOpt:
4626 case SlashOpt: return handleOpt( i, c, arg, tokens );
4627 case Positional: return handlePositional( i, c, arg, tokens );
4628 default: throw std::logic_error( "Unknown mode" );
4629 }
4630 }
4631
4632 Mode handleNone( std::size_t i, char c ) {
4633 if( inQuotes ) {
4634 from = i;
4635 return Positional;
4636 }
4637 switch( c ) {
4638 case '-': return MaybeShortOpt;
4639 #ifdef CLARA_PLATFORM_WINDOWS
4640 case '/': from = i+1; return SlashOpt;
4641 #endif
4642 default: from = i; return Positional;
4643 }
4644 }
4645 Mode handleMaybeShortOpt( std::size_t i, char c ) {
4646 switch( c ) {
4647 case '-': from = i+1; return LongOpt;
4648 default: from = i; return ShortOpt;
4649 }
4650 }
4651
4652 Mode handleOpt( std::size_t i, char c, std::string const& arg, std::vector<Token>& tokens ) {
4653 if( std::string( ":=\0", 3 ).find( c ) == std::string::npos )
4654 return mode;
4655
4656 std::string optName = arg.substr( from, i-from );
4657 if( mode == ShortOpt )
4658 for( std::size_t j = 0; j < optName.size(); ++j )
4659 tokens.push_back( Token( Token::ShortOpt, optName.substr( j, 1 ) ) );
4660 else if( mode == SlashOpt && optName.size() == 1 )
4661 tokens.push_back( Token( Token::ShortOpt, optName ) );
4662 else
4663 tokens.push_back( Token( Token::LongOpt, optName ) );
4664 return None;
4665 }
4666 Mode handlePositional( std::size_t i, char c, std::string const& arg, std::vector<Token>& tokens ) {
4667 if( inQuotes || std::string( "\0", 1 ).find( c ) == std::string::npos )
4668 return mode;
4669
4670 std::string data = arg.substr( from, i-from );
4671 tokens.push_back( Token( Token::Positional, data ) );
4672 return None;
4673 }
4674 };
4675
4676 template<typename ConfigT>
4677 struct CommonArgProperties {
4678 CommonArgProperties() {}
4679 CommonArgProperties( Detail::BoundArgFunction<ConfigT> const& _boundField ) : boundField( _boundField ) {}
4680
4681 Detail::BoundArgFunction<ConfigT> boundField;
4682 std::string description;
4683 std::string detail;
4684 std::string placeholder; // Only value if boundField takes an arg
4685
4686 bool takesArg() const {
4687 return !placeholder.empty();
4688 }
4689 void validate() const {
4690 if( !boundField.isSet() )
4691 throw std::logic_error( "option not bound" );
4692 }
4693 };
4694 struct OptionArgProperties {
4695 std::vector<std::string> shortNames;
4696 std::string longName;
4697
4698 bool hasShortName( std::string const& shortName ) const {
4699 return std::find( shortNames.begin(), shortNames.end(), shortName ) != shortNames.end();
4700 }
4701 bool hasLongName( std::string const& _longName ) const {
4702 return _longName == longName;
4703 }
4704 };
4705 struct PositionalArgProperties {
4706 PositionalArgProperties() : position( -1 ) {}
4707 int position; // -1 means non-positional (floating)
4708
4709 bool isFixedPositional() const {
4710 return position != -1;
4711 }
4712 };
4713
4714 template<typename ConfigT>
4715 class CommandLine {
4716
4717 struct Arg : CommonArgProperties<ConfigT>, OptionArgProperties, PositionalArgProperties {
4718 Arg() {}
4719 Arg( Detail::BoundArgFunction<ConfigT> const& _boundField ) : CommonArgProperties<ConfigT>( _boundField ) {}
4720
4721 using CommonArgProperties<ConfigT>::placeholder; // !TBD
4722
4723 std::string dbgName() const {
4724 if( !longName.empty() )
4725 return "--" + longName;
4726 if( !shortNames.empty() )
4727 return "-" + shortNames[0];
4728 return "positional args";
4729 }
4730 std::string commands() const {
4731 std::ostringstream oss;
4732 bool first = true;
4733 std::vector<std::string>::const_iterator it = shortNames.begin(), itEnd = shortNames.end();
4734 for(; it != itEnd; ++it ) {
4735 if( first )
4736 first = false;
4737 else
4738 oss << ", ";
4739 oss << "-" << *it;
4740 }
4741 if( !longName.empty() ) {
4742 if( !first )
4743 oss << ", ";
4744 oss << "--" << longName;
4745 }
4746 if( !placeholder.empty() )
4747 oss << " <" << placeholder << ">";
4748 return oss.str();
4749 }
4750 };
4751
4752 typedef CLARA_AUTO_PTR( Arg ) ArgAutoPtr;
4753
4754 friend void addOptName( Arg& arg, std::string const& optName )
4755 {
4756 if( optName.empty() )
4757 return;
4758 if( Detail::startsWith( optName, "--" ) ) {
4759 if( !arg.longName.empty() )
4760 throw std::logic_error( "Only one long opt may be specified. '"
4761 + arg.longName
4762 + "' already specified, now attempting to add '"
4763 + optName + "'" );
4764 arg.longName = optName.substr( 2 );
4765 }
4766 else if( Detail::startsWith( optName, "-" ) )
4767 arg.shortNames.push_back( optName.substr( 1 ) );
4768 else
4769 throw std::logic_error( "option must begin with - or --. Option was: '" + optName + "'" );
4770 }
4771 friend void setPositionalArg( Arg& arg, int position )
4772 {
4773 arg.position = position;
4774 }
4775
4776 class ArgBuilder {
4777 public:
4778 ArgBuilder( Arg* arg ) : m_arg( arg ) {}
4779
4780 // Bind a non-boolean data member (requires placeholder string)
4781 template<typename C, typename M>
4782 void bind( M C::* field, std::string const& placeholder ) {
4783 m_arg->boundField = new Detail::BoundDataMember<C,M>( field );
4784 m_arg->placeholder = placeholder;
4785 }
4786 // Bind a boolean data member (no placeholder required)
4787 template<typename C>
4788 void bind( bool C::* field ) {
4789 m_arg->boundField = new Detail::BoundDataMember<C,bool>( field );
4790 }
4791
4792 // Bind a method taking a single, non-boolean argument (requires a placeholder string)
4793 template<typename C, typename M>
4794 void bind( void (C::* unaryMethod)( M ), std::string const& placeholder ) {
4795 m_arg->boundField = new Detail::BoundUnaryMethod<C,M>( unaryMethod );
4796 m_arg->placeholder = placeholder;
4797 }
4798
4799 // Bind a method taking a single, boolean argument (no placeholder string required)
4800 template<typename C>
4801 void bind( void (C::* unaryMethod)( bool ) ) {
4802 m_arg->boundField = new Detail::BoundUnaryMethod<C,bool>( unaryMethod );
4803 }
4804
4805 // Bind a method that takes no arguments (will be called if opt is present)
4806 template<typename C>
4807 void bind( void (C::* nullaryMethod)() ) {
4808 m_arg->boundField = new Detail::BoundNullaryMethod<C>( nullaryMethod );
4809 }
4810
4811 // Bind a free function taking a single argument - the object to operate on (no placeholder string required)
4812 template<typename C>
4813 void bind( void (* unaryFunction)( C& ) ) {
4814 m_arg->boundField = new Detail::BoundUnaryFunction<C>( unaryFunction );
4815 }
4816
4817 // Bind a free function taking a single argument - the object to operate on (requires a placeholder string)
4818 template<typename C, typename T>
4819 void bind( void (* binaryFunction)( C&, T ), std::string const& placeholder ) {
4820 m_arg->boundField = new Detail::BoundBinaryFunction<C, T>( binaryFunction );
4821 m_arg->placeholder = placeholder;
4822 }
4823
4824 ArgBuilder& describe( std::string const& description ) {
4825 m_arg->description = description;
4826 return *this;
4827 }
4828 ArgBuilder& detail( std::string const& detail ) {
4829 m_arg->detail = detail;
4830 return *this;
4831 }
4832
4833 protected:
4834 Arg* m_arg;
4835 };
4836
4837 class OptBuilder : public ArgBuilder {
4838 public:
4839 OptBuilder( Arg* arg ) : ArgBuilder( arg ) {}
4840 OptBuilder( OptBuilder& other ) : ArgBuilder( other ) {}
4841
4842 OptBuilder& operator[]( std::string const& optName ) {
4843 addOptName( *ArgBuilder::m_arg, optName );
4844 return *this;
4845 }
4846 };
4847
4848 public:
4849
4850 CommandLine()
4851 : m_boundProcessName( new Detail::NullBinder<ConfigT>() ),
4852 m_highestSpecifiedArgPosition( 0 ),
4853 m_throwOnUnrecognisedTokens( false )
4854 {}
4855 CommandLine( CommandLine const& other )
4856 : m_boundProcessName( other.m_boundProcessName ),
4857 m_options ( other.m_options ),
4858 m_positionalArgs( other.m_positionalArgs ),
4859 m_highestSpecifiedArgPosition( other.m_highestSpecifiedArgPosition ),
4860 m_throwOnUnrecognisedTokens( other.m_throwOnUnrecognisedTokens )
4861 {
4862 if( other.m_floatingArg.get() )
4863 m_floatingArg.reset( new Arg( *other.m_floatingArg ) );
4864 }
4865
4866 CommandLine& setThrowOnUnrecognisedTokens( bool shouldThrow = true ) {
4867 m_throwOnUnrecognisedTokens = shouldThrow;
4868 return *this;
4869 }
4870
4871 OptBuilder operator[]( std::string const& optName ) {
4872 m_options.push_back( Arg() );
4873 addOptName( m_options.back(), optName );
4874 OptBuilder builder( &m_options.back() );
4875 return builder;
4876 }
4877
4878 ArgBuilder operator[]( int position ) {
4879 m_positionalArgs.insert( std::make_pair( position, Arg() ) );
4880 if( position > m_highestSpecifiedArgPosition )
4881 m_highestSpecifiedArgPosition = position;
4882 setPositionalArg( m_positionalArgs[position], position );
4883 ArgBuilder builder( &m_positionalArgs[position] );
4884 return builder;
4885 }
4886
4887 // Invoke this with the _ instance
4888 ArgBuilder operator[]( UnpositionalTag ) {
4889 if( m_floatingArg.get() )
4890 throw std::logic_error( "Only one unpositional argument can be added" );
4891 m_floatingArg.reset( new Arg() );
4892 ArgBuilder builder( m_floatingArg.get() );
4893 return builder;
4894 }
4895
4896 template<typename C, typename M>
4897 void bindProcessName( M C::* field ) {
4898 m_boundProcessName = new Detail::BoundDataMember<C,M>( field );
4899 }
4900 template<typename C, typename M>
4901 void bindProcessName( void (C::*_unaryMethod)( M ) ) {
4902 m_boundProcessName = new Detail::BoundUnaryMethod<C,M>( _unaryMethod );
4903 }
4904
4905 void optUsage( std::ostream& os, std::size_t indent = 0, std::size_t width = Detail::consoleWidth ) const {
4906 typename std::vector<Arg>::const_iterator itBegin = m_options.begin(), itEnd = m_options.end(), it;
4907 std::size_t maxWidth = 0;
4908 for( it = itBegin; it != itEnd; ++it )
4909 maxWidth = (std::max)( maxWidth, it->commands().size() );
4910
4911 for( it = itBegin; it != itEnd; ++it ) {
4912 Detail::Text usage( it->commands(), Detail::TextAttributes()
4913 .setWidth( maxWidth+indent )
4914 .setIndent( indent ) );
4915 Detail::Text desc( it->description, Detail::TextAttributes()
4916 .setWidth( width - maxWidth - 3 ) );
4917
4918 for( std::size_t i = 0; i < (std::max)( usage.size(), desc.size() ); ++i ) {
4919 std::string usageCol = i < usage.size() ? usage[i] : "";
4920 os << usageCol;
4921
4922 if( i < desc.size() && !desc[i].empty() )
4923 os << std::string( indent + 2 + maxWidth - usageCol.size(), ' ' )
4924 << desc[i];
4925 os << "\n";
4926 }
4927 }
4928 }
4929 std::string optUsage() const {
4930 std::ostringstream oss;
4931 optUsage( oss );
4932 return oss.str();
4933 }
4934
4935 void argSynopsis( std::ostream& os ) const {
4936 for( int i = 1; i <= m_highestSpecifiedArgPosition; ++i ) {
4937 if( i > 1 )
4938 os << " ";
4939 typename std::map<int, Arg>::const_iterator it = m_positionalArgs.find( i );
4940 if( it != m_positionalArgs.end() )
4941 os << "<" << it->second.placeholder << ">";
4942 else if( m_floatingArg.get() )
4943 os << "<" << m_floatingArg->placeholder << ">";
4944 else
4945 throw std::logic_error( "non consecutive positional arguments with no floating args" );
4946 }
4947 // !TBD No indication of mandatory args
4948 if( m_floatingArg.get() ) {
4949 if( m_highestSpecifiedArgPosition > 1 )
4950 os << " ";
4951 os << "[<" << m_floatingArg->placeholder << "> ...]";
4952 }
4953 }
4954 std::string argSynopsis() const {
4955 std::ostringstream oss;
4956 argSynopsis( oss );
4957 return oss.str();
4958 }
4959
4960 void usage( std::ostream& os, std::string const& procName ) const {
4961 validate();
4962 os << "usage:\n " << procName << " ";
4963 argSynopsis( os );
4964 if( !m_options.empty() ) {
4965 os << " [options]\n\nwhere options are: \n";
4966 optUsage( os, 2 );
4967 }
4968 os << "\n";
4969 }
4970 std::string usage( std::string const& procName ) const {
4971 std::ostringstream oss;
4972 usage( oss, procName );
4973 return oss.str();
4974 }
4975
4976 ConfigT parse( std::vector<std::string> const& args ) const {
4977 ConfigT config;
4978 parseInto( args, config );
4979 return config;
4980 }
4981
4982 std::vector<Parser::Token> parseInto( std::vector<std::string> const& args, ConfigT& config ) const {
4983 std::string processName = args.empty() ? std::string() : args[0];
4984 std::size_t lastSlash = processName.find_last_of( "/\\" );
4985 if( lastSlash != std::string::npos )
4986 processName = processName.substr( lastSlash+1 );
4987 m_boundProcessName.set( config, processName );
4988 std::vector<Parser::Token> tokens;
4989 Parser parser;
4990 parser.parseIntoTokens( args, tokens );
4991 return populate( tokens, config );
4992 }
4993
4994 std::vector<Parser::Token> populate( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {
4995 validate();
4996 std::vector<Parser::Token> unusedTokens = populateOptions( tokens, config );
4997 unusedTokens = populateFixedArgs( unusedTokens, config );
4998 unusedTokens = populateFloatingArgs( unusedTokens, config );
4999 return unusedTokens;
5000 }
5001
5002 std::vector<Parser::Token> populateOptions( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {
5003 std::vector<Parser::Token> unusedTokens;
5004 std::vector<std::string> errors;
5005 for( std::size_t i = 0; i < tokens.size(); ++i ) {
5006 Parser::Token const& token = tokens[i];
5007 typename std::vector<Arg>::const_iterator it = m_options.begin(), itEnd = m_options.end();
5008 for(; it != itEnd; ++it ) {
5009 Arg const& arg = *it;
5010
5011 try {
5012 if( ( token.type == Parser::Token::ShortOpt && arg.hasShortName( token.data ) ) ||
5013 ( token.type == Parser::Token::LongOpt && arg.hasLongName( token.data ) ) ) {
5014 if( arg.takesArg() ) {
5015 if( i == tokens.size()-1 || tokens[i+1].type != Parser::Token::Positional )
5016 errors.push_back( "Expected argument to option: " + token.data );
5017 else
5018 arg.boundField.set( config, tokens[++i].data );
5019 }
5020 else {
5021 arg.boundField.set( config, "true" );
5022 }
5023 break;
5024 }
5025 }
5026 catch( std::exception& ex ) {
5027 errors.push_back( std::string( ex.what() ) + "\n- while parsing: (" + arg.commands() + ")" );
5028 }
5029 }
5030 if( it == itEnd ) {
5031 if( token.type == Parser::Token::Positional || !m_throwOnUnrecognisedTokens )
5032 unusedTokens.push_back( token );
5033 else if( errors.empty() && m_throwOnUnrecognisedTokens )
5034 errors.push_back( "unrecognised option: " + token.data );
5035 }
5036 }
5037 if( !errors.empty() ) {
5038 std::ostringstream oss;
5039 for( std::vector<std::string>::const_iterator it = errors.begin(), itEnd = errors.end();
5040 it != itEnd;
5041 ++it ) {
5042 if( it != errors.begin() )
5043 oss << "\n";
5044 oss << *it;
5045 }
5046 throw std::runtime_error( oss.str() );
5047 }
5048 return unusedTokens;
5049 }
5050 std::vector<Parser::Token> populateFixedArgs( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {
5051 std::vector<Parser::Token> unusedTokens;
5052 int position = 1;
5053 for( std::size_t i = 0; i < tokens.size(); ++i ) {
5054 Parser::Token const& token = tokens[i];
5055 typename std::map<int, Arg>::const_iterator it = m_positionalArgs.find( position );
5056 if( it != m_positionalArgs.end() )
5057 it->second.boundField.set( config, token.data );
5058 else
5059 unusedTokens.push_back( token );
5060 if( token.type == Parser::Token::Positional )
5061 position++;
5062 }
5063 return unusedTokens;
5064 }
5065 std::vector<Parser::Token> populateFloatingArgs( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {
5066 if( !m_floatingArg.get() )
5067 return tokens;
5068 std::vector<Parser::Token> unusedTokens;
5069 for( std::size_t i = 0; i < tokens.size(); ++i ) {
5070 Parser::Token const& token = tokens[i];
5071 if( token.type == Parser::Token::Positional )
5072 m_floatingArg->boundField.set( config, token.data );
5073 else
5074 unusedTokens.push_back( token );
5075 }
5076 return unusedTokens;
5077 }
5078
5079 void validate() const
5080 {
5081 if( m_options.empty() && m_positionalArgs.empty() && !m_floatingArg.get() )
5082 throw std::logic_error( "No options or arguments specified" );
5083
5084 for( typename std::vector<Arg>::const_iterator it = m_options.begin(),
5085 itEnd = m_options.end();
5086 it != itEnd; ++it )
5087 it->validate();
5088 }
5089
5090 private:
5091 Detail::BoundArgFunction<ConfigT> m_boundProcessName;
5092 std::vector<Arg> m_options;
5093 std::map<int, Arg> m_positionalArgs;
5094 ArgAutoPtr m_floatingArg;
5095 int m_highestSpecifiedArgPosition;
5096 bool m_throwOnUnrecognisedTokens;
5097 };
5098
5099 } // end namespace Clara
5100
5101 STITCH_CLARA_CLOSE_NAMESPACE
5102 #undef STITCH_CLARA_OPEN_NAMESPACE
5103 #undef STITCH_CLARA_CLOSE_NAMESPACE
5104
5105 #endif // TWOBLUECUBES_CLARA_H_INCLUDED
5106 #undef STITCH_CLARA_OPEN_NAMESPACE
5107
5108 // Restore Clara's value for console width, if present
5109 #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
5110 #define CLARA_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
5111 #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
5112 #endif
5113
5114 #include <fstream>
5115 #include <ctime>
5116
5117 namespace Catch {
5118
5119 inline void abortAfterFirst( ConfigData& config ) { config.abortAfter = 1; }
5120 inline void abortAfterX( ConfigData& config, int x ) {
5121 if( x < 1 )
5122 throw std::runtime_error( "Value after -x or --abortAfter must be greater than zero" );
5123 config.abortAfter = x;
5124 }
5125 inline void addTestOrTags( ConfigData& config, std::string const& _testSpec ) { config.testsOrTags.push_back( _testSpec ); }
5126 inline void addSectionToRun( ConfigData& config, std::string const& sectionName ) { config.sectionsToRun.push_back( sectionName ); }
5127 inline void addReporterName( ConfigData& config, std::string const& _reporterName ) { config.reporterNames.push_back( _reporterName ); }
5128
5129 inline void addWarning( ConfigData& config, std::string const& _warning ) {
5130 if( _warning == "NoAssertions" )
5131 config.warnings = static_cast<WarnAbout::What>( config.warnings | WarnAbout::NoAssertions );
5132 else
5133 throw std::runtime_error( "Unrecognised warning: '" + _warning + '\'' );
5134 }
5135 inline void setOrder( ConfigData& config, std::string const& order ) {
5136 if( startsWith( "declared", order ) )
5137 config.runOrder = RunTests::InDeclarationOrder;
5138 else if( startsWith( "lexical", order ) )
5139 config.runOrder = RunTests::InLexicographicalOrder;
5140 else if( startsWith( "random", order ) )
5141 config.runOrder = RunTests::InRandomOrder;
5142 else
5143 throw std::runtime_error( "Unrecognised ordering: '" + order + '\'' );
5144 }
5145 inline void setRngSeed( ConfigData& config, std::string const& seed ) {
5146 if( seed == "time" ) {
5147 config.rngSeed = static_cast<unsigned int>( std::time(0) );
5148 }
5149 else {
5150 std::stringstream ss;
5151 ss << seed;
5152 ss >> config.rngSeed;
5153 if( ss.fail() )
5154 throw std::runtime_error( "Argument to --rng-seed should be the word 'time' or a number" );
5155 }
5156 }
5157 inline void setVerbosity( ConfigData& config, int level ) {
5158 // !TBD: accept strings?
5159 config.verbosity = static_cast<Verbosity::Level>( level );
5160 }
5161 inline void setShowDurations( ConfigData& config, bool _showDurations ) {
5162 config.showDurations = _showDurations
5163 ? ShowDurations::Always
5164 : ShowDurations::Never;
5165 }
5166 inline void setUseColour( ConfigData& config, std::string const& value ) {
5167 std::string mode = toLower( value );
5168
5169 if( mode == "yes" )
5170 config.useColour = UseColour::Yes;
5171 else if( mode == "no" )
5172 config.useColour = UseColour::No;
5173 else if( mode == "auto" )
5174 config.useColour = UseColour::Auto;
5175 else
5176 throw std::runtime_error( "colour mode must be one of: auto, yes or no" );
5177 }
5178 inline void forceColour( ConfigData& config ) {
5179 config.useColour = UseColour::Yes;
5180 }
5181 inline void loadTestNamesFromFile( ConfigData& config, std::string const& _filename ) {
5182 std::ifstream f( _filename.c_str() );
5183 if( !f.is_open() )
5184 throw std::domain_error( "Unable to load input file: " + _filename );
5185
5186 std::string line;
5187 while( std::getline( f, line ) ) {
5188 line = trim(line);
5189 if( !line.empty() && !startsWith( line, '#' ) ) {
5190 if( !startsWith( line, '"' ) )
5191 line = '"' + line + '"';
5192 addTestOrTags( config, line + ',' );
5193 }
5194 }
5195 }
5196
5197 inline Clara::CommandLine<ConfigData> makeCommandLineParser() {
5198
5199 using namespace Clara;
5200 CommandLine<ConfigData> cli;
5201
5202 cli.bindProcessName( &ConfigData::processName );
5203
5204 cli["-?"]["-h"]["--help"]
5205 .describe( "display usage information" )
5206 .bind( &ConfigData::showHelp );
5207
5208 cli["-l"]["--list-tests"]
5209 .describe( "list all/matching test cases" )
5210 .bind( &ConfigData::listTests );
5211
5212 cli["-t"]["--list-tags"]
5213 .describe( "list all/matching tags" )
5214 .bind( &ConfigData::listTags );
5215
5216 cli["-s"]["--success"]
5217 .describe( "include successful tests in output" )
5218 .bind( &ConfigData::showSuccessfulTests );
5219
5220 cli["-b"]["--break"]
5221 .describe( "break into debugger on failure" )
5222 .bind( &ConfigData::shouldDebugBreak );
5223
5224 cli["-e"]["--nothrow"]
5225 .describe( "skip exception tests" )
5226 .bind( &ConfigData::noThrow );
5227
5228 cli["-i"]["--invisibles"]
5229 .describe( "show invisibles (tabs, newlines)" )
5230 .bind( &ConfigData::showInvisibles );
5231
5232 cli["-o"]["--out"]
5233 .describe( "output filename" )
5234 .bind( &ConfigData::outputFilename, "filename" );
5235
5236 cli["-r"]["--reporter"]
5237 // .placeholder( "name[:filename]" )
5238 .describe( "reporter to use (defaults to console)" )
5239 .bind( &addReporterName, "name" );
5240
5241 cli["-n"]["--name"]
5242 .describe( "suite name" )
5243 .bind( &ConfigData::name, "name" );
5244
5245 cli["-a"]["--abort"]
5246 .describe( "abort at first failure" )
5247 .bind( &abortAfterFirst );
5248
5249 cli["-x"]["--abortx"]
5250 .describe( "abort after x failures" )
5251 .bind( &abortAfterX, "no. failures" );
5252
5253 cli["-w"]["--warn"]
5254 .describe( "enable warnings" )
5255 .bind( &addWarning, "warning name" );
5256
5257 // - needs updating if reinstated
5258 // cli.into( &setVerbosity )
5259 // .describe( "level of verbosity (0=no output)" )
5260 // .shortOpt( "v")
5261 // .longOpt( "verbosity" )
5262 // .placeholder( "level" );
5263
5264 cli[_]
5265 .describe( "which test or tests to use" )
5266 .bind( &addTestOrTags, "test name, pattern or tags" );
5267
5268 cli["-d"]["--durations"]
5269 .describe( "show test durations" )
5270 .bind( &setShowDurations, "yes|no" );
5271
5272 cli["-f"]["--input-file"]
5273 .describe( "load test names to run from a file" )
5274 .bind( &loadTestNamesFromFile, "filename" );
5275
5276 cli["-#"]["--filenames-as-tags"]
5277 .describe( "adds a tag for the filename" )
5278 .bind( &ConfigData::filenamesAsTags );
5279
5280 cli["-c"]["--section"]
5281 .describe( "specify section to run" )
5282 .bind( &addSectionToRun, "section name" );
5283
5284 // Less common commands which don't have a short form
5285 cli["--list-test-names-only"]
5286 .describe( "list all/matching test cases names only" )
5287 .bind( &ConfigData::listTestNamesOnly );
5288
5289 cli["--list-extra-info"]
5290 .describe( "list all/matching test cases with more info" )
5291 .bind( &ConfigData::listExtraInfo );
5292
5293 cli["--list-reporters"]
5294 .describe( "list all reporters" )
5295 .bind( &ConfigData::listReporters );
5296
5297 cli["--order"]
5298 .describe( "test case order (defaults to decl)" )
5299 .bind( &setOrder, "decl|lex|rand" );
5300
5301 cli["--rng-seed"]
5302 .describe( "set a specific seed for random numbers" )
5303 .bind( &setRngSeed, "'time'|number" );
5304
5305 cli["--force-colour"]
5306 .describe( "force colourised output (deprecated)" )
5307 .bind( &forceColour );
5308
5309 cli["--use-colour"]
5310 .describe( "should output be colourised" )
5311 .bind( &setUseColour, "yes|no" );
5312
5313 return cli;
5314 }
5315
5316 } // end namespace Catch
5317
5318 // #included from: internal/catch_list.hpp
5319 #define TWOBLUECUBES_CATCH_LIST_HPP_INCLUDED
5320
5321 // #included from: catch_text.h
5322 #define TWOBLUECUBES_CATCH_TEXT_H_INCLUDED
5323
5324 #define TBC_TEXT_FORMAT_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH
5325
5326 #define CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE Catch
5327 // #included from: ../external/tbc_text_format.h
5328 // Only use header guard if we are not using an outer namespace
5329 #ifndef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
5330 # ifdef TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED
5331 # ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
5332 # define TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
5333 # endif
5334 # else
5335 # define TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED
5336 # endif
5337 #endif
5338 #ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
5339 #include <string>
5340 #include <vector>
5341 #include <sstream>
5342
5343 // Use optional outer namespace
5344 #ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
5345 namespace CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE {
5346 #endif
5347
5348 namespace Tbc {
5349
5350 #ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH
5351 const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH;
5352 #else
5353 const unsigned int consoleWidth = 80;
5354 #endif
5355
5356 struct TextAttributes {
5357 TextAttributes()
5358 : initialIndent( std::string::npos ),
5359 indent( 0 ),
5360 width( consoleWidth-1 )
5361 {}
5362
5363 TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; }
5364 TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; }
5365 TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; }
5366
5367 std::size_t initialIndent; // indent of first line, or npos
5368 std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos
5369 std::size_t width; // maximum width of text, including indent. Longer text will wrap
5370 };
5371
5372 class Text {
5373 public:
5374 Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() )
5375 : attr( _attr )
5376 {
5377 const std::string wrappableBeforeChars = "[({<\t";
5378 const std::string wrappableAfterChars = "])}>-,./|\\";
5379 const std::string wrappableInsteadOfChars = " \n\r";
5380 std::string indent = _attr.initialIndent != std::string::npos
5381 ? std::string( _attr.initialIndent, ' ' )
5382 : std::string( _attr.indent, ' ' );
5383
5384 typedef std::string::const_iterator iterator;
5385 iterator it = _str.begin();
5386 const iterator strEnd = _str.end();
5387
5388 while( it != strEnd ) {
5389
5390 if( lines.size() >= 1000 ) {
5391 lines.push_back( "... message truncated due to excessive size" );
5392 return;
5393 }
5394
5395 std::string suffix;
5396 std::size_t width = (std::min)( static_cast<size_t>( strEnd-it ), _attr.width-static_cast<size_t>( indent.size() ) );
5397 iterator itEnd = it+width;
5398 iterator itNext = _str.end();
5399
5400 iterator itNewLine = std::find( it, itEnd, '\n' );
5401 if( itNewLine != itEnd )
5402 itEnd = itNewLine;
5403
5404 if( itEnd != strEnd ) {
5405 bool foundWrapPoint = false;
5406 iterator findIt = itEnd;
5407 do {
5408 if( wrappableAfterChars.find( *findIt ) != std::string::npos && findIt != itEnd ) {
5409 itEnd = findIt+1;
5410 itNext = findIt+1;
5411 foundWrapPoint = true;
5412 }
5413 else if( findIt > it && wrappableBeforeChars.find( *findIt ) != std::string::npos ) {
5414 itEnd = findIt;
5415 itNext = findIt;
5416 foundWrapPoint = true;
5417 }
5418 else if( wrappableInsteadOfChars.find( *findIt ) != std::string::npos ) {
5419 itNext = findIt+1;
5420 itEnd = findIt;
5421 foundWrapPoint = true;
5422 }
5423 if( findIt == it )
5424 break;
5425 else
5426 --findIt;
5427 }
5428 while( !foundWrapPoint );
5429
5430 if( !foundWrapPoint ) {
5431 // No good wrap char, so we'll break mid word and add a hyphen
5432 --itEnd;
5433 itNext = itEnd;
5434 suffix = "-";
5435 }
5436 else {
5437 while( itEnd > it && wrappableInsteadOfChars.find( *(itEnd-1) ) != std::string::npos )
5438 --itEnd;
5439 }
5440 }
5441 lines.push_back( indent + std::string( it, itEnd ) + suffix );
5442
5443 if( indent.size() != _attr.indent )
5444 indent = std::string( _attr.indent, ' ' );
5445 it = itNext;
5446 }
5447 }
5448
5449 typedef std::vector<std::string>::const_iterator const_iterator;
5450
5451 const_iterator begin() const { return lines.begin(); }
5452 const_iterator end() const { return lines.end(); }
5453 std::string const& last() const { return lines.back(); }
5454 std::size_t size() const { return lines.size(); }
5455 std::string const& operator[]( std::size_t _index ) const { return lines[_index]; }
5456 std::string toString() const {
5457 std::ostringstream oss;
5458 oss << *this;
5459 return oss.str();
5460 }
5461
5462 inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) {
5463 for( Text::const_iterator it = _text.begin(), itEnd = _text.end();
5464 it != itEnd; ++it ) {
5465 if( it != _text.begin() )
5466 _stream << "\n";
5467 _stream << *it;
5468 }
5469 return _stream;
5470 }
5471
5472 private:
5473 std::string str;
5474 TextAttributes attr;
5475 std::vector<std::string> lines;
5476 };
5477
5478 } // end namespace Tbc
5479
5480 #ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
5481 } // end outer namespace
5482 #endif
5483
5484 #endif // TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
5485 #undef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
5486
5487 namespace Catch {
5488 using Tbc::Text;
5489 using Tbc::TextAttributes;
5490 }
5491
5492 // #included from: catch_console_colour.hpp
5493 #define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_HPP_INCLUDED
5494
5495 namespace Catch {
5496
5497 struct Colour {
5498 enum Code {
5499 None = 0,
5500
5501 White,
5502 Red,
5503 Green,
5504 Blue,
5505 Cyan,
5506 Yellow,
5507 Grey,
5508
5509 Bright = 0x10,
5510
5511 BrightRed = Bright | Red,
5512 BrightGreen = Bright | Green,
5513 LightGrey = Bright | Grey,
5514 BrightWhite = Bright | White,
5515
5516 // By intention
5517 FileName = LightGrey,
5518 Warning = Yellow,
5519 ResultError = BrightRed,
5520 ResultSuccess = BrightGreen,
5521 ResultExpectedFailure = Warning,
5522
5523 Error = BrightRed,
5524 Success = Green,
5525
5526 OriginalExpression = Cyan,
5527 ReconstructedExpression = Yellow,
5528
5529 SecondaryText = LightGrey,
5530 Headers = White
5531 };
5532
5533 // Use constructed object for RAII guard
5534 Colour( Code _colourCode );
5535 Colour( Colour const& other );
5536 ~Colour();
5537
5538 // Use static method for one-shot changes
5539 static void use( Code _colourCode );
5540
5541 private:
5542 bool m_moved;
5543 };
5544
5545 inline std::ostream& operator << ( std::ostream& os, Colour const& ) { return os; }
5546
5547 } // end namespace Catch
5548
5549 // #included from: catch_interfaces_reporter.h
5550 #define TWOBLUECUBES_CATCH_INTERFACES_REPORTER_H_INCLUDED
5551
5552 #include <string>
5553 #include <ostream>
5554 #include <map>
5555
5556 namespace Catch
5557 {
5558 struct ReporterConfig {
5559 explicit ReporterConfig( Ptr<IConfig const> const& _fullConfig )
5560 : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
5561
5562 ReporterConfig( Ptr<IConfig const> const& _fullConfig, std::ostream& _stream )
5563 : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
5564
5565 std::ostream& stream() const { return *m_stream; }
5566 Ptr<IConfig const> fullConfig() const { return m_fullConfig; }
5567
5568 private:
5569 std::ostream* m_stream;
5570 Ptr<IConfig const> m_fullConfig;
5571 };
5572
5573 struct ReporterPreferences {
5574 ReporterPreferences()
5575 : shouldRedirectStdOut( false )
5576 {}
5577
5578 bool shouldRedirectStdOut;
5579 };
5580
5581 template<typename T>
5582 struct LazyStat : Option<T> {
5583 LazyStat() : used( false ) {}
5584 LazyStat& operator=( T const& _value ) {
5585 Option<T>::operator=( _value );
5586 used = false;
5587 return *this;
5588 }
5589 void reset() {
5590 Option<T>::reset();
5591 used = false;
5592 }
5593 bool used;
5594 };
5595
5596 struct TestRunInfo {
5597 TestRunInfo( std::string const& _name ) : name( _name ) {}
5598 std::string name;
5599 };
5600 struct GroupInfo {
5601 GroupInfo( std::string const& _name,
5602 std::size_t _groupIndex,
5603 std::size_t _groupsCount )
5604 : name( _name ),
5605 groupIndex( _groupIndex ),
5606 groupsCounts( _groupsCount )
5607 {}
5608
5609 std::string name;
5610 std::size_t groupIndex;
5611 std::size_t groupsCounts;
5612 };
5613
5614 struct AssertionStats {
5615 AssertionStats( AssertionResult const& _assertionResult,
5616 std::vector<MessageInfo> const& _infoMessages,
5617 Totals const& _totals )
5618 : assertionResult( _assertionResult ),
5619 infoMessages( _infoMessages ),
5620 totals( _totals )
5621 {
5622 if( assertionResult.hasMessage() ) {
5623 // Copy message into messages list.
5624 // !TBD This should have been done earlier, somewhere
5625 MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
5626 builder << assertionResult.getMessage();
5627 builder.m_info.message = builder.m_stream.str();
5628
5629 infoMessages.push_back( builder.m_info );
5630 }
5631 }
5632 virtual ~AssertionStats();
5633
5634 # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
5635 AssertionStats( AssertionStats const& ) = default;
5636 AssertionStats( AssertionStats && ) = default;
5637 AssertionStats& operator = ( AssertionStats const& ) = default;
5638 AssertionStats& operator = ( AssertionStats && ) = default;
5639 # endif
5640
5641 AssertionResult assertionResult;
5642 std::vector<MessageInfo> infoMessages;
5643 Totals totals;
5644 };
5645
5646 struct SectionStats {
5647 SectionStats( SectionInfo const& _sectionInfo,
5648 Counts const& _assertions,
5649 double _durationInSeconds,
5650 bool _missingAssertions )
5651 : sectionInfo( _sectionInfo ),
5652 assertions( _assertions ),
5653 durationInSeconds( _durationInSeconds ),
5654 missingAssertions( _missingAssertions )
5655 {}
5656 virtual ~SectionStats();
5657 # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
5658 SectionStats( SectionStats const& ) = default;
5659 SectionStats( SectionStats && ) = default;
5660 SectionStats& operator = ( SectionStats const& ) = default;
5661 SectionStats& operator = ( SectionStats && ) = default;
5662 # endif
5663
5664 SectionInfo sectionInfo;
5665 Counts assertions;
5666 double durationInSeconds;
5667 bool missingAssertions;
5668 };
5669
5670 struct TestCaseStats {
5671 TestCaseStats( TestCaseInfo const& _testInfo,
5672 Totals const& _totals,
5673 std::string const& _stdOut,
5674 std::string const& _stdErr,
5675 bool _aborting )
5676 : testInfo( _testInfo ),
5677 totals( _totals ),
5678 stdOut( _stdOut ),
5679 stdErr( _stdErr ),
5680 aborting( _aborting )
5681 {}
5682 virtual ~TestCaseStats();
5683
5684 # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
5685 TestCaseStats( TestCaseStats const& ) = default;
5686 TestCaseStats( TestCaseStats && ) = default;
5687 TestCaseStats& operator = ( TestCaseStats const& ) = default;
5688 TestCaseStats& operator = ( TestCaseStats && ) = default;
5689 # endif
5690
5691 TestCaseInfo testInfo;
5692 Totals totals;
5693 std::string stdOut;
5694 std::string stdErr;
5695 bool aborting;
5696 };
5697
5698 struct TestGroupStats {
5699 TestGroupStats( GroupInfo const& _groupInfo,
5700 Totals const& _totals,
5701 bool _aborting )
5702 : groupInfo( _groupInfo ),
5703 totals( _totals ),
5704 aborting( _aborting )
5705 {}
5706 TestGroupStats( GroupInfo const& _groupInfo )
5707 : groupInfo( _groupInfo ),
5708 aborting( false )
5709 {}
5710 virtual ~TestGroupStats();
5711
5712 # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
5713 TestGroupStats( TestGroupStats const& ) = default;
5714 TestGroupStats( TestGroupStats && ) = default;
5715 TestGroupStats& operator = ( TestGroupStats const& ) = default;
5716 TestGroupStats& operator = ( TestGroupStats && ) = default;
5717 # endif
5718
5719 GroupInfo groupInfo;
5720 Totals totals;
5721 bool aborting;
5722 };
5723
5724 struct TestRunStats {
5725 TestRunStats( TestRunInfo const& _runInfo,
5726 Totals const& _totals,
5727 bool _aborting )
5728 : runInfo( _runInfo ),
5729 totals( _totals ),
5730 aborting( _aborting )
5731 {}
5732 virtual ~TestRunStats();
5733
5734 # ifndef CATCH_CONFIG_CPP11_GENERATED_METHODS
5735 TestRunStats( TestRunStats const& _other )
5736 : runInfo( _other.runInfo ),
5737 totals( _other.totals ),
5738 aborting( _other.aborting )
5739 {}
5740 # else
5741 TestRunStats( TestRunStats const& ) = default;
5742 TestRunStats( TestRunStats && ) = default;
5743 TestRunStats& operator = ( TestRunStats const& ) = default;
5744 TestRunStats& operator = ( TestRunStats && ) = default;
5745 # endif
5746
5747 TestRunInfo runInfo;
5748 Totals totals;
5749 bool aborting;
5750 };
5751
5752 class MultipleReporters;
5753
5754 struct IStreamingReporter : IShared {
5755 virtual ~IStreamingReporter();
5756
5757 // Implementing class must also provide the following static method:
5758 // static std::string getDescription();
5759
5760 virtual ReporterPreferences getPreferences() const = 0;
5761
5762 virtual void noMatchingTestCases( std::string const& spec ) = 0;
5763
5764 virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
5765 virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
5766
5767 virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
5768 virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
5769
5770 virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
5771
5772 // The return value indicates if the messages buffer should be cleared:
5773 virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
5774
5775 virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
5776 virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
5777 virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
5778 virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
5779
5780 virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
5781
5782 virtual MultipleReporters* tryAsMulti() { return CATCH_NULL; }
5783 };
5784
5785 struct IReporterFactory : IShared {
5786 virtual ~IReporterFactory();
5787 virtual IStreamingReporter* create( ReporterConfig const& config ) const = 0;
5788 virtual std::string getDescription() const = 0;
5789 };
5790
5791 struct IReporterRegistry {
5792 typedef std::map<std::string, Ptr<IReporterFactory> > FactoryMap;
5793 typedef std::vector<Ptr<IReporterFactory> > Listeners;
5794
5795 virtual ~IReporterRegistry();
5796 virtual IStreamingReporter* create( std::string const& name, Ptr<IConfig const> const& config ) const = 0;
5797 virtual FactoryMap const& getFactories() const = 0;
5798 virtual Listeners const& getListeners() const = 0;
5799 };
5800
5801 Ptr<IStreamingReporter> addReporter( Ptr<IStreamingReporter> const& existingReporter, Ptr<IStreamingReporter> const& additionalReporter );
5802
5803 }
5804
5805 #include <limits>
5806 #include <algorithm>
5807
5808 namespace Catch {
5809
5810 inline std::size_t listTests( Config const& config ) {
5811
5812 TestSpec testSpec = config.testSpec();
5813 if( config.testSpec().hasFilters() )
5814 Catch::cout() << "Matching test cases:\n";
5815 else {
5816 Catch::cout() << "All available test cases:\n";
5817 testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
5818 }
5819
5820 std::size_t matchedTests = 0;
5821 TextAttributes nameAttr, descAttr, tagsAttr;
5822 nameAttr.setInitialIndent( 2 ).setIndent( 4 );
5823 descAttr.setIndent( 4 );
5824 tagsAttr.setIndent( 6 );
5825
5826 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
5827 for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();
5828 it != itEnd;
5829 ++it ) {
5830 matchedTests++;
5831 TestCaseInfo const& testCaseInfo = it->getTestCaseInfo();
5832 Colour::Code colour = testCaseInfo.isHidden()
5833 ? Colour::SecondaryText
5834 : Colour::None;
5835 Colour colourGuard( colour );
5836
5837 Catch::cout() << Text( testCaseInfo.name, nameAttr ) << std::endl;
5838 if( config.listExtraInfo() ) {
5839 Catch::cout() << " " << testCaseInfo.lineInfo << std::endl;
5840 std::string description = testCaseInfo.description;
5841 if( description.empty() )
5842 description = "(NO DESCRIPTION)";
5843 Catch::cout() << Text( description, descAttr ) << std::endl;
5844 }
5845 if( !testCaseInfo.tags.empty() )
5846 Catch::cout() << Text( testCaseInfo.tagsAsString, tagsAttr ) << std::endl;
5847 }
5848
5849 if( !config.testSpec().hasFilters() )
5850 Catch::cout() << pluralise( matchedTests, "test case" ) << '\n' << std::endl;
5851 else
5852 Catch::cout() << pluralise( matchedTests, "matching test case" ) << '\n' << std::endl;
5853 return matchedTests;
5854 }
5855
5856 inline std::size_t listTestsNamesOnly( Config const& config ) {
5857 TestSpec testSpec = config.testSpec();
5858 if( !config.testSpec().hasFilters() )
5859 testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
5860 std::size_t matchedTests = 0;
5861 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
5862 for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();
5863 it != itEnd;
5864 ++it ) {
5865 matchedTests++;
5866 TestCaseInfo const& testCaseInfo = it->getTestCaseInfo();
5867 if( startsWith( testCaseInfo.name, '#' ) )
5868 Catch::cout() << '"' << testCaseInfo.name << '"';
5869 else
5870 Catch::cout() << testCaseInfo.name;
5871 if ( config.listExtraInfo() )
5872 Catch::cout() << "\t@" << testCaseInfo.lineInfo;
5873 Catch::cout() << std::endl;
5874 }
5875 return matchedTests;
5876 }
5877
5878 struct TagInfo {
5879 TagInfo() : count ( 0 ) {}
5880 void add( std::string const& spelling ) {
5881 ++count;
5882 spellings.insert( spelling );
5883 }
5884 std::string all() const {
5885 std::string out;
5886 for( std::set<std::string>::const_iterator it = spellings.begin(), itEnd = spellings.end();
5887 it != itEnd;
5888 ++it )
5889 out += "[" + *it + "]";
5890 return out;
5891 }
5892 std::set<std::string> spellings;
5893 std::size_t count;
5894 };
5895
5896 inline std::size_t listTags( Config const& config ) {
5897 TestSpec testSpec = config.testSpec();
5898 if( config.testSpec().hasFilters() )
5899 Catch::cout() << "Tags for matching test cases:\n";
5900 else {
5901 Catch::cout() << "All available tags:\n";
5902 testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
5903 }
5904
5905 std::map<std::string, TagInfo> tagCounts;
5906
5907 std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
5908 for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();
5909 it != itEnd;
5910 ++it ) {
5911 for( std::set<std::string>::const_iterator tagIt = it->getTestCaseInfo().tags.begin(),
5912 tagItEnd = it->getTestCaseInfo().tags.end();
5913 tagIt != tagItEnd;
5914 ++tagIt ) {
5915 std::string tagName = *tagIt;
5916 std::string lcaseTagName = toLower( tagName );
5917 std::map<std::string, TagInfo>::iterator countIt = tagCounts.find( lcaseTagName );
5918 if( countIt == tagCounts.end() )
5919 countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
5920 countIt->second.add( tagName );
5921 }
5922 }
5923
5924 for( std::map<std::string, TagInfo>::const_iterator countIt = tagCounts.begin(),
5925 countItEnd = tagCounts.end();
5926 countIt != countItEnd;
5927 ++countIt ) {
5928 std::ostringstream oss;
5929 oss << " " << std::setw(2) << countIt->second.count << " ";
5930 Text wrapper( countIt->second.all(), TextAttributes()
5931 .setInitialIndent( 0 )
5932 .setIndent( oss.str().size() )
5933 .setWidth( CATCH_CONFIG_CONSOLE_WIDTH-10 ) );
5934 Catch::cout() << oss.str() << wrapper << '\n';
5935 }
5936 Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
5937 return tagCounts.size();
5938 }
5939
5940 inline std::size_t listReporters( Config const& /*config*/ ) {
5941 Catch::cout() << "Available reporters:\n";
5942 IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
5943 IReporterRegistry::FactoryMap::const_iterator itBegin = factories.begin(), itEnd = factories.end(), it;
5944 std::size_t maxNameLen = 0;
5945 for(it = itBegin; it != itEnd; ++it )
5946 maxNameLen = (std::max)( maxNameLen, it->first.size() );
5947
5948 for(it = itBegin; it != itEnd; ++it ) {
5949 Text wrapper( it->second->getDescription(), TextAttributes()
5950 .setInitialIndent( 0 )
5951 .setIndent( 7+maxNameLen )
5952 .setWidth( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) );
5953 Catch::cout() << " "
5954 << it->first
5955 << ':'
5956 << std::string( maxNameLen - it->first.size() + 2, ' ' )
5957 << wrapper << '\n';
5958 }
5959 Catch::cout() << std::endl;
5960 return factories.size();
5961 }
5962
5963 inline Option<std::size_t> list( Config const& config ) {
5964 Option<std::size_t> listedCount;
5965 if( config.listTests() || ( config.listExtraInfo() && !config.listTestNamesOnly() ) )
5966 listedCount = listedCount.valueOr(0) + listTests( config );
5967 if( config.listTestNamesOnly() )
5968 listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
5969 if( config.listTags() )
5970 listedCount = listedCount.valueOr(0) + listTags( config );
5971 if( config.listReporters() )
5972 listedCount = listedCount.valueOr(0) + listReporters( config );
5973 return listedCount;
5974 }
5975
5976 } // end namespace Catch
5977
5978 // #included from: internal/catch_run_context.hpp
5979 #define TWOBLUECUBES_CATCH_RUNNER_IMPL_HPP_INCLUDED
5980
5981 // #included from: catch_test_case_tracker.hpp
5982 #define TWOBLUECUBES_CATCH_TEST_CASE_TRACKER_HPP_INCLUDED
5983
5984 #include <algorithm>
5985 #include <string>
5986 #include <assert.h>
5987 #include <vector>
5988 #include <stdexcept>
5989
5990 CATCH_INTERNAL_SUPPRESS_ETD_WARNINGS
5991
5992 namespace Catch {
5993 namespace TestCaseTracking {
5994
5995 struct NameAndLocation {
5996 std::string name;
5997 SourceLineInfo location;
5998
5999 NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
6000 : name( _name ),
6001 location( _location )
6002 {}
6003 };
6004
6005 struct ITracker : SharedImpl<> {
6006 virtual ~ITracker();
6007
6008 // static queries
6009 virtual NameAndLocation const& nameAndLocation() const = 0;
6010
6011 // dynamic queries
6012 virtual bool isComplete() const = 0; // Successfully completed or failed
6013 virtual bool isSuccessfullyCompleted() const = 0;
6014 virtual bool isOpen() const = 0; // Started but not complete
6015 virtual bool hasChildren() const = 0;
6016
6017 virtual ITracker& parent() = 0;
6018
6019 // actions
6020 virtual void close() = 0; // Successfully complete
6021 virtual void fail() = 0;
6022 virtual void markAsNeedingAnotherRun() = 0;
6023
6024 virtual void addChild( Ptr<ITracker> const& child ) = 0;
6025 virtual ITracker* findChild( NameAndLocation const& nameAndLocation ) = 0;
6026 virtual void openChild() = 0;
6027
6028 // Debug/ checking
6029 virtual bool isSectionTracker() const = 0;
6030 virtual bool isIndexTracker() const = 0;
6031 };
6032
6033 class TrackerContext {
6034
6035 enum RunState {
6036 NotStarted,
6037 Executing,
6038 CompletedCycle
6039 };
6040
6041 Ptr<ITracker> m_rootTracker;
6042 ITracker* m_currentTracker;
6043 RunState m_runState;
6044
6045 public:
6046
6047 static TrackerContext& instance() {
6048 static TrackerContext s_instance;
6049 return s_instance;
6050 }
6051
6052 TrackerContext()
6053 : m_currentTracker( CATCH_NULL ),
6054 m_runState( NotStarted )
6055 {}
6056
6057 ITracker& startRun();
6058
6059 void endRun() {
6060 m_rootTracker.reset();
6061 m_currentTracker = CATCH_NULL;
6062 m_runState = NotStarted;
6063 }
6064
6065 void startCycle() {
6066 m_currentTracker = m_rootTracker.get();
6067 m_runState = Executing;
6068 }
6069 void completeCycle() {
6070 m_runState = CompletedCycle;
6071 }
6072
6073 bool completedCycle() const {
6074 return m_runState == CompletedCycle;
6075 }
6076 ITracker& currentTracker() {
6077 return *m_currentTracker;
6078 }
6079 void setCurrentTracker( ITracker* tracker ) {
6080 m_currentTracker = tracker;
6081 }
6082 };
6083
6084 class TrackerBase : public ITracker {
6085 protected:
6086 enum CycleState {
6087 NotStarted,
6088 Executing,
6089 ExecutingChildren,
6090 NeedsAnotherRun,
6091 CompletedSuccessfully,
6092 Failed
6093 };
6094 class TrackerHasName {
6095 NameAndLocation m_nameAndLocation;
6096 public:
6097 TrackerHasName( NameAndLocation const& nameAndLocation ) : m_nameAndLocation( nameAndLocation ) {}
6098 bool operator ()( Ptr<ITracker> const& tracker ) {
6099 return
6100 tracker->nameAndLocation().name == m_nameAndLocation.name &&
6101 tracker->nameAndLocation().location == m_nameAndLocation.location;
6102 }
6103 };
6104 typedef std::vector<Ptr<ITracker> > Children;
6105 NameAndLocation m_nameAndLocation;
6106 TrackerContext& m_ctx;
6107 ITracker* m_parent;
6108 Children m_children;
6109 CycleState m_runState;
6110 public:
6111 TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
6112 : m_nameAndLocation( nameAndLocation ),
6113 m_ctx( ctx ),
6114 m_parent( parent ),
6115 m_runState( NotStarted )
6116 {}
6117 virtual ~TrackerBase();
6118
6119 virtual NameAndLocation const& nameAndLocation() const CATCH_OVERRIDE {
6120 return m_nameAndLocation;
6121 }
6122 virtual bool isComplete() const CATCH_OVERRIDE {
6123 return m_runState == CompletedSuccessfully || m_runState == Failed;
6124 }
6125 virtual bool isSuccessfullyCompleted() const CATCH_OVERRIDE {
6126 return m_runState == CompletedSuccessfully;
6127 }
6128 virtual bool isOpen() const CATCH_OVERRIDE {
6129 return m_runState != NotStarted && !isComplete();
6130 }
6131 virtual bool hasChildren() const CATCH_OVERRIDE {
6132 return !m_children.empty();
6133 }
6134
6135 virtual void addChild( Ptr<ITracker> const& child ) CATCH_OVERRIDE {
6136 m_children.push_back( child );
6137 }
6138
6139 virtual ITracker* findChild( NameAndLocation const& nameAndLocation ) CATCH_OVERRIDE {
6140 Children::const_iterator it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( nameAndLocation ) );
6141 return( it != m_children.end() )
6142 ? it->get()
6143 : CATCH_NULL;
6144 }
6145 virtual ITracker& parent() CATCH_OVERRIDE {
6146 assert( m_parent ); // Should always be non-null except for root
6147 return *m_parent;
6148 }
6149
6150 virtual void openChild() CATCH_OVERRIDE {
6151 if( m_runState != ExecutingChildren ) {
6152 m_runState = ExecutingChildren;
6153 if( m_parent )
6154 m_parent->openChild();
6155 }
6156 }
6157
6158 virtual bool isSectionTracker() const CATCH_OVERRIDE { return false; }
6159 virtual bool isIndexTracker() const CATCH_OVERRIDE { return false; }
6160
6161 void open() {
6162 m_runState = Executing;
6163 moveToThis();
6164 if( m_parent )
6165 m_parent->openChild();
6166 }
6167
6168 virtual void close() CATCH_OVERRIDE {
6169
6170 // Close any still open children (e.g. generators)
6171 while( &m_ctx.currentTracker() != this )
6172 m_ctx.currentTracker().close();
6173
6174 switch( m_runState ) {
6175 case NotStarted:
6176 case CompletedSuccessfully:
6177 case Failed:
6178 throw std::logic_error( "Illogical state" );
6179
6180 case NeedsAnotherRun:
6181 break;;
6182
6183 case Executing:
6184 m_runState = CompletedSuccessfully;
6185 break;
6186 case ExecutingChildren:
6187 if( m_children.empty() || m_children.back()->isComplete() )
6188 m_runState = CompletedSuccessfully;
6189 break;
6190
6191 default:
6192 throw std::logic_error( "Unexpected state" );
6193 }
6194 moveToParent();
6195 m_ctx.completeCycle();
6196 }
6197 virtual void fail() CATCH_OVERRIDE {
6198 m_runState = Failed;
6199 if( m_parent )
6200 m_parent->markAsNeedingAnotherRun();
6201 moveToParent();
6202 m_ctx.completeCycle();
6203 }
6204 virtual void markAsNeedingAnotherRun() CATCH_OVERRIDE {
6205 m_runState = NeedsAnotherRun;
6206 }
6207 private:
6208 void moveToParent() {
6209 assert( m_parent );
6210 m_ctx.setCurrentTracker( m_parent );
6211 }
6212 void moveToThis() {
6213 m_ctx.setCurrentTracker( this );
6214 }
6215 };
6216
6217 class SectionTracker : public TrackerBase {
6218 std::vector<std::string> m_filters;
6219 public:
6220 SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
6221 : TrackerBase( nameAndLocation, ctx, parent )
6222 {
6223 if( parent ) {
6224 while( !parent->isSectionTracker() )
6225 parent = &parent->parent();
6226
6227 SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
6228 addNextFilters( parentSection.m_filters );
6229 }
6230 }
6231 virtual ~SectionTracker();
6232
6233 virtual bool isSectionTracker() const CATCH_OVERRIDE { return true; }
6234
6235 static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
6236 SectionTracker* section = CATCH_NULL;
6237
6238 ITracker& currentTracker = ctx.currentTracker();
6239 if( ITracker* childTracker = currentTracker.findChild( nameAndLocation ) ) {
6240 assert( childTracker );
6241 assert( childTracker->isSectionTracker() );
6242 section = static_cast<SectionTracker*>( childTracker );
6243 }
6244 else {
6245 section = new SectionTracker( nameAndLocation, ctx, &currentTracker );
6246 currentTracker.addChild( section );
6247 }
6248 if( !ctx.completedCycle() )
6249 section->tryOpen();
6250 return *section;
6251 }
6252
6253 void tryOpen() {
6254 if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
6255 open();
6256 }
6257
6258 void addInitialFilters( std::vector<std::string> const& filters ) {
6259 if( !filters.empty() ) {
6260 m_filters.push_back(""); // Root - should never be consulted
6261 m_filters.push_back(""); // Test Case - not a section filter
6262 m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
6263 }
6264 }
6265 void addNextFilters( std::vector<std::string> const& filters ) {
6266 if( filters.size() > 1 )
6267 m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
6268 }
6269 };
6270
6271 class IndexTracker : public TrackerBase {
6272 int m_size;
6273 int m_index;
6274 public:
6275 IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size )
6276 : TrackerBase( nameAndLocation, ctx, parent ),
6277 m_size( size ),
6278 m_index( -1 )
6279 {}
6280 virtual ~IndexTracker();
6281
6282 virtual bool isIndexTracker() const CATCH_OVERRIDE { return true; }
6283
6284 static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) {
6285 IndexTracker* tracker = CATCH_NULL;
6286
6287 ITracker& currentTracker = ctx.currentTracker();
6288 if( ITracker* childTracker = currentTracker.findChild( nameAndLocation ) ) {
6289 assert( childTracker );
6290 assert( childTracker->isIndexTracker() );
6291 tracker = static_cast<IndexTracker*>( childTracker );
6292 }
6293 else {
6294 tracker = new IndexTracker( nameAndLocation, ctx, &currentTracker, size );
6295 currentTracker.addChild( tracker );
6296 }
6297
6298 if( !ctx.completedCycle() && !tracker->isComplete() ) {
6299 if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
6300 tracker->moveNext();
6301 tracker->open();
6302 }
6303
6304 return *tracker;
6305 }
6306
6307 int index() const { return m_index; }
6308
6309 void moveNext() {
6310 m_index++;
6311 m_children.clear();
6312 }
6313
6314 virtual void close() CATCH_OVERRIDE {
6315 TrackerBase::close();
6316 if( m_runState == CompletedSuccessfully && m_index < m_size-1 )
6317 m_runState = Executing;
6318 }
6319 };
6320
6321 inline ITracker& TrackerContext::startRun() {
6322 m_rootTracker = new SectionTracker( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, CATCH_NULL );
6323 m_currentTracker = CATCH_NULL;
6324 m_runState = Executing;
6325 return *m_rootTracker;
6326 }
6327
6328 } // namespace TestCaseTracking
6329
6330 using TestCaseTracking::ITracker;
6331 using TestCaseTracking::TrackerContext;
6332 using TestCaseTracking::SectionTracker;
6333 using TestCaseTracking::IndexTracker;
6334
6335 } // namespace Catch
6336
6337 CATCH_INTERNAL_UNSUPPRESS_ETD_WARNINGS
6338
6339 // #included from: catch_fatal_condition.hpp
6340 #define TWOBLUECUBES_CATCH_FATAL_CONDITION_H_INCLUDED
6341
6342 namespace Catch {
6343
6344 // Report the error condition
6345 inline void reportFatal( std::string const& message ) {
6346 IContext& context = Catch::getCurrentContext();
6347 IResultCapture* resultCapture = context.getResultCapture();
6348 resultCapture->handleFatalErrorCondition( message );
6349 }
6350
6351 } // namespace Catch
6352
6353 #if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
6354 // #included from: catch_windows_h_proxy.h
6355
6356 #define TWOBLUECUBES_CATCH_WINDOWS_H_PROXY_H_INCLUDED
6357
6358 #ifdef CATCH_DEFINES_NOMINMAX
6359 # define NOMINMAX
6360 #endif
6361 #ifdef CATCH_DEFINES_WIN32_LEAN_AND_MEAN
6362 # define WIN32_LEAN_AND_MEAN
6363 #endif
6364
6365 #ifdef __AFXDLL
6366 #include <AfxWin.h>
6367 #else
6368 #include <windows.h>
6369 #endif
6370
6371 #ifdef CATCH_DEFINES_NOMINMAX
6372 # undef NOMINMAX
6373 #endif
6374 #ifdef CATCH_DEFINES_WIN32_LEAN_AND_MEAN
6375 # undef WIN32_LEAN_AND_MEAN
6376 #endif
6377
6378
6379 # if !defined ( CATCH_CONFIG_WINDOWS_SEH )
6380
6381 namespace Catch {
6382 struct FatalConditionHandler {
6383 void reset() {}
6384 };
6385 }
6386
6387 # else // CATCH_CONFIG_WINDOWS_SEH is defined
6388
6389 namespace Catch {
6390
6391 struct SignalDefs { DWORD id; const char* name; };
6392 extern SignalDefs signalDefs[];
6393 // There is no 1-1 mapping between signals and windows exceptions.
6394 // Windows can easily distinguish between SO and SigSegV,
6395 // but SigInt, SigTerm, etc are handled differently.
6396 SignalDefs signalDefs[] = {
6397 { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
6398 { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
6399 { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
6400 { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
6401 };
6402
6403 struct FatalConditionHandler {
6404
6405 static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
6406 for (int i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
6407 if (ExceptionInfo->ExceptionRecord->ExceptionCode == signalDefs[i].id) {
6408 reportFatal(signalDefs[i].name);
6409 }
6410 }
6411 // If its not an exception we care about, pass it along.
6412 // This stops us from eating debugger breaks etc.
6413 return EXCEPTION_CONTINUE_SEARCH;
6414 }
6415
6416 FatalConditionHandler() {
6417 isSet = true;
6418 // 32k seems enough for Catch to handle stack overflow,
6419 // but the value was found experimentally, so there is no strong guarantee
6420 guaranteeSize = 32 * 1024;
6421 exceptionHandlerHandle = CATCH_NULL;
6422 // Register as first handler in current chain
6423 exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
6424 // Pass in guarantee size to be filled
6425 SetThreadStackGuarantee(&guaranteeSize);
6426 }
6427
6428 static void reset() {
6429 if (isSet) {
6430 // Unregister handler and restore the old guarantee
6431 RemoveVectoredExceptionHandler(exceptionHandlerHandle);
6432 SetThreadStackGuarantee(&guaranteeSize);
6433 exceptionHandlerHandle = CATCH_NULL;
6434 isSet = false;
6435 }
6436 }
6437
6438 ~FatalConditionHandler() {
6439 reset();
6440 }
6441 private:
6442 static bool isSet;
6443 static ULONG guaranteeSize;
6444 static PVOID exceptionHandlerHandle;
6445 };
6446
6447 bool FatalConditionHandler::isSet = false;
6448 ULONG FatalConditionHandler::guaranteeSize = 0;
6449 PVOID FatalConditionHandler::exceptionHandlerHandle = CATCH_NULL;
6450
6451 } // namespace Catch
6452
6453 # endif // CATCH_CONFIG_WINDOWS_SEH
6454
6455 #else // Not Windows - assumed to be POSIX compatible //////////////////////////
6456
6457 # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
6458
6459 namespace Catch {
6460 struct FatalConditionHandler {
6461 void reset() {}
6462 };
6463 }
6464
6465 # else // CATCH_CONFIG_POSIX_SIGNALS is defined
6466
6467 #include <signal.h>
6468
6469 namespace Catch {
6470
6471 struct SignalDefs {
6472 int id;
6473 const char* name;
6474 };
6475
6476 // 32kb for the alternate stack seems to be sufficient. However, this value
6477 // is experimentally determined, so that's not guaranteed.
6478 #if defined(_SC_SIGSTKSZ_SOURCE) || defined(_GNU_SOURCE)
6479 // on glibc > 2.33 this is no longer constant, see
6480 // https://sourceware.org/git/?p=glibc.git;a=blob;f=NEWS;h=85e84fe53699fe9e392edffa993612ce08b2954a;hb=HEAD
6481 static constexpr std::size_t altStackSize = 32 * 1024;
6482 #else
6483 static constexpr std::size_t altStackSize = std::max(static_cast<size_t>(SIGSTKSZ), 32 * 1024)
6484 #endif
6485
6486 extern SignalDefs signalDefs[];
6487 SignalDefs signalDefs[] = {
6488 { SIGINT, "SIGINT - Terminal interrupt signal" },
6489 { SIGILL, "SIGILL - Illegal instruction signal" },
6490 { SIGFPE, "SIGFPE - Floating point error signal" },
6491 { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
6492 { SIGTERM, "SIGTERM - Termination request signal" },
6493 { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
6494 };
6495
6496 struct FatalConditionHandler {
6497
6498 static bool isSet;
6499 static struct sigaction oldSigActions [sizeof(signalDefs)/sizeof(SignalDefs)];
6500 static stack_t oldSigStack;
6501 static char altStackMem[altStackSize];
6502
6503 static void handleSignal( int sig ) {
6504 std::string name = "<unknown signal>";
6505 for (std::size_t i = 0; i < sizeof(signalDefs) / sizeof(SignalDefs); ++i) {
6506 SignalDefs &def = signalDefs[i];
6507 if (sig == def.id) {
6508 name = def.name;
6509 break;
6510 }
6511 }
6512 reset();
6513 reportFatal(name);
6514 raise( sig );
6515 }
6516
6517 FatalConditionHandler() {
6518 isSet = true;
6519 stack_t sigStack;
6520 sigStack.ss_sp = altStackMem;
6521 sigStack.ss_size = altStackSize;
6522 sigStack.ss_flags = 0;
6523 sigaltstack(&sigStack, &oldSigStack);
6524 struct sigaction sa = { 0 };
6525
6526 sa.sa_handler = handleSignal;
6527 sa.sa_flags = SA_ONSTACK;
6528 for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
6529 sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
6530 }
6531 }
6532
6533 ~FatalConditionHandler() {
6534 reset();
6535 }
6536 static void reset() {
6537 if( isSet ) {
6538 // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
6539 for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
6540 sigaction(signalDefs[i].id, &oldSigActions[i], CATCH_NULL);
6541 }
6542 // Return the old stack
6543 sigaltstack(&oldSigStack, CATCH_NULL);
6544 isSet = false;
6545 }
6546 }
6547 };
6548
6549 bool FatalConditionHandler::isSet = false;
6550 struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
6551 stack_t FatalConditionHandler::oldSigStack = {};
6552 char FatalConditionHandler::altStackMem[altStackSize] = {};
6553
6554 } // namespace Catch
6555
6556 # endif // CATCH_CONFIG_POSIX_SIGNALS
6557
6558 #endif // not Windows
6559
6560 #include <set>
6561 #include <string>
6562
6563 namespace Catch {
6564
6565 class StreamRedirect {
6566
6567 public:
6568 StreamRedirect( std::ostream& stream, std::string& targetString )
6569 : m_stream( stream ),
6570 m_prevBuf( stream.rdbuf() ),
6571 m_targetString( targetString )
6572 {
6573 stream.rdbuf( m_oss.rdbuf() );
6574 }
6575
6576 ~StreamRedirect() {
6577 m_targetString += m_oss.str();
6578 m_stream.rdbuf( m_prevBuf );
6579 }
6580
6581 private:
6582 std::ostream& m_stream;
6583 std::streambuf* m_prevBuf;
6584 std::ostringstream m_oss;
6585 std::string& m_targetString;
6586 };
6587
6588 ///////////////////////////////////////////////////////////////////////////
6589
6590 class RunContext : public IResultCapture, public IRunner {
6591
6592 RunContext( RunContext const& );
6593 void operator =( RunContext const& );
6594
6595 public:
6596
6597 explicit RunContext( Ptr<IConfig const> const& _config, Ptr<IStreamingReporter> const& reporter )
6598 : m_runInfo( _config->name() ),
6599 m_context( getCurrentMutableContext() ),
6600 m_activeTestCase( CATCH_NULL ),
6601 m_config( _config ),
6602 m_reporter( reporter ),
6603 m_shouldReportUnexpected ( true )
6604 {
6605 m_context.setRunner( this );
6606 m_context.setConfig( m_config );
6607 m_context.setResultCapture( this );
6608 m_reporter->testRunStarting( m_runInfo );
6609 }
6610
6611 virtual ~RunContext() {
6612 m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, aborting() ) );
6613 }
6614
6615 void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ) {
6616 m_reporter->testGroupStarting( GroupInfo( testSpec, groupIndex, groupsCount ) );
6617 }
6618 void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ) {
6619 m_reporter->testGroupEnded( TestGroupStats( GroupInfo( testSpec, groupIndex, groupsCount ), totals, aborting() ) );
6620 }
6621
6622 Totals runTest( TestCase const& testCase ) {
6623 Totals prevTotals = m_totals;
6624
6625 std::string redirectedCout;
6626 std::string redirectedCerr;
6627
6628 TestCaseInfo testInfo = testCase.getTestCaseInfo();
6629
6630 m_reporter->testCaseStarting( testInfo );
6631
6632 m_activeTestCase = &testCase;
6633
6634 do {
6635 ITracker& rootTracker = m_trackerContext.startRun();
6636 assert( rootTracker.isSectionTracker() );
6637 static_cast<SectionTracker&>( rootTracker ).addInitialFilters( m_config->getSectionsToRun() );
6638 do {
6639 m_trackerContext.startCycle();
6640 m_testCaseTracker = &SectionTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( testInfo.name, testInfo.lineInfo ) );
6641 runCurrentTest( redirectedCout, redirectedCerr );
6642 }
6643 while( !m_testCaseTracker->isSuccessfullyCompleted() && !aborting() );
6644 }
6645 // !TBD: deprecated - this will be replaced by indexed trackers
6646 while( getCurrentContext().advanceGeneratorsForCurrentTest() && !aborting() );
6647
6648 Totals deltaTotals = m_totals.delta( prevTotals );
6649 if( testInfo.expectedToFail() && deltaTotals.testCases.passed > 0 ) {
6650 deltaTotals.assertions.failed++;
6651 deltaTotals.testCases.passed--;
6652 deltaTotals.testCases.failed++;
6653 }
6654 m_totals.testCases += deltaTotals.testCases;
6655 m_reporter->testCaseEnded( TestCaseStats( testInfo,
6656 deltaTotals,
6657 redirectedCout,
6658 redirectedCerr,
6659 aborting() ) );
6660
6661 m_activeTestCase = CATCH_NULL;
6662 m_testCaseTracker = CATCH_NULL;
6663
6664 return deltaTotals;
6665 }
6666
6667 Ptr<IConfig const> config() const {
6668 return m_config;
6669 }
6670
6671 private: // IResultCapture
6672
6673 virtual void assertionEnded( AssertionResult const& result ) {
6674 if( result.getResultType() == ResultWas::Ok ) {
6675 m_totals.assertions.passed++;
6676 }
6677 else if( !result.isOk() ) {
6678 m_totals.assertions.failed++;
6679 }
6680
6681 // We have no use for the return value (whether messages should be cleared), because messages were made scoped
6682 // and should be let to clear themselves out.
6683 static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
6684
6685 // Reset working state
6686 m_lastAssertionInfo = AssertionInfo( "", m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition );
6687 m_lastResult = result;
6688 }
6689
6690 virtual bool sectionStarted (
6691 SectionInfo const& sectionInfo,
6692 Counts& assertions
6693 )
6694 {
6695 ITracker& sectionTracker = SectionTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( sectionInfo.name, sectionInfo.lineInfo ) );
6696 if( !sectionTracker.isOpen() )
6697 return false;
6698 m_activeSections.push_back( &sectionTracker );
6699
6700 m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
6701
6702 m_reporter->sectionStarting( sectionInfo );
6703
6704 assertions = m_totals.assertions;
6705
6706 return true;
6707 }
6708 bool testForMissingAssertions( Counts& assertions ) {
6709 if( assertions.total() != 0 )
6710 return false;
6711 if( !m_config->warnAboutMissingAssertions() )
6712 return false;
6713 if( m_trackerContext.currentTracker().hasChildren() )
6714 return false;
6715 m_totals.assertions.failed++;
6716 assertions.failed++;
6717 return true;
6718 }
6719
6720 virtual void sectionEnded( SectionEndInfo const& endInfo ) {
6721 Counts assertions = m_totals.assertions - endInfo.prevAssertions;
6722 bool missingAssertions = testForMissingAssertions( assertions );
6723
6724 if( !m_activeSections.empty() ) {
6725 m_activeSections.back()->close();
6726 m_activeSections.pop_back();
6727 }
6728
6729 m_reporter->sectionEnded( SectionStats( endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions ) );
6730 m_messages.clear();
6731 }
6732
6733 virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) {
6734 if( m_unfinishedSections.empty() )
6735 m_activeSections.back()->fail();
6736 else
6737 m_activeSections.back()->close();
6738 m_activeSections.pop_back();
6739
6740 m_unfinishedSections.push_back( endInfo );
6741 }
6742
6743 virtual void pushScopedMessage( MessageInfo const& message ) {
6744 m_messages.push_back( message );
6745 }
6746
6747 virtual void popScopedMessage( MessageInfo const& message ) {
6748 m_messages.erase( std::remove( m_messages.begin(), m_messages.end(), message ), m_messages.end() );
6749 }
6750
6751 virtual std::string getCurrentTestName() const {
6752 return m_activeTestCase
6753 ? m_activeTestCase->getTestCaseInfo().name
6754 : std::string();
6755 }
6756
6757 virtual const AssertionResult* getLastResult() const {
6758 return &m_lastResult;
6759 }
6760
6761 virtual void exceptionEarlyReported() {
6762 m_shouldReportUnexpected = false;
6763 }
6764
6765 virtual void handleFatalErrorCondition( std::string const& message ) {
6766 // Don't rebuild the result -- the stringification itself can cause more fatal errors
6767 // Instead, fake a result data.
6768 AssertionResultData tempResult;
6769 tempResult.resultType = ResultWas::FatalErrorCondition;
6770 tempResult.message = message;
6771 AssertionResult result(m_lastAssertionInfo, tempResult);
6772
6773 getResultCapture().assertionEnded(result);
6774
6775 handleUnfinishedSections();
6776
6777 // Recreate section for test case (as we will lose the one that was in scope)
6778 TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
6779 SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description );
6780
6781 Counts assertions;
6782 assertions.failed = 1;
6783 SectionStats testCaseSectionStats( testCaseSection, assertions, 0, false );
6784 m_reporter->sectionEnded( testCaseSectionStats );
6785
6786 TestCaseInfo testInfo = m_activeTestCase->getTestCaseInfo();
6787
6788 Totals deltaTotals;
6789 deltaTotals.testCases.failed = 1;
6790 m_reporter->testCaseEnded( TestCaseStats( testInfo,
6791 deltaTotals,
6792 std::string(),
6793 std::string(),
6794 false ) );
6795 m_totals.testCases.failed++;
6796 testGroupEnded( std::string(), m_totals, 1, 1 );
6797 m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, false ) );
6798 }
6799
6800 public:
6801 // !TBD We need to do this another way!
6802 bool aborting() const {
6803 return m_totals.assertions.failed == static_cast<std::size_t>( m_config->abortAfter() );
6804 }
6805
6806 private:
6807
6808 void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ) {
6809 TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
6810 SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description );
6811 m_reporter->sectionStarting( testCaseSection );
6812 Counts prevAssertions = m_totals.assertions;
6813 double duration = 0;
6814 m_shouldReportUnexpected = true;
6815 try {
6816 m_lastAssertionInfo = AssertionInfo( "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal );
6817
6818 seedRng( *m_config );
6819
6820 Timer timer;
6821 timer.start();
6822 if( m_reporter->getPreferences().shouldRedirectStdOut ) {
6823 StreamRedirect coutRedir( Catch::cout(), redirectedCout );
6824 StreamRedirect cerrRedir( Catch::cerr(), redirectedCerr );
6825 invokeActiveTestCase();
6826 }
6827 else {
6828 invokeActiveTestCase();
6829 }
6830 duration = timer.getElapsedSeconds();
6831 }
6832 catch( TestFailureException& ) {
6833 // This just means the test was aborted due to failure
6834 }
6835 catch(...) {
6836 // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
6837 // are reported without translation at the point of origin.
6838 if (m_shouldReportUnexpected) {
6839 makeUnexpectedResultBuilder().useActiveException();
6840 }
6841 }
6842 m_testCaseTracker->close();
6843 handleUnfinishedSections();
6844 m_messages.clear();
6845
6846 Counts assertions = m_totals.assertions - prevAssertions;
6847 bool missingAssertions = testForMissingAssertions( assertions );
6848
6849 if( testCaseInfo.okToFail() ) {
6850 std::swap( assertions.failedButOk, assertions.failed );
6851 m_totals.assertions.failed -= assertions.failedButOk;
6852 m_totals.assertions.failedButOk += assertions.failedButOk;
6853 }
6854
6855 SectionStats testCaseSectionStats( testCaseSection, assertions, duration, missingAssertions );
6856 m_reporter->sectionEnded( testCaseSectionStats );
6857 }
6858
6859 void invokeActiveTestCase() {
6860 FatalConditionHandler fatalConditionHandler; // Handle signals
6861 m_activeTestCase->invoke();
6862 fatalConditionHandler.reset();
6863 }
6864
6865 private:
6866
6867 ResultBuilder makeUnexpectedResultBuilder() const {
6868 return ResultBuilder( m_lastAssertionInfo.macroName,
6869 m_lastAssertionInfo.lineInfo,
6870 m_lastAssertionInfo.capturedExpression,
6871 m_lastAssertionInfo.resultDisposition );
6872 }
6873
6874 void handleUnfinishedSections() {
6875 // If sections ended prematurely due to an exception we stored their
6876 // infos here so we can tear them down outside the unwind process.
6877 for( std::vector<SectionEndInfo>::const_reverse_iterator it = m_unfinishedSections.rbegin(),
6878 itEnd = m_unfinishedSections.rend();
6879 it != itEnd;
6880 ++it )
6881 sectionEnded( *it );
6882 m_unfinishedSections.clear();
6883 }
6884
6885 TestRunInfo m_runInfo;
6886 IMutableContext& m_context;
6887 TestCase const* m_activeTestCase;
6888 ITracker* m_testCaseTracker;
6889 ITracker* m_currentSectionTracker;
6890 AssertionResult m_lastResult;
6891
6892 Ptr<IConfig const> m_config;
6893 Totals m_totals;
6894 Ptr<IStreamingReporter> m_reporter;
6895 std::vector<MessageInfo> m_messages;
6896 AssertionInfo m_lastAssertionInfo;
6897 std::vector<SectionEndInfo> m_unfinishedSections;
6898 std::vector<ITracker*> m_activeSections;
6899 TrackerContext m_trackerContext;
6900 bool m_shouldReportUnexpected;
6901 };
6902
6903 IResultCapture& getResultCapture() {
6904 if( IResultCapture* capture = getCurrentContext().getResultCapture() )
6905 return *capture;
6906 else
6907 throw std::logic_error( "No result capture instance" );
6908 }
6909
6910 } // end namespace Catch
6911
6912 // #included from: internal/catch_version.h
6913 #define TWOBLUECUBES_CATCH_VERSION_H_INCLUDED
6914
6915 namespace Catch {
6916
6917 // Versioning information
6918 struct Version {
6919 Version( unsigned int _majorVersion,
6920 unsigned int _minorVersion,
6921 unsigned int _patchNumber,
6922 char const * const _branchName,
6923 unsigned int _buildNumber );
6924
6925 unsigned int const majorVersion;
6926 unsigned int const minorVersion;
6927 unsigned int const patchNumber;
6928
6929 // buildNumber is only used if branchName is not null
6930 char const * const branchName;
6931 unsigned int const buildNumber;
6932
6933 friend std::ostream& operator << ( std::ostream& os, Version const& version );
6934
6935 private:
6936 void operator=( Version const& );
6937 };
6938
6939 inline Version libraryVersion();
6940 }
6941
6942 #include <fstream>
6943 #include <stdlib.h>
6944 #include <limits>
6945
6946 namespace Catch {
6947
6948 Ptr<IStreamingReporter> createReporter( std::string const& reporterName, Ptr<Config> const& config ) {
6949 Ptr<IStreamingReporter> reporter = getRegistryHub().getReporterRegistry().create( reporterName, config.get() );
6950 if( !reporter ) {
6951 std::ostringstream oss;
6952 oss << "No reporter registered with name: '" << reporterName << "'";
6953 throw std::domain_error( oss.str() );
6954 }
6955 return reporter;
6956 }
6957
6958 Ptr<IStreamingReporter> makeReporter( Ptr<Config> const& config ) {
6959 std::vector<std::string> reporters = config->getReporterNames();
6960 if( reporters.empty() )
6961 reporters.push_back( "console" );
6962
6963 Ptr<IStreamingReporter> reporter;
6964 for( std::vector<std::string>::const_iterator it = reporters.begin(), itEnd = reporters.end();
6965 it != itEnd;
6966 ++it )
6967 reporter = addReporter( reporter, createReporter( *it, config ) );
6968 return reporter;
6969 }
6970 Ptr<IStreamingReporter> addListeners( Ptr<IConfig const> const& config, Ptr<IStreamingReporter> reporters ) {
6971 IReporterRegistry::Listeners listeners = getRegistryHub().getReporterRegistry().getListeners();
6972 for( IReporterRegistry::Listeners::const_iterator it = listeners.begin(), itEnd = listeners.end();
6973 it != itEnd;
6974 ++it )
6975 reporters = addReporter(reporters, (*it)->create( ReporterConfig( config ) ) );
6976 return reporters;
6977 }
6978
6979 Totals runTests( Ptr<Config> const& config ) {
6980
6981 Ptr<IConfig const> iconfig = config.get();
6982
6983 Ptr<IStreamingReporter> reporter = makeReporter( config );
6984 reporter = addListeners( iconfig, reporter );
6985
6986 RunContext context( iconfig, reporter );
6987
6988 Totals totals;
6989
6990 context.testGroupStarting( config->name(), 1, 1 );
6991
6992 TestSpec testSpec = config->testSpec();
6993 if( !testSpec.hasFilters() )
6994 testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "~[.]" ).testSpec(); // All not hidden tests
6995
6996 std::vector<TestCase> const& allTestCases = getAllTestCasesSorted( *iconfig );
6997 for( std::vector<TestCase>::const_iterator it = allTestCases.begin(), itEnd = allTestCases.end();
6998 it != itEnd;
6999 ++it ) {
7000 if( !context.aborting() && matchTest( *it, testSpec, *iconfig ) )
7001 totals += context.runTest( *it );
7002 else
7003 reporter->skipTest( *it );
7004 }
7005
7006 context.testGroupEnded( iconfig->name(), totals, 1, 1 );
7007 return totals;
7008 }
7009
7010 void applyFilenamesAsTags( IConfig const& config ) {
7011 std::vector<TestCase> const& tests = getAllTestCasesSorted( config );
7012 for(std::size_t i = 0; i < tests.size(); ++i ) {
7013 TestCase& test = const_cast<TestCase&>( tests[i] );
7014 std::set<std::string> tags = test.tags;
7015
7016 std::string filename = test.lineInfo.file;
7017 std::string::size_type lastSlash = filename.find_last_of( "\\/" );
7018 if( lastSlash != std::string::npos )
7019 filename = filename.substr( lastSlash+1 );
7020
7021 std::string::size_type lastDot = filename.find_last_of( "." );
7022 if( lastDot != std::string::npos )
7023 filename = filename.substr( 0, lastDot );
7024
7025 tags.insert( "#" + filename );
7026 setTags( test, tags );
7027 }
7028 }
7029
7030 class Session : NonCopyable {
7031 static bool alreadyInstantiated;
7032
7033 public:
7034
7035 struct OnUnusedOptions { enum DoWhat { Ignore, Fail }; };
7036
7037 Session()
7038 : m_cli( makeCommandLineParser() ) {
7039 if( alreadyInstantiated ) {
7040 std::string msg = "Only one instance of Catch::Session can ever be used";
7041 Catch::cerr() << msg << std::endl;
7042 throw std::logic_error( msg );
7043 }
7044 alreadyInstantiated = true;
7045 }
7046 ~Session() {
7047 Catch::cleanUp();
7048 }
7049
7050 void showHelp( std::string const& processName ) {
7051 Catch::cout() << "\nCatch v" << libraryVersion() << "\n";
7052
7053 m_cli.usage( Catch::cout(), processName );
7054 Catch::cout() << "For more detail usage please see the project docs\n" << std::endl;
7055 }
7056
7057 int applyCommandLine( int argc, char const* const* const argv, OnUnusedOptions::DoWhat unusedOptionBehaviour = OnUnusedOptions::Fail ) {
7058 try {
7059 m_cli.setThrowOnUnrecognisedTokens( unusedOptionBehaviour == OnUnusedOptions::Fail );
7060 m_unusedTokens = m_cli.parseInto( Clara::argsToVector( argc, argv ), m_configData );
7061 if( m_configData.showHelp )
7062 showHelp( m_configData.processName );
7063 m_config.reset();
7064 }
7065 catch( std::exception& ex ) {
7066 {
7067 Colour colourGuard( Colour::Red );
7068 Catch::cerr()
7069 << "\nError(s) in input:\n"
7070 << Text( ex.what(), TextAttributes().setIndent(2) )
7071 << "\n\n";
7072 }
7073 m_cli.usage( Catch::cout(), m_configData.processName );
7074 return (std::numeric_limits<int>::max)();
7075 }
7076 return 0;
7077 }
7078
7079 void useConfigData( ConfigData const& _configData ) {
7080 m_configData = _configData;
7081 m_config.reset();
7082 }
7083
7084 int run( int argc, char const* const* const argv ) {
7085
7086 int returnCode = applyCommandLine( argc, argv );
7087 if( returnCode == 0 )
7088 returnCode = run();
7089 return returnCode;
7090 }
7091
7092 #if defined(WIN32) && defined(UNICODE)
7093 int run( int argc, wchar_t const* const* const argv ) {
7094
7095 char **utf8Argv = new char *[ argc ];
7096
7097 for ( int i = 0; i < argc; ++i ) {
7098 int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
7099
7100 utf8Argv[ i ] = new char[ bufSize ];
7101
7102 WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
7103 }
7104
7105 int returnCode = applyCommandLine( argc, utf8Argv );
7106 if( returnCode == 0 )
7107 returnCode = run();
7108
7109 for ( int i = 0; i < argc; ++i )
7110 delete [] utf8Argv[ i ];
7111
7112 delete [] utf8Argv;
7113
7114 return returnCode;
7115 }
7116 #endif
7117
7118 int run() {
7119 if( m_configData.showHelp )
7120 return 0;
7121
7122 try
7123 {
7124 config(); // Force config to be constructed
7125
7126 seedRng( *m_config );
7127
7128 if( m_configData.filenamesAsTags )
7129 applyFilenamesAsTags( *m_config );
7130
7131 // Handle list request
7132 if( Option<std::size_t> listed = list( config() ) )
7133 return static_cast<int>( *listed );
7134
7135 return static_cast<int>( runTests( m_config ).assertions.failed );
7136 }
7137 catch( std::exception& ex ) {
7138 Catch::cerr() << ex.what() << std::endl;
7139 return (std::numeric_limits<int>::max)();
7140 }
7141 }
7142
7143 Clara::CommandLine<ConfigData> const& cli() const {
7144 return m_cli;
7145 }
7146 std::vector<Clara::Parser::Token> const& unusedTokens() const {
7147 return m_unusedTokens;
7148 }
7149 ConfigData& configData() {
7150 return m_configData;
7151 }
7152 Config& config() {
7153 if( !m_config )
7154 m_config = new Config( m_configData );
7155 return *m_config;
7156 }
7157 private:
7158 Clara::CommandLine<ConfigData> m_cli;
7159 std::vector<Clara::Parser::Token> m_unusedTokens;
7160 ConfigData m_configData;
7161 Ptr<Config> m_config;
7162 };
7163
7164 bool Session::alreadyInstantiated = false;
7165
7166 } // end namespace Catch
7167
7168 // #included from: catch_registry_hub.hpp
7169 #define TWOBLUECUBES_CATCH_REGISTRY_HUB_HPP_INCLUDED
7170
7171 // #included from: catch_test_case_registry_impl.hpp
7172 #define TWOBLUECUBES_CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED
7173
7174 #include <vector>
7175 #include <set>
7176 #include <sstream>
7177 #include <algorithm>
7178
7179 namespace Catch {
7180
7181 struct RandomNumberGenerator {
7182 typedef std::ptrdiff_t result_type;
7183
7184 result_type operator()( result_type n ) const { return std::rand() % n; }
7185
7186 #ifdef CATCH_CONFIG_CPP11_SHUFFLE
7187 static constexpr result_type min() { return 0; }
7188 static constexpr result_type max() { return 1000000; }
7189 result_type operator()() const { return std::rand() % max(); }
7190 #endif
7191 template<typename V>
7192 static void shuffle( V& vector ) {
7193 RandomNumberGenerator rng;
7194 #ifdef CATCH_CONFIG_CPP11_SHUFFLE
7195 std::shuffle( vector.begin(), vector.end(), rng );
7196 #else
7197 std::random_shuffle( vector.begin(), vector.end(), rng );
7198 #endif
7199 }
7200 };
7201
7202 inline std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
7203
7204 std::vector<TestCase> sorted = unsortedTestCases;
7205
7206 switch( config.runOrder() ) {
7207 case RunTests::InLexicographicalOrder:
7208 std::sort( sorted.begin(), sorted.end() );
7209 break;
7210 case RunTests::InRandomOrder:
7211 {
7212 seedRng( config );
7213 RandomNumberGenerator::shuffle( sorted );
7214 }
7215 break;
7216 case RunTests::InDeclarationOrder:
7217 // already in declaration order
7218 break;
7219 }
7220 return sorted;
7221 }
7222 bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
7223 return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
7224 }
7225
7226 void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
7227 std::set<TestCase> seenFunctions;
7228 for( std::vector<TestCase>::const_iterator it = functions.begin(), itEnd = functions.end();
7229 it != itEnd;
7230 ++it ) {
7231 std::pair<std::set<TestCase>::const_iterator, bool> prev = seenFunctions.insert( *it );
7232 if( !prev.second ) {
7233 std::ostringstream ss;
7234
7235 ss << Colour( Colour::Red )
7236 << "error: TEST_CASE( \"" << it->name << "\" ) already defined.\n"
7237 << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << '\n'
7238 << "\tRedefined at " << it->getTestCaseInfo().lineInfo << std::endl;
7239
7240 throw std::runtime_error(ss.str());
7241 }
7242 }
7243 }
7244
7245 std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
7246 std::vector<TestCase> filtered;
7247 filtered.reserve( testCases.size() );
7248 for( std::vector<TestCase>::const_iterator it = testCases.begin(), itEnd = testCases.end();
7249 it != itEnd;
7250 ++it )
7251 if( matchTest( *it, testSpec, config ) )
7252 filtered.push_back( *it );
7253 return filtered;
7254 }
7255 std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
7256 return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
7257 }
7258
7259 class TestRegistry : public ITestCaseRegistry {
7260 public:
7261 TestRegistry()
7262 : m_currentSortOrder( RunTests::InDeclarationOrder ),
7263 m_unnamedCount( 0 )
7264 {}
7265 virtual ~TestRegistry();
7266
7267 virtual void registerTest( TestCase const& testCase ) {
7268 std::string name = testCase.getTestCaseInfo().name;
7269 if( name.empty() ) {
7270 std::ostringstream oss;
7271 oss << "Anonymous test case " << ++m_unnamedCount;
7272 return registerTest( testCase.withName( oss.str() ) );
7273 }
7274 m_functions.push_back( testCase );
7275 }
7276
7277 virtual std::vector<TestCase> const& getAllTests() const {
7278 return m_functions;
7279 }
7280 virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const {
7281 if( m_sortedFunctions.empty() )
7282 enforceNoDuplicateTestCases( m_functions );
7283
7284 if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
7285 m_sortedFunctions = sortTests( config, m_functions );
7286 m_currentSortOrder = config.runOrder();
7287 }
7288 return m_sortedFunctions;
7289 }
7290
7291 private:
7292 std::vector<TestCase> m_functions;
7293 mutable RunTests::InWhatOrder m_currentSortOrder;
7294 mutable std::vector<TestCase> m_sortedFunctions;
7295 size_t m_unnamedCount;
7296 std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
7297 };
7298
7299 ///////////////////////////////////////////////////////////////////////////
7300
7301 class FreeFunctionTestCase : public SharedImpl<ITestCase> {
7302 public:
7303
7304 FreeFunctionTestCase( TestFunction fun ) : m_fun( fun ) {}
7305
7306 virtual void invoke() const {
7307 m_fun();
7308 }
7309
7310 private:
7311 virtual ~FreeFunctionTestCase();
7312
7313 TestFunction m_fun;
7314 };
7315
7316 inline std::string extractClassName( std::string const& classOrQualifiedMethodName ) {
7317 std::string className = classOrQualifiedMethodName;
7318 if( startsWith( className, '&' ) )
7319 {
7320 std::size_t lastColons = className.rfind( "::" );
7321 std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
7322 if( penultimateColons == std::string::npos )
7323 penultimateColons = 1;
7324 className = className.substr( penultimateColons, lastColons-penultimateColons );
7325 }
7326 return className;
7327 }
7328
7329 void registerTestCase
7330 ( ITestCase* testCase,
7331 char const* classOrQualifiedMethodName,
7332 NameAndDesc const& nameAndDesc,
7333 SourceLineInfo const& lineInfo ) {
7334
7335 getMutableRegistryHub().registerTest
7336 ( makeTestCase
7337 ( testCase,
7338 extractClassName( classOrQualifiedMethodName ),
7339 nameAndDesc.name,
7340 nameAndDesc.description,
7341 lineInfo ) );
7342 }
7343 void registerTestCaseFunction
7344 ( TestFunction function,
7345 SourceLineInfo const& lineInfo,
7346 NameAndDesc const& nameAndDesc ) {
7347 registerTestCase( new FreeFunctionTestCase( function ), "", nameAndDesc, lineInfo );
7348 }
7349
7350 ///////////////////////////////////////////////////////////////////////////
7351
7352 AutoReg::AutoReg
7353 ( TestFunction function,
7354 SourceLineInfo const& lineInfo,
7355 NameAndDesc const& nameAndDesc ) {
7356 registerTestCaseFunction( function, lineInfo, nameAndDesc );
7357 }
7358
7359 AutoReg::~AutoReg() {}
7360
7361 } // end namespace Catch
7362
7363 // #included from: catch_reporter_registry.hpp
7364 #define TWOBLUECUBES_CATCH_REPORTER_REGISTRY_HPP_INCLUDED
7365
7366 #include <map>
7367
7368 namespace Catch {
7369
7370 class ReporterRegistry : public IReporterRegistry {
7371
7372 public:
7373
7374 virtual ~ReporterRegistry() CATCH_OVERRIDE {}
7375
7376 virtual IStreamingReporter* create( std::string const& name, Ptr<IConfig const> const& config ) const CATCH_OVERRIDE {
7377 FactoryMap::const_iterator it = m_factories.find( name );
7378 if( it == m_factories.end() )
7379 return CATCH_NULL;
7380 return it->second->create( ReporterConfig( config ) );
7381 }
7382
7383 void registerReporter( std::string const& name, Ptr<IReporterFactory> const& factory ) {
7384 m_factories.insert( std::make_pair( name, factory ) );
7385 }
7386 void registerListener( Ptr<IReporterFactory> const& factory ) {
7387 m_listeners.push_back( factory );
7388 }
7389
7390 virtual FactoryMap const& getFactories() const CATCH_OVERRIDE {
7391 return m_factories;
7392 }
7393 virtual Listeners const& getListeners() const CATCH_OVERRIDE {
7394 return m_listeners;
7395 }
7396
7397 private:
7398 FactoryMap m_factories;
7399 Listeners m_listeners;
7400 };
7401 }
7402
7403 // #included from: catch_exception_translator_registry.hpp
7404 #define TWOBLUECUBES_CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED
7405
7406 #ifdef __OBJC__
7407 #import "Foundation/Foundation.h"
7408 #endif
7409
7410 namespace Catch {
7411
7412 class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
7413 public:
7414 ~ExceptionTranslatorRegistry() {
7415 deleteAll( m_translators );
7416 }
7417
7418 virtual void registerTranslator( const IExceptionTranslator* translator ) {
7419 m_translators.push_back( translator );
7420 }
7421
7422 virtual std::string translateActiveException() const {
7423 try {
7424 #ifdef __OBJC__
7425 // In Objective-C try objective-c exceptions first
7426 @try {
7427 return tryTranslators();
7428 }
7429 @catch (NSException *exception) {
7430 return Catch::toString( [exception description] );
7431 }
7432 #else
7433 return tryTranslators();
7434 #endif
7435 }
7436 catch( TestFailureException& ) {
7437 throw;
7438 }
7439 catch( std::exception& ex ) {
7440 return ex.what();
7441 }
7442 catch( std::string& msg ) {
7443 return msg;
7444 }
7445 catch( const char* msg ) {
7446 return msg;
7447 }
7448 catch(...) {
7449 return "Unknown exception";
7450 }
7451 }
7452
7453 std::string tryTranslators() const {
7454 if( m_translators.empty() )
7455 throw;
7456 else
7457 return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() );
7458 }
7459
7460 private:
7461 std::vector<const IExceptionTranslator*> m_translators;
7462 };
7463 }
7464
7465 // #included from: catch_tag_alias_registry.h
7466 #define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_H_INCLUDED
7467
7468 #include <map>
7469
7470 namespace Catch {
7471
7472 class TagAliasRegistry : public ITagAliasRegistry {
7473 public:
7474 virtual ~TagAliasRegistry();
7475 virtual Option<TagAlias> find( std::string const& alias ) const;
7476 virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const;
7477 void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
7478
7479 private:
7480 std::map<std::string, TagAlias> m_registry;
7481 };
7482
7483 } // end namespace Catch
7484
7485 namespace Catch {
7486
7487 namespace {
7488
7489 class RegistryHub : public IRegistryHub, public IMutableRegistryHub {
7490
7491 RegistryHub( RegistryHub const& );
7492 void operator=( RegistryHub const& );
7493
7494 public: // IRegistryHub
7495 RegistryHub() {
7496 }
7497 virtual IReporterRegistry const& getReporterRegistry() const CATCH_OVERRIDE {
7498 return m_reporterRegistry;
7499 }
7500 virtual ITestCaseRegistry const& getTestCaseRegistry() const CATCH_OVERRIDE {
7501 return m_testCaseRegistry;
7502 }
7503 virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() CATCH_OVERRIDE {
7504 return m_exceptionTranslatorRegistry;
7505 }
7506 virtual ITagAliasRegistry const& getTagAliasRegistry() const CATCH_OVERRIDE {
7507 return m_tagAliasRegistry;
7508 }
7509
7510 public: // IMutableRegistryHub
7511 virtual void registerReporter( std::string const& name, Ptr<IReporterFactory> const& factory ) CATCH_OVERRIDE {
7512 m_reporterRegistry.registerReporter( name, factory );
7513 }
7514 virtual void registerListener( Ptr<IReporterFactory> const& factory ) CATCH_OVERRIDE {
7515 m_reporterRegistry.registerListener( factory );
7516 }
7517 virtual void registerTest( TestCase const& testInfo ) CATCH_OVERRIDE {
7518 m_testCaseRegistry.registerTest( testInfo );
7519 }
7520 virtual void registerTranslator( const IExceptionTranslator* translator ) CATCH_OVERRIDE {
7521 m_exceptionTranslatorRegistry.registerTranslator( translator );
7522 }
7523 virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) CATCH_OVERRIDE {
7524 m_tagAliasRegistry.add( alias, tag, lineInfo );
7525 }
7526
7527 private:
7528 TestRegistry m_testCaseRegistry;
7529 ReporterRegistry m_reporterRegistry;
7530 ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
7531 TagAliasRegistry m_tagAliasRegistry;
7532 };
7533
7534 // Single, global, instance
7535 inline RegistryHub*& getTheRegistryHub() {
7536 static RegistryHub* theRegistryHub = CATCH_NULL;
7537 if( !theRegistryHub )
7538 theRegistryHub = new RegistryHub();
7539 return theRegistryHub;
7540 }
7541 }
7542
7543 IRegistryHub& getRegistryHub() {
7544 return *getTheRegistryHub();
7545 }
7546 IMutableRegistryHub& getMutableRegistryHub() {
7547 return *getTheRegistryHub();
7548 }
7549 void cleanUp() {
7550 delete getTheRegistryHub();
7551 getTheRegistryHub() = CATCH_NULL;
7552 cleanUpContext();
7553 }
7554 std::string translateActiveException() {
7555 return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
7556 }
7557
7558 } // end namespace Catch
7559
7560 // #included from: catch_notimplemented_exception.hpp
7561 #define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_HPP_INCLUDED
7562
7563 #include <sstream>
7564
7565 namespace Catch {
7566
7567 NotImplementedException::NotImplementedException( SourceLineInfo const& lineInfo )
7568 : m_lineInfo( lineInfo ) {
7569 std::ostringstream oss;
7570 oss << lineInfo << ": function ";
7571 oss << "not implemented";
7572 m_what = oss.str();
7573 }
7574
7575 const char* NotImplementedException::what() const CATCH_NOEXCEPT {
7576 return m_what.c_str();
7577 }
7578
7579 } // end namespace Catch
7580
7581 // #included from: catch_context_impl.hpp
7582 #define TWOBLUECUBES_CATCH_CONTEXT_IMPL_HPP_INCLUDED
7583
7584 // #included from: catch_stream.hpp
7585 #define TWOBLUECUBES_CATCH_STREAM_HPP_INCLUDED
7586
7587 #include <stdexcept>
7588 #include <cstdio>
7589 #include <iostream>
7590
7591 namespace Catch {
7592
7593 template<typename WriterF, size_t bufferSize=256>
7594 class StreamBufImpl : public StreamBufBase {
7595 char data[bufferSize];
7596 WriterF m_writer;
7597
7598 public:
7599 StreamBufImpl() {
7600 setp( data, data + sizeof(data) );
7601 }
7602
7603 ~StreamBufImpl() CATCH_NOEXCEPT {
7604 sync();
7605 }
7606
7607 private:
7608 int overflow( int c ) {
7609 sync();
7610
7611 if( c != EOF ) {
7612 if( pbase() == epptr() )
7613 m_writer( std::string( 1, static_cast<char>( c ) ) );
7614 else
7615 sputc( static_cast<char>( c ) );
7616 }
7617 return 0;
7618 }
7619
7620 int sync() {
7621 if( pbase() != pptr() ) {
7622 m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
7623 setp( pbase(), epptr() );
7624 }
7625 return 0;
7626 }
7627 };
7628
7629 ///////////////////////////////////////////////////////////////////////////
7630
7631 FileStream::FileStream( std::string const& filename ) {
7632 m_ofs.open( filename.c_str() );
7633 if( m_ofs.fail() ) {
7634 std::ostringstream oss;
7635 oss << "Unable to open file: '" << filename << '\'';
7636 throw std::domain_error( oss.str() );
7637 }
7638 }
7639
7640 std::ostream& FileStream::stream() const {
7641 return m_ofs;
7642 }
7643
7644 struct OutputDebugWriter {
7645
7646 void operator()( std::string const&str ) {
7647 writeToDebugConsole( str );
7648 }
7649 };
7650
7651 DebugOutStream::DebugOutStream()
7652 : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
7653 m_os( m_streamBuf.get() )
7654 {}
7655
7656 std::ostream& DebugOutStream::stream() const {
7657 return m_os;
7658 }
7659
7660 // Store the streambuf from cout up-front because
7661 // cout may get redirected when running tests
7662 CoutStream::CoutStream()
7663 : m_os( Catch::cout().rdbuf() )
7664 {}
7665
7666 std::ostream& CoutStream::stream() const {
7667 return m_os;
7668 }
7669
7670 #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
7671 std::ostream& cout() {
7672 return std::cout;
7673 }
7674 std::ostream& cerr() {
7675 return std::cerr;
7676 }
7677 #endif
7678 }
7679
7680 namespace Catch {
7681
7682 class Context : public IMutableContext {
7683
7684 Context() : m_config( CATCH_NULL ), m_runner( CATCH_NULL ), m_resultCapture( CATCH_NULL ) {}
7685 Context( Context const& );
7686 void operator=( Context const& );
7687
7688 public:
7689 virtual ~Context() {
7690 deleteAllValues( m_generatorsByTestName );
7691 }
7692
7693 public: // IContext
7694 virtual IResultCapture* getResultCapture() {
7695 return m_resultCapture;
7696 }
7697 virtual IRunner* getRunner() {
7698 return m_runner;
7699 }
7700 virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) {
7701 return getGeneratorsForCurrentTest()
7702 .getGeneratorInfo( fileInfo, totalSize )
7703 .getCurrentIndex();
7704 }
7705 virtual bool advanceGeneratorsForCurrentTest() {
7706 IGeneratorsForTest* generators = findGeneratorsForCurrentTest();
7707 return generators && generators->moveNext();
7708 }
7709
7710 virtual Ptr<IConfig const> getConfig() const {
7711 return m_config;
7712 }
7713
7714 public: // IMutableContext
7715 virtual void setResultCapture( IResultCapture* resultCapture ) {
7716 m_resultCapture = resultCapture;
7717 }
7718 virtual void setRunner( IRunner* runner ) {
7719 m_runner = runner;
7720 }
7721 virtual void setConfig( Ptr<IConfig const> const& config ) {
7722 m_config = config;
7723 }
7724
7725 friend IMutableContext& getCurrentMutableContext();
7726
7727 private:
7728 IGeneratorsForTest* findGeneratorsForCurrentTest() {
7729 std::string testName = getResultCapture()->getCurrentTestName();
7730
7731 std::map<std::string, IGeneratorsForTest*>::const_iterator it =
7732 m_generatorsByTestName.find( testName );
7733 return it != m_generatorsByTestName.end()
7734 ? it->second
7735 : CATCH_NULL;
7736 }
7737
7738 IGeneratorsForTest& getGeneratorsForCurrentTest() {
7739 IGeneratorsForTest* generators = findGeneratorsForCurrentTest();
7740 if( !generators ) {
7741 std::string testName = getResultCapture()->getCurrentTestName();
7742 generators = createGeneratorsForTest();
7743 m_generatorsByTestName.insert( std::make_pair( testName, generators ) );
7744 }
7745 return *generators;
7746 }
7747
7748 private:
7749 Ptr<IConfig const> m_config;
7750 IRunner* m_runner;
7751 IResultCapture* m_resultCapture;
7752 std::map<std::string, IGeneratorsForTest*> m_generatorsByTestName;
7753 };
7754
7755 namespace {
7756 Context* currentContext = CATCH_NULL;
7757 }
7758 IMutableContext& getCurrentMutableContext() {
7759 if( !currentContext )
7760 currentContext = new Context();
7761 return *currentContext;
7762 }
7763 IContext& getCurrentContext() {
7764 return getCurrentMutableContext();
7765 }
7766
7767 void cleanUpContext() {
7768 delete currentContext;
7769 currentContext = CATCH_NULL;
7770 }
7771 }
7772
7773 // #included from: catch_console_colour_impl.hpp
7774 #define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_IMPL_HPP_INCLUDED
7775
7776 // #included from: catch_errno_guard.hpp
7777 #define TWOBLUECUBES_CATCH_ERRNO_GUARD_HPP_INCLUDED
7778
7779 #include <cerrno>
7780
7781 namespace Catch {
7782
7783 class ErrnoGuard {
7784 public:
7785 ErrnoGuard():m_oldErrno(errno){}
7786 ~ErrnoGuard() { errno = m_oldErrno; }
7787 private:
7788 int m_oldErrno;
7789 };
7790
7791 }
7792
7793 namespace Catch {
7794 namespace {
7795
7796 struct IColourImpl {
7797 virtual ~IColourImpl() {}
7798 virtual void use( Colour::Code _colourCode ) = 0;
7799 };
7800
7801 struct NoColourImpl : IColourImpl {
7802 void use( Colour::Code ) {}
7803
7804 static IColourImpl* instance() {
7805 static NoColourImpl s_instance;
7806 return &s_instance;
7807 }
7808 };
7809
7810 } // anon namespace
7811 } // namespace Catch
7812
7813 #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
7814 # ifdef CATCH_PLATFORM_WINDOWS
7815 # define CATCH_CONFIG_COLOUR_WINDOWS
7816 # else
7817 # define CATCH_CONFIG_COLOUR_ANSI
7818 # endif
7819 #endif
7820
7821 #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
7822
7823 namespace Catch {
7824 namespace {
7825
7826 class Win32ColourImpl : public IColourImpl {
7827 public:
7828 Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
7829 {
7830 CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
7831 GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
7832 originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
7833 originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
7834 }
7835
7836 virtual void use( Colour::Code _colourCode ) {
7837 switch( _colourCode ) {
7838 case Colour::None: return setTextAttribute( originalForegroundAttributes );
7839 case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
7840 case Colour::Red: return setTextAttribute( FOREGROUND_RED );
7841 case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
7842 case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
7843 case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
7844 case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
7845 case Colour::Grey: return setTextAttribute( 0 );
7846
7847 case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
7848 case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
7849 case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
7850 case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
7851
7852 case Colour::Bright: throw std::logic_error( "not a colour" );
7853 }
7854 }
7855
7856 private:
7857 void setTextAttribute( WORD _textAttribute ) {
7858 SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
7859 }
7860 HANDLE stdoutHandle;
7861 WORD originalForegroundAttributes;
7862 WORD originalBackgroundAttributes;
7863 };
7864
7865 IColourImpl* platformColourInstance() {
7866 static Win32ColourImpl s_instance;
7867
7868 Ptr<IConfig const> config = getCurrentContext().getConfig();
7869 UseColour::YesOrNo colourMode = config
7870 ? config->useColour()
7871 : UseColour::Auto;
7872 if( colourMode == UseColour::Auto )
7873 colourMode = !isDebuggerActive()
7874 ? UseColour::Yes
7875 : UseColour::No;
7876 return colourMode == UseColour::Yes
7877 ? &s_instance
7878 : NoColourImpl::instance();
7879 }
7880
7881 } // end anon namespace
7882 } // end namespace Catch
7883
7884 #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
7885
7886 #include <unistd.h>
7887
7888 namespace Catch {
7889 namespace {
7890
7891 // use POSIX/ ANSI console terminal codes
7892 // Thanks to Adam Strzelecki for original contribution
7893 // (http://github.com/nanoant)
7894 // https://github.com/philsquared/Catch/pull/131
7895 class PosixColourImpl : public IColourImpl {
7896 public:
7897 virtual void use( Colour::Code _colourCode ) {
7898 switch( _colourCode ) {
7899 case Colour::None:
7900 case Colour::White: return setColour( "[0m" );
7901 case Colour::Red: return setColour( "[0;31m" );
7902 case Colour::Green: return setColour( "[0;32m" );
7903 case Colour::Blue: return setColour( "[0;34m" );
7904 case Colour::Cyan: return setColour( "[0;36m" );
7905 case Colour::Yellow: return setColour( "[0;33m" );
7906 case Colour::Grey: return setColour( "[1;30m" );
7907
7908 case Colour::LightGrey: return setColour( "[0;37m" );
7909 case Colour::BrightRed: return setColour( "[1;31m" );
7910 case Colour::BrightGreen: return setColour( "[1;32m" );
7911 case Colour::BrightWhite: return setColour( "[1;37m" );
7912
7913 case Colour::Bright: throw std::logic_error( "not a colour" );
7914 }
7915 }
7916 static IColourImpl* instance() {
7917 static PosixColourImpl s_instance;
7918 return &s_instance;
7919 }
7920
7921 private:
7922 void setColour( const char* _escapeCode ) {
7923 Catch::cout() << '\033' << _escapeCode;
7924 }
7925 };
7926
7927 IColourImpl* platformColourInstance() {
7928 ErrnoGuard guard;
7929 Ptr<IConfig const> config = getCurrentContext().getConfig();
7930 UseColour::YesOrNo colourMode = config
7931 ? config->useColour()
7932 : UseColour::Auto;
7933 if( colourMode == UseColour::Auto )
7934 colourMode = (!isDebuggerActive() && isatty(STDOUT_FILENO) )
7935 ? UseColour::Yes
7936 : UseColour::No;
7937 return colourMode == UseColour::Yes
7938 ? PosixColourImpl::instance()
7939 : NoColourImpl::instance();
7940 }
7941
7942 } // end anon namespace
7943 } // end namespace Catch
7944
7945 #else // not Windows or ANSI ///////////////////////////////////////////////
7946
7947 namespace Catch {
7948
7949 static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
7950
7951 } // end namespace Catch
7952
7953 #endif // Windows/ ANSI/ None
7954
7955 namespace Catch {
7956
7957 Colour::Colour( Code _colourCode ) : m_moved( false ) { use( _colourCode ); }
7958 Colour::Colour( Colour const& _other ) : m_moved( false ) { const_cast<Colour&>( _other ).m_moved = true; }
7959 Colour::~Colour(){ if( !m_moved ) use( None ); }
7960
7961 void Colour::use( Code _colourCode ) {
7962 static IColourImpl* impl = platformColourInstance();
7963 impl->use( _colourCode );
7964 }
7965
7966 } // end namespace Catch
7967
7968 // #included from: catch_generators_impl.hpp
7969 #define TWOBLUECUBES_CATCH_GENERATORS_IMPL_HPP_INCLUDED
7970
7971 #include <vector>
7972 #include <string>
7973 #include <map>
7974
7975 namespace Catch {
7976
7977 struct GeneratorInfo : IGeneratorInfo {
7978
7979 GeneratorInfo( std::size_t size )
7980 : m_size( size ),
7981 m_currentIndex( 0 )
7982 {}
7983
7984 bool moveNext() {
7985 if( ++m_currentIndex == m_size ) {
7986 m_currentIndex = 0;
7987 return false;
7988 }
7989 return true;
7990 }
7991
7992 std::size_t getCurrentIndex() const {
7993 return m_currentIndex;
7994 }
7995
7996 std::size_t m_size;
7997 std::size_t m_currentIndex;
7998 };
7999
8000 ///////////////////////////////////////////////////////////////////////////
8001
8002 class GeneratorsForTest : public IGeneratorsForTest {
8003
8004 public:
8005 ~GeneratorsForTest() {
8006 deleteAll( m_generatorsInOrder );
8007 }
8008
8009 IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) {
8010 std::map<std::string, IGeneratorInfo*>::const_iterator it = m_generatorsByName.find( fileInfo );
8011 if( it == m_generatorsByName.end() ) {
8012 IGeneratorInfo* info = new GeneratorInfo( size );
8013 m_generatorsByName.insert( std::make_pair( fileInfo, info ) );
8014 m_generatorsInOrder.push_back( info );
8015 return *info;
8016 }
8017 return *it->second;
8018 }
8019
8020 bool moveNext() {
8021 std::vector<IGeneratorInfo*>::const_iterator it = m_generatorsInOrder.begin();
8022 std::vector<IGeneratorInfo*>::const_iterator itEnd = m_generatorsInOrder.end();
8023 for(; it != itEnd; ++it ) {
8024 if( (*it)->moveNext() )
8025 return true;
8026 }
8027 return false;
8028 }
8029
8030 private:
8031 std::map<std::string, IGeneratorInfo*> m_generatorsByName;
8032 std::vector<IGeneratorInfo*> m_generatorsInOrder;
8033 };
8034
8035 IGeneratorsForTest* createGeneratorsForTest()
8036 {
8037 return new GeneratorsForTest();
8038 }
8039
8040 } // end namespace Catch
8041
8042 // #included from: catch_assertionresult.hpp
8043 #define TWOBLUECUBES_CATCH_ASSERTIONRESULT_HPP_INCLUDED
8044
8045 namespace Catch {
8046
8047 AssertionInfo::AssertionInfo( char const * _macroName,
8048 SourceLineInfo const& _lineInfo,
8049 char const * _capturedExpression,
8050 ResultDisposition::Flags _resultDisposition,
8051 char const * _secondArg)
8052 : macroName( _macroName ),
8053 lineInfo( _lineInfo ),
8054 capturedExpression( _capturedExpression ),
8055 resultDisposition( _resultDisposition ),
8056 secondArg( _secondArg )
8057 {}
8058
8059 AssertionResult::AssertionResult() {}
8060
8061 AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
8062 : m_info( info ),
8063 m_resultData( data )
8064 {}
8065
8066 AssertionResult::~AssertionResult() {}
8067
8068 // Result was a success
8069 bool AssertionResult::succeeded() const {
8070 return Catch::isOk( m_resultData.resultType );
8071 }
8072
8073 // Result was a success, or failure is suppressed
8074 bool AssertionResult::isOk() const {
8075 return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
8076 }
8077
8078 ResultWas::OfType AssertionResult::getResultType() const {
8079 return m_resultData.resultType;
8080 }
8081
8082 bool AssertionResult::hasExpression() const {
8083 return m_info.capturedExpression[0] != 0;
8084 }
8085
8086 bool AssertionResult::hasMessage() const {
8087 return !m_resultData.message.empty();
8088 }
8089
8090 std::string capturedExpressionWithSecondArgument( char const * capturedExpression, char const * secondArg ) {
8091 return (secondArg[0] == 0 || secondArg[0] == '"' && secondArg[1] == '"')
8092 ? capturedExpression
8093 : std::string(capturedExpression) + ", " + secondArg;
8094 }
8095
8096 std::string AssertionResult::getExpression() const {
8097 if( isFalseTest( m_info.resultDisposition ) )
8098 return '!' + capturedExpressionWithSecondArgument(m_info.capturedExpression, m_info.secondArg);
8099 else
8100 return capturedExpressionWithSecondArgument(m_info.capturedExpression, m_info.secondArg);
8101 }
8102 std::string AssertionResult::getExpressionInMacro() const {
8103 if( m_info.macroName[0] == 0 )
8104 return capturedExpressionWithSecondArgument(m_info.capturedExpression, m_info.secondArg);
8105 else
8106 return std::string(m_info.macroName) + "( " + capturedExpressionWithSecondArgument(m_info.capturedExpression, m_info.secondArg) + " )";
8107 }
8108
8109 bool AssertionResult::hasExpandedExpression() const {
8110 return hasExpression() && getExpandedExpression() != getExpression();
8111 }
8112
8113 std::string AssertionResult::getExpandedExpression() const {
8114 return m_resultData.reconstructExpression();
8115 }
8116
8117 std::string AssertionResult::getMessage() const {
8118 return m_resultData.message;
8119 }
8120 SourceLineInfo AssertionResult::getSourceInfo() const {
8121 return m_info.lineInfo;
8122 }
8123
8124 std::string AssertionResult::getTestMacroName() const {
8125 return m_info.macroName;
8126 }
8127
8128 void AssertionResult::discardDecomposedExpression() const {
8129 m_resultData.decomposedExpression = CATCH_NULL;
8130 }
8131
8132 void AssertionResult::expandDecomposedExpression() const {
8133 m_resultData.reconstructExpression();
8134 }
8135
8136 } // end namespace Catch
8137
8138 // #included from: catch_test_case_info.hpp
8139 #define TWOBLUECUBES_CATCH_TEST_CASE_INFO_HPP_INCLUDED
8140
8141 #include <cctype>
8142
8143 namespace Catch {
8144
8145 inline TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
8146 if( startsWith( tag, '.' ) ||
8147 tag == "hide" ||
8148 tag == "!hide" )
8149 return TestCaseInfo::IsHidden;
8150 else if( tag == "!throws" )
8151 return TestCaseInfo::Throws;
8152 else if( tag == "!shouldfail" )
8153 return TestCaseInfo::ShouldFail;
8154 else if( tag == "!mayfail" )
8155 return TestCaseInfo::MayFail;
8156 else if( tag == "!nonportable" )
8157 return TestCaseInfo::NonPortable;
8158 else
8159 return TestCaseInfo::None;
8160 }
8161 inline bool isReservedTag( std::string const& tag ) {
8162 return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( tag[0] );
8163 }
8164 inline void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
8165 if( isReservedTag( tag ) ) {
8166 std::ostringstream ss;
8167 ss << Colour(Colour::Red)
8168 << "Tag name [" << tag << "] not allowed.\n"
8169 << "Tag names starting with non alpha-numeric characters are reserved\n"
8170 << Colour(Colour::FileName)
8171 << _lineInfo << '\n';
8172 throw std::runtime_error(ss.str());
8173 }
8174 }
8175
8176 TestCase makeTestCase( ITestCase* _testCase,
8177 std::string const& _className,
8178 std::string const& _name,
8179 std::string const& _descOrTags,
8180 SourceLineInfo const& _lineInfo )
8181 {
8182 bool isHidden( startsWith( _name, "./" ) ); // Legacy support
8183
8184 // Parse out tags
8185 std::set<std::string> tags;
8186 std::string desc, tag;
8187 bool inTag = false;
8188 for( std::size_t i = 0; i < _descOrTags.size(); ++i ) {
8189 char c = _descOrTags[i];
8190 if( !inTag ) {
8191 if( c == '[' )
8192 inTag = true;
8193 else
8194 desc += c;
8195 }
8196 else {
8197 if( c == ']' ) {
8198 TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
8199 if( prop == TestCaseInfo::IsHidden )
8200 isHidden = true;
8201 else if( prop == TestCaseInfo::None )
8202 enforceNotReservedTag( tag, _lineInfo );
8203
8204 tags.insert( tag );
8205 tag.clear();
8206 inTag = false;
8207 }
8208 else
8209 tag += c;
8210 }
8211 }
8212 if( isHidden ) {
8213 tags.insert( "hide" );
8214 tags.insert( "." );
8215 }
8216
8217 TestCaseInfo info( _name, _className, desc, tags, _lineInfo );
8218 return TestCase( _testCase, info );
8219 }
8220
8221 void setTags( TestCaseInfo& testCaseInfo, std::set<std::string> const& tags )
8222 {
8223 testCaseInfo.tags = tags;
8224 testCaseInfo.lcaseTags.clear();
8225
8226 std::ostringstream oss;
8227 for( std::set<std::string>::const_iterator it = tags.begin(), itEnd = tags.end(); it != itEnd; ++it ) {
8228 oss << '[' << *it << ']';
8229 std::string lcaseTag = toLower( *it );
8230 testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
8231 testCaseInfo.lcaseTags.insert( lcaseTag );
8232 }
8233 testCaseInfo.tagsAsString = oss.str();
8234 }
8235
8236 TestCaseInfo::TestCaseInfo( std::string const& _name,
8237 std::string const& _className,
8238 std::string const& _description,
8239 std::set<std::string> const& _tags,
8240 SourceLineInfo const& _lineInfo )
8241 : name( _name ),
8242 className( _className ),
8243 description( _description ),
8244 lineInfo( _lineInfo ),
8245 properties( None )
8246 {
8247 setTags( *this, _tags );
8248 }
8249
8250 TestCaseInfo::TestCaseInfo( TestCaseInfo const& other )
8251 : name( other.name ),
8252 className( other.className ),
8253 description( other.description ),
8254 tags( other.tags ),
8255 lcaseTags( other.lcaseTags ),
8256 tagsAsString( other.tagsAsString ),
8257 lineInfo( other.lineInfo ),
8258 properties( other.properties )
8259 {}
8260
8261 bool TestCaseInfo::isHidden() const {
8262 return ( properties & IsHidden ) != 0;
8263 }
8264 bool TestCaseInfo::throws() const {
8265 return ( properties & Throws ) != 0;
8266 }
8267 bool TestCaseInfo::okToFail() const {
8268 return ( properties & (ShouldFail | MayFail ) ) != 0;
8269 }
8270 bool TestCaseInfo::expectedToFail() const {
8271 return ( properties & (ShouldFail ) ) != 0;
8272 }
8273
8274 TestCase::TestCase( ITestCase* testCase, TestCaseInfo const& info ) : TestCaseInfo( info ), test( testCase ) {}
8275
8276 TestCase::TestCase( TestCase const& other )
8277 : TestCaseInfo( other ),
8278 test( other.test )
8279 {}
8280
8281 TestCase TestCase::withName( std::string const& _newName ) const {
8282 TestCase other( *this );
8283 other.name = _newName;
8284 return other;
8285 }
8286
8287 void TestCase::swap( TestCase& other ) {
8288 test.swap( other.test );
8289 name.swap( other.name );
8290 className.swap( other.className );
8291 description.swap( other.description );
8292 tags.swap( other.tags );
8293 lcaseTags.swap( other.lcaseTags );
8294 tagsAsString.swap( other.tagsAsString );
8295 std::swap( TestCaseInfo::properties, static_cast<TestCaseInfo&>( other ).properties );
8296 std::swap( lineInfo, other.lineInfo );
8297 }
8298
8299 void TestCase::invoke() const {
8300 test->invoke();
8301 }
8302
8303 bool TestCase::operator == ( TestCase const& other ) const {
8304 return test.get() == other.test.get() &&
8305 name == other.name &&
8306 className == other.className;
8307 }
8308
8309 bool TestCase::operator < ( TestCase const& other ) const {
8310 return name < other.name;
8311 }
8312 TestCase& TestCase::operator = ( TestCase const& other ) {
8313 TestCase temp( other );
8314 swap( temp );
8315 return *this;
8316 }
8317
8318 TestCaseInfo const& TestCase::getTestCaseInfo() const
8319 {
8320 return *this;
8321 }
8322
8323 } // end namespace Catch
8324
8325 // #included from: catch_version.hpp
8326 #define TWOBLUECUBES_CATCH_VERSION_HPP_INCLUDED
8327
8328 namespace Catch {
8329
8330 Version::Version
8331 ( unsigned int _majorVersion,
8332 unsigned int _minorVersion,
8333 unsigned int _patchNumber,
8334 char const * const _branchName,
8335 unsigned int _buildNumber )
8336 : majorVersion( _majorVersion ),
8337 minorVersion( _minorVersion ),
8338 patchNumber( _patchNumber ),
8339 branchName( _branchName ),
8340 buildNumber( _buildNumber )
8341 {}
8342
8343 std::ostream& operator << ( std::ostream& os, Version const& version ) {
8344 os << version.majorVersion << '.'
8345 << version.minorVersion << '.'
8346 << version.patchNumber;
8347 // branchName is never null -> 0th char is \0 if it is empty
8348 if (version.branchName[0]) {
8349 os << '-' << version.branchName
8350 << '.' << version.buildNumber;
8351 }
8352 return os;
8353 }
8354
8355 inline Version libraryVersion() {
8356 static Version version( 1, 9, 6, "", 0 );
8357 return version;
8358 }
8359
8360 }
8361
8362 // #included from: catch_message.hpp
8363 #define TWOBLUECUBES_CATCH_MESSAGE_HPP_INCLUDED
8364
8365 namespace Catch {
8366
8367 MessageInfo::MessageInfo( std::string const& _macroName,
8368 SourceLineInfo const& _lineInfo,
8369 ResultWas::OfType _type )
8370 : macroName( _macroName ),
8371 lineInfo( _lineInfo ),
8372 type( _type ),
8373 sequence( ++globalCount )
8374 {}
8375
8376 // This may need protecting if threading support is added
8377 unsigned int MessageInfo::globalCount = 0;
8378
8379 ////////////////////////////////////////////////////////////////////////////
8380
8381 ScopedMessage::ScopedMessage( MessageBuilder const& builder )
8382 : m_info( builder.m_info )
8383 {
8384 m_info.message = builder.m_stream.str();
8385 getResultCapture().pushScopedMessage( m_info );
8386 }
8387 ScopedMessage::ScopedMessage( ScopedMessage const& other )
8388 : m_info( other.m_info )
8389 {}
8390
8391 ScopedMessage::~ScopedMessage() {
8392 if ( !std::uncaught_exception() ){
8393 getResultCapture().popScopedMessage(m_info);
8394 }
8395 }
8396
8397 } // end namespace Catch
8398
8399 // #included from: catch_legacy_reporter_adapter.hpp
8400 #define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_HPP_INCLUDED
8401
8402 // #included from: catch_legacy_reporter_adapter.h
8403 #define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_H_INCLUDED
8404
8405 namespace Catch
8406 {
8407 // Deprecated
8408 struct IReporter : IShared {
8409 virtual ~IReporter();
8410
8411 virtual bool shouldRedirectStdout() const = 0;
8412
8413 virtual void StartTesting() = 0;
8414 virtual void EndTesting( Totals const& totals ) = 0;
8415 virtual void StartGroup( std::string const& groupName ) = 0;
8416 virtual void EndGroup( std::string const& groupName, Totals const& totals ) = 0;
8417 virtual void StartTestCase( TestCaseInfo const& testInfo ) = 0;
8418 virtual void EndTestCase( TestCaseInfo const& testInfo, Totals const& totals, std::string const& stdOut, std::string const& stdErr ) = 0;
8419 virtual void StartSection( std::string const& sectionName, std::string const& description ) = 0;
8420 virtual void EndSection( std::string const& sectionName, Counts const& assertions ) = 0;
8421 virtual void NoAssertionsInSection( std::string const& sectionName ) = 0;
8422 virtual void NoAssertionsInTestCase( std::string const& testName ) = 0;
8423 virtual void Aborted() = 0;
8424 virtual void Result( AssertionResult const& result ) = 0;
8425 };
8426
8427 class LegacyReporterAdapter : public SharedImpl<IStreamingReporter>
8428 {
8429 public:
8430 LegacyReporterAdapter( Ptr<IReporter> const& legacyReporter );
8431 virtual ~LegacyReporterAdapter();
8432
8433 virtual ReporterPreferences getPreferences() const;
8434 virtual void noMatchingTestCases( std::string const& );
8435 virtual void testRunStarting( TestRunInfo const& );
8436 virtual void testGroupStarting( GroupInfo const& groupInfo );
8437 virtual void testCaseStarting( TestCaseInfo const& testInfo );
8438 virtual void sectionStarting( SectionInfo const& sectionInfo );
8439 virtual void assertionStarting( AssertionInfo const& );
8440 virtual bool assertionEnded( AssertionStats const& assertionStats );
8441 virtual void sectionEnded( SectionStats const& sectionStats );
8442 virtual void testCaseEnded( TestCaseStats const& testCaseStats );
8443 virtual void testGroupEnded( TestGroupStats const& testGroupStats );
8444 virtual void testRunEnded( TestRunStats const& testRunStats );
8445 virtual void skipTest( TestCaseInfo const& );
8446
8447 private:
8448 Ptr<IReporter> m_legacyReporter;
8449 };
8450 }
8451
8452 namespace Catch
8453 {
8454 LegacyReporterAdapter::LegacyReporterAdapter( Ptr<IReporter> const& legacyReporter )
8455 : m_legacyReporter( legacyReporter )
8456 {}
8457 LegacyReporterAdapter::~LegacyReporterAdapter() {}
8458
8459 ReporterPreferences LegacyReporterAdapter::getPreferences() const {
8460 ReporterPreferences prefs;
8461 prefs.shouldRedirectStdOut = m_legacyReporter->shouldRedirectStdout();
8462 return prefs;
8463 }
8464
8465 void LegacyReporterAdapter::noMatchingTestCases( std::string const& ) {}
8466 void LegacyReporterAdapter::testRunStarting( TestRunInfo const& ) {
8467 m_legacyReporter->StartTesting();
8468 }
8469 void LegacyReporterAdapter::testGroupStarting( GroupInfo const& groupInfo ) {
8470 m_legacyReporter->StartGroup( groupInfo.name );
8471 }
8472 void LegacyReporterAdapter::testCaseStarting( TestCaseInfo const& testInfo ) {
8473 m_legacyReporter->StartTestCase( testInfo );
8474 }
8475 void LegacyReporterAdapter::sectionStarting( SectionInfo const& sectionInfo ) {
8476 m_legacyReporter->StartSection( sectionInfo.name, sectionInfo.description );
8477 }
8478 void LegacyReporterAdapter::assertionStarting( AssertionInfo const& ) {
8479 // Not on legacy interface
8480 }
8481
8482 bool LegacyReporterAdapter::assertionEnded( AssertionStats const& assertionStats ) {
8483 if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) {
8484 for( std::vector<MessageInfo>::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end();
8485 it != itEnd;
8486 ++it ) {
8487 if( it->type == ResultWas::Info ) {
8488 ResultBuilder rb( it->macroName.c_str(), it->lineInfo, "", ResultDisposition::Normal );
8489 rb << it->message;
8490 rb.setResultType( ResultWas::Info );
8491 AssertionResult result = rb.build();
8492 m_legacyReporter->Result( result );
8493 }
8494 }
8495 }
8496 m_legacyReporter->Result( assertionStats.assertionResult );
8497 return true;
8498 }
8499 void LegacyReporterAdapter::sectionEnded( SectionStats const& sectionStats ) {
8500 if( sectionStats.missingAssertions )
8501 m_legacyReporter->NoAssertionsInSection( sectionStats.sectionInfo.name );
8502 m_legacyReporter->EndSection( sectionStats.sectionInfo.name, sectionStats.assertions );
8503 }
8504 void LegacyReporterAdapter::testCaseEnded( TestCaseStats const& testCaseStats ) {
8505 m_legacyReporter->EndTestCase
8506 ( testCaseStats.testInfo,
8507 testCaseStats.totals,
8508 testCaseStats.stdOut,
8509 testCaseStats.stdErr );
8510 }
8511 void LegacyReporterAdapter::testGroupEnded( TestGroupStats const& testGroupStats ) {
8512 if( testGroupStats.aborting )
8513 m_legacyReporter->Aborted();
8514 m_legacyReporter->EndGroup( testGroupStats.groupInfo.name, testGroupStats.totals );
8515 }
8516 void LegacyReporterAdapter::testRunEnded( TestRunStats const& testRunStats ) {
8517 m_legacyReporter->EndTesting( testRunStats.totals );
8518 }
8519 void LegacyReporterAdapter::skipTest( TestCaseInfo const& ) {
8520 }
8521 }
8522
8523 // #included from: catch_timer.hpp
8524
8525 #ifdef __clang__
8526 #pragma clang diagnostic push
8527 #pragma clang diagnostic ignored "-Wc++11-long-long"
8528 #endif
8529
8530 #ifdef CATCH_PLATFORM_WINDOWS
8531
8532 #else
8533
8534 #include <sys/time.h>
8535
8536 #endif
8537
8538 namespace Catch {
8539
8540 namespace {
8541 #ifdef CATCH_PLATFORM_WINDOWS
8542 UInt64 getCurrentTicks() {
8543 static UInt64 hz=0, hzo=0;
8544 if (!hz) {
8545 QueryPerformanceFrequency( reinterpret_cast<LARGE_INTEGER*>( &hz ) );
8546 QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER*>( &hzo ) );
8547 }
8548 UInt64 t;
8549 QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER*>( &t ) );
8550 return ((t-hzo)*1000000)/hz;
8551 }
8552 #else
8553 UInt64 getCurrentTicks() {
8554 timeval t;
8555 gettimeofday(&t,CATCH_NULL);
8556 return static_cast<UInt64>( t.tv_sec ) * 1000000ull + static_cast<UInt64>( t.tv_usec );
8557 }
8558 #endif
8559 }
8560
8561 void Timer::start() {
8562 m_ticks = getCurrentTicks();
8563 }
8564 unsigned int Timer::getElapsedMicroseconds() const {
8565 return static_cast<unsigned int>(getCurrentTicks() - m_ticks);
8566 }
8567 unsigned int Timer::getElapsedMilliseconds() const {
8568 return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
8569 }
8570 double Timer::getElapsedSeconds() const {
8571 return getElapsedMicroseconds()/1000000.0;
8572 }
8573
8574 } // namespace Catch
8575
8576 #ifdef __clang__
8577 #pragma clang diagnostic pop
8578 #endif
8579 // #included from: catch_common.hpp
8580 #define TWOBLUECUBES_CATCH_COMMON_HPP_INCLUDED
8581
8582 #include <cstring>
8583 #include <cctype>
8584
8585 namespace Catch {
8586
8587 bool startsWith( std::string const& s, std::string const& prefix ) {
8588 return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
8589 }
8590 bool startsWith( std::string const& s, char prefix ) {
8591 return !s.empty() && s[0] == prefix;
8592 }
8593 bool endsWith( std::string const& s, std::string const& suffix ) {
8594 return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
8595 }
8596 bool endsWith( std::string const& s, char suffix ) {
8597 return !s.empty() && s[s.size()-1] == suffix;
8598 }
8599 bool contains( std::string const& s, std::string const& infix ) {
8600 return s.find( infix ) != std::string::npos;
8601 }
8602 char toLowerCh(char c) {
8603 return static_cast<char>( std::tolower( c ) );
8604 }
8605 void toLowerInPlace( std::string& s ) {
8606 std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
8607 }
8608 std::string toLower( std::string const& s ) {
8609 std::string lc = s;
8610 toLowerInPlace( lc );
8611 return lc;
8612 }
8613 std::string trim( std::string const& str ) {
8614 static char const* whitespaceChars = "\n\r\t ";
8615 std::string::size_type start = str.find_first_not_of( whitespaceChars );
8616 std::string::size_type end = str.find_last_not_of( whitespaceChars );
8617
8618 return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
8619 }
8620
8621 bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
8622 bool replaced = false;
8623 std::size_t i = str.find( replaceThis );
8624 while( i != std::string::npos ) {
8625 replaced = true;
8626 str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
8627 if( i < str.size()-withThis.size() )
8628 i = str.find( replaceThis, i+withThis.size() );
8629 else
8630 i = std::string::npos;
8631 }
8632 return replaced;
8633 }
8634
8635 pluralise::pluralise( std::size_t count, std::string const& label )
8636 : m_count( count ),
8637 m_label( label )
8638 {}
8639
8640 std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
8641 os << pluraliser.m_count << ' ' << pluraliser.m_label;
8642 if( pluraliser.m_count != 1 )
8643 os << 's';
8644 return os;
8645 }
8646
8647 SourceLineInfo::SourceLineInfo() : file(""), line( 0 ){}
8648 SourceLineInfo::SourceLineInfo( char const* _file, std::size_t _line )
8649 : file( _file ),
8650 line( _line )
8651 {}
8652 bool SourceLineInfo::empty() const {
8653 return file[0] == '\0';
8654 }
8655 bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const {
8656 return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
8657 }
8658 bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const {
8659 return line < other.line || ( line == other.line && (std::strcmp(file, other.file) < 0));
8660 }
8661
8662 void seedRng( IConfig const& config ) {
8663 if( config.rngSeed() != 0 )
8664 std::srand( config.rngSeed() );
8665 }
8666 unsigned int rngSeed() {
8667 return getCurrentContext().getConfig()->rngSeed();
8668 }
8669
8670 std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
8671 #ifndef __GNUG__
8672 os << info.file << '(' << info.line << ')';
8673 #else
8674 os << info.file << ':' << info.line;
8675 #endif
8676 return os;
8677 }
8678
8679 void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ) {
8680 std::ostringstream oss;
8681 oss << locationInfo << ": Internal Catch error: '" << message << '\'';
8682 if( alwaysTrue() )
8683 throw std::logic_error( oss.str() );
8684 }
8685 }
8686
8687 // #included from: catch_section.hpp
8688 #define TWOBLUECUBES_CATCH_SECTION_HPP_INCLUDED
8689
8690 namespace Catch {
8691
8692 SectionInfo::SectionInfo
8693 ( SourceLineInfo const& _lineInfo,
8694 std::string const& _name,
8695 std::string const& _description )
8696 : name( _name ),
8697 description( _description ),
8698 lineInfo( _lineInfo )
8699 {}
8700
8701 Section::Section( SectionInfo const& info )
8702 : m_info( info ),
8703 m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
8704 {
8705 m_timer.start();
8706 }
8707
8708 #if defined(_MSC_VER)
8709 #pragma warning(push)
8710 #pragma warning(disable:4996) // std::uncaught_exception is deprecated in C++17
8711 #endif
8712 Section::~Section() {
8713 if( m_sectionIncluded ) {
8714 SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() );
8715 if( std::uncaught_exception() )
8716 getResultCapture().sectionEndedEarly( endInfo );
8717 else
8718 getResultCapture().sectionEnded( endInfo );
8719 }
8720 }
8721 #if defined(_MSC_VER)
8722 #pragma warning(pop)
8723 #endif
8724
8725 // This indicates whether the section should be executed or not
8726 Section::operator bool() const {
8727 return m_sectionIncluded;
8728 }
8729
8730 } // end namespace Catch
8731
8732 // #included from: catch_debugger.hpp
8733 #define TWOBLUECUBES_CATCH_DEBUGGER_HPP_INCLUDED
8734
8735 #ifdef CATCH_PLATFORM_MAC
8736
8737 #include <assert.h>
8738 #include <stdbool.h>
8739 #include <sys/types.h>
8740 #include <unistd.h>
8741 #include <sys/sysctl.h>
8742
8743 namespace Catch{
8744
8745 // The following function is taken directly from the following technical note:
8746 // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
8747
8748 // Returns true if the current process is being debugged (either
8749 // running under the debugger or has a debugger attached post facto).
8750 bool isDebuggerActive(){
8751
8752 int mib[4];
8753 struct kinfo_proc info;
8754 size_t size;
8755
8756 // Initialize the flags so that, if sysctl fails for some bizarre
8757 // reason, we get a predictable result.
8758
8759 info.kp_proc.p_flag = 0;
8760
8761 // Initialize mib, which tells sysctl the info we want, in this case
8762 // we're looking for information about a specific process ID.
8763
8764 mib[0] = CTL_KERN;
8765 mib[1] = KERN_PROC;
8766 mib[2] = KERN_PROC_PID;
8767 mib[3] = getpid();
8768
8769 // Call sysctl.
8770
8771 size = sizeof(info);
8772 if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, CATCH_NULL, 0) != 0 ) {
8773 Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
8774 return false;
8775 }
8776
8777 // We're being debugged if the P_TRACED flag is set.
8778
8779 return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
8780 }
8781 } // namespace Catch
8782
8783 #elif defined(CATCH_PLATFORM_LINUX)
8784 #include <fstream>
8785 #include <string>
8786
8787 namespace Catch{
8788 // The standard POSIX way of detecting a debugger is to attempt to
8789 // ptrace() the process, but this needs to be done from a child and not
8790 // this process itself to still allow attaching to this process later
8791 // if wanted, so is rather heavy. Under Linux we have the PID of the
8792 // "debugger" (which doesn't need to be gdb, of course, it could also
8793 // be strace, for example) in /proc/$PID/status, so just get it from
8794 // there instead.
8795 bool isDebuggerActive(){
8796 // Libstdc++ has a bug, where std::ifstream sets errno to 0
8797 // This way our users can properly assert over errno values
8798 ErrnoGuard guard;
8799 std::ifstream in("/proc/self/status");
8800 for( std::string line; std::getline(in, line); ) {
8801 static const int PREFIX_LEN = 11;
8802 if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
8803 // We're traced if the PID is not 0 and no other PID starts
8804 // with 0 digit, so it's enough to check for just a single
8805 // character.
8806 return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
8807 }
8808 }
8809
8810 return false;
8811 }
8812 } // namespace Catch
8813 #elif defined(_MSC_VER)
8814 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
8815 namespace Catch {
8816 bool isDebuggerActive() {
8817 return IsDebuggerPresent() != 0;
8818 }
8819 }
8820 #elif defined(__MINGW32__)
8821 extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
8822 namespace Catch {
8823 bool isDebuggerActive() {
8824 return IsDebuggerPresent() != 0;
8825 }
8826 }
8827 #else
8828 namespace Catch {
8829 inline bool isDebuggerActive() { return false; }
8830 }
8831 #endif // Platform
8832
8833 #ifdef CATCH_PLATFORM_WINDOWS
8834
8835 namespace Catch {
8836 void writeToDebugConsole( std::string const& text ) {
8837 ::OutputDebugStringA( text.c_str() );
8838 }
8839 }
8840 #else
8841 namespace Catch {
8842 void writeToDebugConsole( std::string const& text ) {
8843 // !TBD: Need a version for Mac/ XCode and other IDEs
8844 Catch::cout() << text;
8845 }
8846 }
8847 #endif // Platform
8848
8849 // #included from: catch_tostring.hpp
8850 #define TWOBLUECUBES_CATCH_TOSTRING_HPP_INCLUDED
8851
8852 namespace Catch {
8853
8854 namespace Detail {
8855
8856 const std::string unprintableString = "{?}";
8857
8858 namespace {
8859 const int hexThreshold = 255;
8860
8861 struct Endianness {
8862 enum Arch { Big, Little };
8863
8864 static Arch which() {
8865 union _{
8866 int asInt;
8867 char asChar[sizeof (int)];
8868 } u;
8869
8870 u.asInt = 1;
8871 return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
8872 }
8873 };
8874 }
8875
8876 std::string rawMemoryToString( const void *object, std::size_t size )
8877 {
8878 // Reverse order for little endian architectures
8879 int i = 0, end = static_cast<int>( size ), inc = 1;
8880 if( Endianness::which() == Endianness::Little ) {
8881 i = end-1;
8882 end = inc = -1;
8883 }
8884
8885 unsigned char const *bytes = static_cast<unsigned char const *>(object);
8886 std::ostringstream os;
8887 os << "0x" << std::setfill('0') << std::hex;
8888 for( ; i != end; i += inc )
8889 os << std::setw(2) << static_cast<unsigned>(bytes[i]);
8890 return os.str();
8891 }
8892 }
8893
8894 std::string toString( std::string const& value ) {
8895 std::string s = value;
8896 if( getCurrentContext().getConfig()->showInvisibles() ) {
8897 for(size_t i = 0; i < s.size(); ++i ) {
8898 std::string subs;
8899 switch( s[i] ) {
8900 case '\n': subs = "\\n"; break;
8901 case '\t': subs = "\\t"; break;
8902 default: break;
8903 }
8904 if( !subs.empty() ) {
8905 s = s.substr( 0, i ) + subs + s.substr( i+1 );
8906 ++i;
8907 }
8908 }
8909 }
8910 return '"' + s + '"';
8911 }
8912 std::string toString( std::wstring const& value ) {
8913
8914 std::string s;
8915 s.reserve( value.size() );
8916 for(size_t i = 0; i < value.size(); ++i )
8917 s += value[i] <= 0xff ? static_cast<char>( value[i] ) : '?';
8918 return Catch::toString( s );
8919 }
8920
8921 std::string toString( const char* const value ) {
8922 return value ? Catch::toString( std::string( value ) ) : std::string( "{null string}" );
8923 }
8924
8925 std::string toString( char* const value ) {
8926 return Catch::toString( static_cast<const char*>( value ) );
8927 }
8928
8929 std::string toString( const wchar_t* const value )
8930 {
8931 return value ? Catch::toString( std::wstring(value) ) : std::string( "{null string}" );
8932 }
8933
8934 std::string toString( wchar_t* const value )
8935 {
8936 return Catch::toString( static_cast<const wchar_t*>( value ) );
8937 }
8938
8939 std::string toString( int value ) {
8940 std::ostringstream oss;
8941 oss << value;
8942 if( value > Detail::hexThreshold )
8943 oss << " (0x" << std::hex << value << ')';
8944 return oss.str();
8945 }
8946
8947 std::string toString( unsigned long value ) {
8948 std::ostringstream oss;
8949 oss << value;
8950 if( value > Detail::hexThreshold )
8951 oss << " (0x" << std::hex << value << ')';
8952 return oss.str();
8953 }
8954
8955 std::string toString( unsigned int value ) {
8956 return Catch::toString( static_cast<unsigned long>( value ) );
8957 }
8958
8959 template<typename T>
8960 std::string fpToString( T value, int precision ) {
8961 std::ostringstream oss;
8962 oss << std::setprecision( precision )
8963 << std::fixed
8964 << value;
8965 std::string d = oss.str();
8966 std::size_t i = d.find_last_not_of( '0' );
8967 if( i != std::string::npos && i != d.size()-1 ) {
8968 if( d[i] == '.' )
8969 i++;
8970 d = d.substr( 0, i+1 );
8971 }
8972 return d;
8973 }
8974
8975 std::string toString( const double value ) {
8976 return fpToString( value, 10 );
8977 }
8978 std::string toString( const float value ) {
8979 return fpToString( value, 5 ) + 'f';
8980 }
8981
8982 std::string toString( bool value ) {
8983 return value ? "true" : "false";
8984 }
8985
8986 std::string toString( char value ) {
8987 if ( value == '\r' )
8988 return "'\\r'";
8989 if ( value == '\f' )
8990 return "'\\f'";
8991 if ( value == '\n' )
8992 return "'\\n'";
8993 if ( value == '\t' )
8994 return "'\\t'";
8995 if ( '\0' <= value && value < ' ' )
8996 return toString( static_cast<unsigned int>( value ) );
8997 char chstr[] = "' '";
8998 chstr[1] = value;
8999 return chstr;
9000 }
9001
9002 std::string toString( signed char value ) {
9003 return toString( static_cast<char>( value ) );
9004 }
9005
9006 std::string toString( unsigned char value ) {
9007 return toString( static_cast<char>( value ) );
9008 }
9009
9010 #ifdef CATCH_CONFIG_CPP11_LONG_LONG
9011 std::string toString( long long value ) {
9012 std::ostringstream oss;
9013 oss << value;
9014 if( value > Detail::hexThreshold )
9015 oss << " (0x" << std::hex << value << ')';
9016 return oss.str();
9017 }
9018 std::string toString( unsigned long long value ) {
9019 std::ostringstream oss;
9020 oss << value;
9021 if( value > Detail::hexThreshold )
9022 oss << " (0x" << std::hex << value << ')';
9023 return oss.str();
9024 }
9025 #endif
9026
9027 #ifdef CATCH_CONFIG_CPP11_NULLPTR
9028 std::string toString( std::nullptr_t ) {
9029 return "nullptr";
9030 }
9031 #endif
9032
9033 #ifdef __OBJC__
9034 std::string toString( NSString const * const& nsstring ) {
9035 if( !nsstring )
9036 return "nil";
9037 return "@" + toString([nsstring UTF8String]);
9038 }
9039 std::string toString( NSString * CATCH_ARC_STRONG & nsstring ) {
9040 if( !nsstring )
9041 return "nil";
9042 return "@" + toString([nsstring UTF8String]);
9043 }
9044 std::string toString( NSObject* const& nsObject ) {
9045 return toString( [nsObject description] );
9046 }
9047 #endif
9048
9049 } // end namespace Catch
9050
9051 // #included from: catch_result_builder.hpp
9052 #define TWOBLUECUBES_CATCH_RESULT_BUILDER_HPP_INCLUDED
9053
9054 namespace Catch {
9055
9056 ResultBuilder::ResultBuilder( char const* macroName,
9057 SourceLineInfo const& lineInfo,
9058 char const* capturedExpression,
9059 ResultDisposition::Flags resultDisposition,
9060 char const* secondArg )
9061 : m_assertionInfo( macroName, lineInfo, capturedExpression, resultDisposition, secondArg ),
9062 m_shouldDebugBreak( false ),
9063 m_shouldThrow( false ),
9064 m_guardException( false )
9065 {
9066 m_stream().oss.str("");
9067 }
9068
9069 ResultBuilder::~ResultBuilder() {
9070 #if defined(CATCH_CONFIG_FAST_COMPILE)
9071 if ( m_guardException ) {
9072 m_stream().oss << "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
9073 captureResult( ResultWas::ThrewException );
9074 getCurrentContext().getResultCapture()->exceptionEarlyReported();
9075 }
9076 #endif
9077 }
9078
9079 ResultBuilder& ResultBuilder::setResultType( ResultWas::OfType result ) {
9080 m_data.resultType = result;
9081 return *this;
9082 }
9083 ResultBuilder& ResultBuilder::setResultType( bool result ) {
9084 m_data.resultType = result ? ResultWas::Ok : ResultWas::ExpressionFailed;
9085 return *this;
9086 }
9087
9088 void ResultBuilder::endExpression( DecomposedExpression const& expr ) {
9089 AssertionResult result = build( expr );
9090 handleResult( result );
9091 }
9092
9093 void ResultBuilder::useActiveException( ResultDisposition::Flags resultDisposition ) {
9094 m_assertionInfo.resultDisposition = resultDisposition;
9095 m_stream().oss << Catch::translateActiveException();
9096 captureResult( ResultWas::ThrewException );
9097 }
9098
9099 void ResultBuilder::captureResult( ResultWas::OfType resultType ) {
9100 setResultType( resultType );
9101 captureExpression();
9102 }
9103
9104 void ResultBuilder::captureExpectedException( std::string const& expectedMessage ) {
9105 if( expectedMessage.empty() )
9106 captureExpectedException( Matchers::Impl::MatchAllOf<std::string>() );
9107 else
9108 captureExpectedException( Matchers::Equals( expectedMessage ) );
9109 }
9110
9111 void ResultBuilder::captureExpectedException( Matchers::Impl::MatcherBase<std::string> const& matcher ) {
9112
9113 assert( !isFalseTest( m_assertionInfo.resultDisposition ) );
9114 AssertionResultData data = m_data;
9115 data.resultType = ResultWas::Ok;
9116 data.reconstructedExpression = capturedExpressionWithSecondArgument(m_assertionInfo.capturedExpression, m_assertionInfo.secondArg);
9117
9118 std::string actualMessage = Catch::translateActiveException();
9119 if( !matcher.match( actualMessage ) ) {
9120 data.resultType = ResultWas::ExpressionFailed;
9121 data.reconstructedExpression = actualMessage;
9122 }
9123 AssertionResult result( m_assertionInfo, data );
9124 handleResult( result );
9125 }
9126
9127 void ResultBuilder::captureExpression() {
9128 AssertionResult result = build();
9129 handleResult( result );
9130 }
9131
9132 void ResultBuilder::handleResult( AssertionResult const& result )
9133 {
9134 getResultCapture().assertionEnded( result );
9135
9136 if( !result.isOk() ) {
9137 if( getCurrentContext().getConfig()->shouldDebugBreak() )
9138 m_shouldDebugBreak = true;
9139 if( getCurrentContext().getRunner()->aborting() || (m_assertionInfo.resultDisposition & ResultDisposition::Normal) )
9140 m_shouldThrow = true;
9141 }
9142 }
9143
9144 void ResultBuilder::react() {
9145 #if defined(CATCH_CONFIG_FAST_COMPILE)
9146 if (m_shouldDebugBreak) {
9147 ///////////////////////////////////////////////////////////////////
9148 // To inspect the state during test, you need to go one level up the callstack
9149 // To go back to the test and change execution, jump over the throw statement
9150 ///////////////////////////////////////////////////////////////////
9151 CATCH_BREAK_INTO_DEBUGGER();
9152 }
9153 #endif
9154 if( m_shouldThrow )
9155 throw Catch::TestFailureException();
9156 }
9157
9158 bool ResultBuilder::shouldDebugBreak() const { return m_shouldDebugBreak; }
9159 bool ResultBuilder::allowThrows() const { return getCurrentContext().getConfig()->allowThrows(); }
9160
9161 AssertionResult ResultBuilder::build() const
9162 {
9163 return build( *this );
9164 }
9165
9166 // CAVEAT: The returned AssertionResult stores a pointer to the argument expr,
9167 // a temporary DecomposedExpression, which in turn holds references to
9168 // operands, possibly temporary as well.
9169 // It should immediately be passed to handleResult; if the expression
9170 // needs to be reported, its string expansion must be composed before
9171 // the temporaries are destroyed.
9172 AssertionResult ResultBuilder::build( DecomposedExpression const& expr ) const
9173 {
9174 assert( m_data.resultType != ResultWas::Unknown );
9175 AssertionResultData data = m_data;
9176
9177 // Flip bool results if FalseTest flag is set
9178 if( isFalseTest( m_assertionInfo.resultDisposition ) ) {
9179 data.negate( expr.isBinaryExpression() );
9180 }
9181
9182 data.message = m_stream().oss.str();
9183 data.decomposedExpression = &expr; // for lazy reconstruction
9184 return AssertionResult( m_assertionInfo, data );
9185 }
9186
9187 void ResultBuilder::reconstructExpression( std::string& dest ) const {
9188 dest = capturedExpressionWithSecondArgument(m_assertionInfo.capturedExpression, m_assertionInfo.secondArg);
9189 }
9190
9191 void ResultBuilder::setExceptionGuard() {
9192 m_guardException = true;
9193 }
9194 void ResultBuilder::unsetExceptionGuard() {
9195 m_guardException = false;
9196 }
9197
9198 } // end namespace Catch
9199
9200 // #included from: catch_tag_alias_registry.hpp
9201 #define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED
9202
9203 namespace Catch {
9204
9205 TagAliasRegistry::~TagAliasRegistry() {}
9206
9207 Option<TagAlias> TagAliasRegistry::find( std::string const& alias ) const {
9208 std::map<std::string, TagAlias>::const_iterator it = m_registry.find( alias );
9209 if( it != m_registry.end() )
9210 return it->second;
9211 else
9212 return Option<TagAlias>();
9213 }
9214
9215 std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
9216 std::string expandedTestSpec = unexpandedTestSpec;
9217 for( std::map<std::string, TagAlias>::const_iterator it = m_registry.begin(), itEnd = m_registry.end();
9218 it != itEnd;
9219 ++it ) {
9220 std::size_t pos = expandedTestSpec.find( it->first );
9221 if( pos != std::string::npos ) {
9222 expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
9223 it->second.tag +
9224 expandedTestSpec.substr( pos + it->first.size() );
9225 }
9226 }
9227 return expandedTestSpec;
9228 }
9229
9230 void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
9231
9232 if( !startsWith( alias, "[@" ) || !endsWith( alias, ']' ) ) {
9233 std::ostringstream oss;
9234 oss << Colour( Colour::Red )
9235 << "error: tag alias, \"" << alias << "\" is not of the form [@alias name].\n"
9236 << Colour( Colour::FileName )
9237 << lineInfo << '\n';
9238 throw std::domain_error( oss.str().c_str() );
9239 }
9240 if( !m_registry.insert( std::make_pair( alias, TagAlias( tag, lineInfo ) ) ).second ) {
9241 std::ostringstream oss;
9242 oss << Colour( Colour::Red )
9243 << "error: tag alias, \"" << alias << "\" already registered.\n"
9244 << "\tFirst seen at "
9245 << Colour( Colour::Red ) << find(alias)->lineInfo << '\n'
9246 << Colour( Colour::Red ) << "\tRedefined at "
9247 << Colour( Colour::FileName) << lineInfo << '\n';
9248 throw std::domain_error( oss.str().c_str() );
9249 }
9250 }
9251
9252 ITagAliasRegistry::~ITagAliasRegistry() {}
9253
9254 ITagAliasRegistry const& ITagAliasRegistry::get() {
9255 return getRegistryHub().getTagAliasRegistry();
9256 }
9257
9258 RegistrarForTagAliases::RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) {
9259 getMutableRegistryHub().registerTagAlias( alias, tag, lineInfo );
9260 }
9261
9262 } // end namespace Catch
9263
9264 // #included from: catch_matchers_string.hpp
9265
9266 namespace Catch {
9267 namespace Matchers {
9268
9269 namespace StdString {
9270
9271 CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
9272 : m_caseSensitivity( caseSensitivity ),
9273 m_str( adjustString( str ) )
9274 {}
9275 std::string CasedString::adjustString( std::string const& str ) const {
9276 return m_caseSensitivity == CaseSensitive::No
9277 ? toLower( str )
9278 : str;
9279 }
9280 std::string CasedString::caseSensitivitySuffix() const {
9281 return m_caseSensitivity == CaseSensitive::No
9282 ? " (case insensitive)"
9283 : std::string();
9284 }
9285
9286 StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
9287 : m_comparator( comparator ),
9288 m_operation( operation ) {
9289 }
9290
9291 std::string StringMatcherBase::describe() const {
9292 std::string description;
9293 description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
9294 m_comparator.caseSensitivitySuffix().size());
9295 description += m_operation;
9296 description += ": \"";
9297 description += m_comparator.m_str;
9298 description += "\"";
9299 description += m_comparator.caseSensitivitySuffix();
9300 return description;
9301 }
9302
9303 EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
9304
9305 bool EqualsMatcher::match( std::string const& source ) const {
9306 return m_comparator.adjustString( source ) == m_comparator.m_str;
9307 }
9308
9309 ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
9310
9311 bool ContainsMatcher::match( std::string const& source ) const {
9312 return contains( m_comparator.adjustString( source ), m_comparator.m_str );
9313 }
9314
9315 StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
9316
9317 bool StartsWithMatcher::match( std::string const& source ) const {
9318 return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
9319 }
9320
9321 EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
9322
9323 bool EndsWithMatcher::match( std::string const& source ) const {
9324 return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
9325 }
9326
9327 } // namespace StdString
9328
9329 StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
9330 return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
9331 }
9332 StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
9333 return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
9334 }
9335 StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
9336 return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
9337 }
9338 StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
9339 return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
9340 }
9341
9342 } // namespace Matchers
9343 } // namespace Catch
9344 // #included from: ../reporters/catch_reporter_multi.hpp
9345 #define TWOBLUECUBES_CATCH_REPORTER_MULTI_HPP_INCLUDED
9346
9347 namespace Catch {
9348
9349 class MultipleReporters : public SharedImpl<IStreamingReporter> {
9350 typedef std::vector<Ptr<IStreamingReporter> > Reporters;
9351 Reporters m_reporters;
9352
9353 public:
9354 void add( Ptr<IStreamingReporter> const& reporter ) {
9355 m_reporters.push_back( reporter );
9356 }
9357
9358 public: // IStreamingReporter
9359
9360 virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE {
9361 return m_reporters[0]->getPreferences();
9362 }
9363
9364 virtual void noMatchingTestCases( std::string const& spec ) CATCH_OVERRIDE {
9365 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9366 it != itEnd;
9367 ++it )
9368 (*it)->noMatchingTestCases( spec );
9369 }
9370
9371 virtual void testRunStarting( TestRunInfo const& testRunInfo ) CATCH_OVERRIDE {
9372 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9373 it != itEnd;
9374 ++it )
9375 (*it)->testRunStarting( testRunInfo );
9376 }
9377
9378 virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE {
9379 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9380 it != itEnd;
9381 ++it )
9382 (*it)->testGroupStarting( groupInfo );
9383 }
9384
9385 virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE {
9386 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9387 it != itEnd;
9388 ++it )
9389 (*it)->testCaseStarting( testInfo );
9390 }
9391
9392 virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE {
9393 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9394 it != itEnd;
9395 ++it )
9396 (*it)->sectionStarting( sectionInfo );
9397 }
9398
9399 virtual void assertionStarting( AssertionInfo const& assertionInfo ) CATCH_OVERRIDE {
9400 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9401 it != itEnd;
9402 ++it )
9403 (*it)->assertionStarting( assertionInfo );
9404 }
9405
9406 // The return value indicates if the messages buffer should be cleared:
9407 virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE {
9408 bool clearBuffer = false;
9409 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9410 it != itEnd;
9411 ++it )
9412 clearBuffer |= (*it)->assertionEnded( assertionStats );
9413 return clearBuffer;
9414 }
9415
9416 virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE {
9417 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9418 it != itEnd;
9419 ++it )
9420 (*it)->sectionEnded( sectionStats );
9421 }
9422
9423 virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE {
9424 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9425 it != itEnd;
9426 ++it )
9427 (*it)->testCaseEnded( testCaseStats );
9428 }
9429
9430 virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE {
9431 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9432 it != itEnd;
9433 ++it )
9434 (*it)->testGroupEnded( testGroupStats );
9435 }
9436
9437 virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE {
9438 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9439 it != itEnd;
9440 ++it )
9441 (*it)->testRunEnded( testRunStats );
9442 }
9443
9444 virtual void skipTest( TestCaseInfo const& testInfo ) CATCH_OVERRIDE {
9445 for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
9446 it != itEnd;
9447 ++it )
9448 (*it)->skipTest( testInfo );
9449 }
9450
9451 virtual MultipleReporters* tryAsMulti() CATCH_OVERRIDE {
9452 return this;
9453 }
9454
9455 };
9456
9457 Ptr<IStreamingReporter> addReporter( Ptr<IStreamingReporter> const& existingReporter, Ptr<IStreamingReporter> const& additionalReporter ) {
9458 Ptr<IStreamingReporter> resultingReporter;
9459
9460 if( existingReporter ) {
9461 MultipleReporters* multi = existingReporter->tryAsMulti();
9462 if( !multi ) {
9463 multi = new MultipleReporters;
9464 resultingReporter = Ptr<IStreamingReporter>( multi );
9465 if( existingReporter )
9466 multi->add( existingReporter );
9467 }
9468 else
9469 resultingReporter = existingReporter;
9470 multi->add( additionalReporter );
9471 }
9472 else
9473 resultingReporter = additionalReporter;
9474
9475 return resultingReporter;
9476 }
9477
9478 } // end namespace Catch
9479
9480 // #included from: ../reporters/catch_reporter_xml.hpp
9481 #define TWOBLUECUBES_CATCH_REPORTER_XML_HPP_INCLUDED
9482
9483 // #included from: catch_reporter_bases.hpp
9484 #define TWOBLUECUBES_CATCH_REPORTER_BASES_HPP_INCLUDED
9485
9486 #include <cstring>
9487 #include <cfloat>
9488 #include <cstdio>
9489 #include <assert.h>
9490
9491 namespace Catch {
9492
9493 namespace {
9494 // Because formatting using c++ streams is stateful, drop down to C is required
9495 // Alternatively we could use stringstream, but its performance is... not good.
9496 std::string getFormattedDuration( double duration ) {
9497 // Max exponent + 1 is required to represent the whole part
9498 // + 1 for decimal point
9499 // + 3 for the 3 decimal places
9500 // + 1 for null terminator
9501 const size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
9502 char buffer[maxDoubleSize];
9503
9504 // Save previous errno, to prevent sprintf from overwriting it
9505 ErrnoGuard guard;
9506 #ifdef _MSC_VER
9507 sprintf_s(buffer, "%.3f", duration);
9508 #else
9509 sprintf(buffer, "%.3f", duration);
9510 #endif
9511 return std::string(buffer);
9512 }
9513 }
9514
9515 struct StreamingReporterBase : SharedImpl<IStreamingReporter> {
9516
9517 StreamingReporterBase( ReporterConfig const& _config )
9518 : m_config( _config.fullConfig() ),
9519 stream( _config.stream() )
9520 {
9521 m_reporterPrefs.shouldRedirectStdOut = false;
9522 }
9523
9524 virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE {
9525 return m_reporterPrefs;
9526 }
9527
9528 virtual ~StreamingReporterBase() CATCH_OVERRIDE;
9529
9530 virtual void noMatchingTestCases( std::string const& ) CATCH_OVERRIDE {}
9531
9532 virtual void testRunStarting( TestRunInfo const& _testRunInfo ) CATCH_OVERRIDE {
9533 currentTestRunInfo = _testRunInfo;
9534 }
9535 virtual void testGroupStarting( GroupInfo const& _groupInfo ) CATCH_OVERRIDE {
9536 currentGroupInfo = _groupInfo;
9537 }
9538
9539 virtual void testCaseStarting( TestCaseInfo const& _testInfo ) CATCH_OVERRIDE {
9540 currentTestCaseInfo = _testInfo;
9541 }
9542 virtual void sectionStarting( SectionInfo const& _sectionInfo ) CATCH_OVERRIDE {
9543 m_sectionStack.push_back( _sectionInfo );
9544 }
9545
9546 virtual void sectionEnded( SectionStats const& /* _sectionStats */ ) CATCH_OVERRIDE {
9547 m_sectionStack.pop_back();
9548 }
9549 virtual void testCaseEnded( TestCaseStats const& /* _testCaseStats */ ) CATCH_OVERRIDE {
9550 currentTestCaseInfo.reset();
9551 }
9552 virtual void testGroupEnded( TestGroupStats const& /* _testGroupStats */ ) CATCH_OVERRIDE {
9553 currentGroupInfo.reset();
9554 }
9555 virtual void testRunEnded( TestRunStats const& /* _testRunStats */ ) CATCH_OVERRIDE {
9556 currentTestCaseInfo.reset();
9557 currentGroupInfo.reset();
9558 currentTestRunInfo.reset();
9559 }
9560
9561 virtual void skipTest( TestCaseInfo const& ) CATCH_OVERRIDE {
9562 // Don't do anything with this by default.
9563 // It can optionally be overridden in the derived class.
9564 }
9565
9566 Ptr<IConfig const> m_config;
9567 std::ostream& stream;
9568
9569 LazyStat<TestRunInfo> currentTestRunInfo;
9570 LazyStat<GroupInfo> currentGroupInfo;
9571 LazyStat<TestCaseInfo> currentTestCaseInfo;
9572
9573 std::vector<SectionInfo> m_sectionStack;
9574 ReporterPreferences m_reporterPrefs;
9575 };
9576
9577 struct CumulativeReporterBase : SharedImpl<IStreamingReporter> {
9578 template<typename T, typename ChildNodeT>
9579 struct Node : SharedImpl<> {
9580 explicit Node( T const& _value ) : value( _value ) {}
9581 virtual ~Node() {}
9582
9583 typedef std::vector<Ptr<ChildNodeT> > ChildNodes;
9584 T value;
9585 ChildNodes children;
9586 };
9587 struct SectionNode : SharedImpl<> {
9588 explicit SectionNode( SectionStats const& _stats ) : stats( _stats ) {}
9589 virtual ~SectionNode();
9590
9591 bool operator == ( SectionNode const& other ) const {
9592 return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
9593 }
9594 bool operator == ( Ptr<SectionNode> const& other ) const {
9595 return operator==( *other );
9596 }
9597
9598 SectionStats stats;
9599 typedef std::vector<Ptr<SectionNode> > ChildSections;
9600 typedef std::vector<AssertionStats> Assertions;
9601 ChildSections childSections;
9602 Assertions assertions;
9603 std::string stdOut;
9604 std::string stdErr;
9605 };
9606
9607 struct BySectionInfo {
9608 BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
9609 BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
9610 bool operator() ( Ptr<SectionNode> const& node ) const {
9611 return node->stats.sectionInfo.lineInfo == m_other.lineInfo;
9612 }
9613 private:
9614 void operator=( BySectionInfo const& );
9615 SectionInfo const& m_other;
9616 };
9617
9618 typedef Node<TestCaseStats, SectionNode> TestCaseNode;
9619 typedef Node<TestGroupStats, TestCaseNode> TestGroupNode;
9620 typedef Node<TestRunStats, TestGroupNode> TestRunNode;
9621
9622 CumulativeReporterBase( ReporterConfig const& _config )
9623 : m_config( _config.fullConfig() ),
9624 stream( _config.stream() )
9625 {
9626 m_reporterPrefs.shouldRedirectStdOut = false;
9627 }
9628 ~CumulativeReporterBase();
9629
9630 virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE {
9631 return m_reporterPrefs;
9632 }
9633
9634 virtual void testRunStarting( TestRunInfo const& ) CATCH_OVERRIDE {}
9635 virtual void testGroupStarting( GroupInfo const& ) CATCH_OVERRIDE {}
9636
9637 virtual void testCaseStarting( TestCaseInfo const& ) CATCH_OVERRIDE {}
9638
9639 virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE {
9640 SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
9641 Ptr<SectionNode> node;
9642 if( m_sectionStack.empty() ) {
9643 if( !m_rootSection )
9644 m_rootSection = new SectionNode( incompleteStats );
9645 node = m_rootSection;
9646 }
9647 else {
9648 SectionNode& parentNode = *m_sectionStack.back();
9649 SectionNode::ChildSections::const_iterator it =
9650 std::find_if( parentNode.childSections.begin(),
9651 parentNode.childSections.end(),
9652 BySectionInfo( sectionInfo ) );
9653 if( it == parentNode.childSections.end() ) {
9654 node = new SectionNode( incompleteStats );
9655 parentNode.childSections.push_back( node );
9656 }
9657 else
9658 node = *it;
9659 }
9660 m_sectionStack.push_back( node );
9661 m_deepestSection = node;
9662 }
9663
9664 virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {}
9665
9666 virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE {
9667 assert( !m_sectionStack.empty() );
9668 SectionNode& sectionNode = *m_sectionStack.back();
9669 sectionNode.assertions.push_back( assertionStats );
9670 // AssertionResult holds a pointer to a temporary DecomposedExpression,
9671 // which getExpandedExpression() calls to build the expression string.
9672 // Our section stack copy of the assertionResult will likely outlive the
9673 // temporary, so it must be expanded or discarded now to avoid calling
9674 // a destroyed object later.
9675 prepareExpandedExpression( sectionNode.assertions.back().assertionResult );
9676 return true;
9677 }
9678 virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE {
9679 assert( !m_sectionStack.empty() );
9680 SectionNode& node = *m_sectionStack.back();
9681 node.stats = sectionStats;
9682 m_sectionStack.pop_back();
9683 }
9684 virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE {
9685 Ptr<TestCaseNode> node = new TestCaseNode( testCaseStats );
9686 assert( m_sectionStack.size() == 0 );
9687 node->children.push_back( m_rootSection );
9688 m_testCases.push_back( node );
9689 m_rootSection.reset();
9690
9691 assert( m_deepestSection );
9692 m_deepestSection->stdOut = testCaseStats.stdOut;
9693 m_deepestSection->stdErr = testCaseStats.stdErr;
9694 }
9695 virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE {
9696 Ptr<TestGroupNode> node = new TestGroupNode( testGroupStats );
9697 node->children.swap( m_testCases );
9698 m_testGroups.push_back( node );
9699 }
9700 virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE {
9701 Ptr<TestRunNode> node = new TestRunNode( testRunStats );
9702 node->children.swap( m_testGroups );
9703 m_testRuns.push_back( node );
9704 testRunEndedCumulative();
9705 }
9706 virtual void testRunEndedCumulative() = 0;
9707
9708 virtual void skipTest( TestCaseInfo const& ) CATCH_OVERRIDE {}
9709
9710 virtual void prepareExpandedExpression( AssertionResult& result ) const {
9711 if( result.isOk() )
9712 result.discardDecomposedExpression();
9713 else
9714 result.expandDecomposedExpression();
9715 }
9716
9717 Ptr<IConfig const> m_config;
9718 std::ostream& stream;
9719 std::vector<AssertionStats> m_assertions;
9720 std::vector<std::vector<Ptr<SectionNode> > > m_sections;
9721 std::vector<Ptr<TestCaseNode> > m_testCases;
9722 std::vector<Ptr<TestGroupNode> > m_testGroups;
9723
9724 std::vector<Ptr<TestRunNode> > m_testRuns;
9725
9726 Ptr<SectionNode> m_rootSection;
9727 Ptr<SectionNode> m_deepestSection;
9728 std::vector<Ptr<SectionNode> > m_sectionStack;
9729 ReporterPreferences m_reporterPrefs;
9730
9731 };
9732
9733 template<char C>
9734 char const* getLineOfChars() {
9735 static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
9736 if( !*line ) {
9737 std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
9738 line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
9739 }
9740 return line;
9741 }
9742
9743 struct TestEventListenerBase : StreamingReporterBase {
9744 TestEventListenerBase( ReporterConfig const& _config )
9745 : StreamingReporterBase( _config )
9746 {}
9747
9748 virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {}
9749 virtual bool assertionEnded( AssertionStats const& ) CATCH_OVERRIDE {
9750 return false;
9751 }
9752 };
9753
9754 } // end namespace Catch
9755
9756 // #included from: ../internal/catch_reporter_registrars.hpp
9757 #define TWOBLUECUBES_CATCH_REPORTER_REGISTRARS_HPP_INCLUDED
9758
9759 namespace Catch {
9760
9761 template<typename T>
9762 class LegacyReporterRegistrar {
9763
9764 class ReporterFactory : public IReporterFactory {
9765 virtual IStreamingReporter* create( ReporterConfig const& config ) const {
9766 return new LegacyReporterAdapter( new T( config ) );
9767 }
9768
9769 virtual std::string getDescription() const {
9770 return T::getDescription();
9771 }
9772 };
9773
9774 public:
9775
9776 LegacyReporterRegistrar( std::string const& name ) {
9777 getMutableRegistryHub().registerReporter( name, new ReporterFactory() );
9778 }
9779 };
9780
9781 template<typename T>
9782 class ReporterRegistrar {
9783
9784 class ReporterFactory : public SharedImpl<IReporterFactory> {
9785
9786 // *** Please Note ***:
9787 // - If you end up here looking at a compiler error because it's trying to register
9788 // your custom reporter class be aware that the native reporter interface has changed
9789 // to IStreamingReporter. The "legacy" interface, IReporter, is still supported via
9790 // an adapter. Just use REGISTER_LEGACY_REPORTER to take advantage of the adapter.
9791 // However please consider updating to the new interface as the old one is now
9792 // deprecated and will probably be removed quite soon!
9793 // Please contact me via github if you have any questions at all about this.
9794 // In fact, ideally, please contact me anyway to let me know you've hit this - as I have
9795 // no idea who is actually using custom reporters at all (possibly no-one!).
9796 // The new interface is designed to minimise exposure to interface changes in the future.
9797 virtual IStreamingReporter* create( ReporterConfig const& config ) const {
9798 return new T( config );
9799 }
9800
9801 virtual std::string getDescription() const {
9802 return T::getDescription();
9803 }
9804 };
9805
9806 public:
9807
9808 ReporterRegistrar( std::string const& name ) {
9809 getMutableRegistryHub().registerReporter( name, new ReporterFactory() );
9810 }
9811 };
9812
9813 template<typename T>
9814 class ListenerRegistrar {
9815
9816 class ListenerFactory : public SharedImpl<IReporterFactory> {
9817
9818 virtual IStreamingReporter* create( ReporterConfig const& config ) const {
9819 return new T( config );
9820 }
9821 virtual std::string getDescription() const {
9822 return std::string();
9823 }
9824 };
9825
9826 public:
9827
9828 ListenerRegistrar() {
9829 getMutableRegistryHub().registerListener( new ListenerFactory() );
9830 }
9831 };
9832 }
9833
9834 #define INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) \
9835 namespace{ Catch::LegacyReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); }
9836
9837 #define INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) \
9838 namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); }
9839
9840 // Deprecated - use the form without INTERNAL_
9841 #define INTERNAL_CATCH_REGISTER_LISTENER( listenerType ) \
9842 namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; }
9843
9844 #define CATCH_REGISTER_LISTENER( listenerType ) \
9845 namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; }
9846
9847 // #included from: ../internal/catch_xmlwriter.hpp
9848 #define TWOBLUECUBES_CATCH_XMLWRITER_HPP_INCLUDED
9849
9850 #include <sstream>
9851 #include <string>
9852 #include <vector>
9853 #include <iomanip>
9854
9855 namespace Catch {
9856
9857 class XmlEncode {
9858 public:
9859 enum ForWhat { ForTextNodes, ForAttributes };
9860
9861 XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes )
9862 : m_str( str ),
9863 m_forWhat( forWhat )
9864 {}
9865
9866 void encodeTo( std::ostream& os ) const {
9867
9868 // Apostrophe escaping not necessary if we always use " to write attributes
9869 // (see: http://www.w3.org/TR/xml/#syntax)
9870
9871 for( std::size_t i = 0; i < m_str.size(); ++ i ) {
9872 char c = m_str[i];
9873 switch( c ) {
9874 case '<': os << "&lt;"; break;
9875 case '&': os << "&amp;"; break;
9876
9877 case '>':
9878 // See: http://www.w3.org/TR/xml/#syntax
9879 if( i > 2 && m_str[i-1] == ']' && m_str[i-2] == ']' )
9880 os << "&gt;";
9881 else
9882 os << c;
9883 break;
9884
9885 case '\"':
9886 if( m_forWhat == ForAttributes )
9887 os << "&quot;";
9888 else
9889 os << c;
9890 break;
9891
9892 default:
9893 // Escape control chars - based on contribution by @espenalb in PR #465 and
9894 // by @mrpi PR #588
9895 if ( ( c >= 0 && c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) {
9896 // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
9897 os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
9898 << static_cast<int>( c );
9899 }
9900 else
9901 os << c;
9902 }
9903 }
9904 }
9905
9906 friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
9907 xmlEncode.encodeTo( os );
9908 return os;
9909 }
9910
9911 private:
9912 std::string m_str;
9913 ForWhat m_forWhat;
9914 };
9915
9916 class XmlWriter {
9917 public:
9918
9919 class ScopedElement {
9920 public:
9921 ScopedElement( XmlWriter* writer )
9922 : m_writer( writer )
9923 {}
9924
9925 ScopedElement( ScopedElement const& other )
9926 : m_writer( other.m_writer ){
9927 other.m_writer = CATCH_NULL;
9928 }
9929
9930 ~ScopedElement() {
9931 if( m_writer )
9932 m_writer->endElement();
9933 }
9934
9935 ScopedElement& writeText( std::string const& text, bool indent = true ) {
9936 m_writer->writeText( text, indent );
9937 return *this;
9938 }
9939
9940 template<typename T>
9941 ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
9942 m_writer->writeAttribute( name, attribute );
9943 return *this;
9944 }
9945
9946 private:
9947 mutable XmlWriter* m_writer;
9948 };
9949
9950 XmlWriter()
9951 : m_tagIsOpen( false ),
9952 m_needsNewline( false ),
9953 m_os( Catch::cout() )
9954 {
9955 writeDeclaration();
9956 }
9957
9958 XmlWriter( std::ostream& os )
9959 : m_tagIsOpen( false ),
9960 m_needsNewline( false ),
9961 m_os( os )
9962 {
9963 writeDeclaration();
9964 }
9965
9966 ~XmlWriter() {
9967 while( !m_tags.empty() )
9968 endElement();
9969 }
9970
9971 XmlWriter& startElement( std::string const& name ) {
9972 ensureTagClosed();
9973 newlineIfNecessary();
9974 m_os << m_indent << '<' << name;
9975 m_tags.push_back( name );
9976 m_indent += " ";
9977 m_tagIsOpen = true;
9978 return *this;
9979 }
9980
9981 ScopedElement scopedElement( std::string const& name ) {
9982 ScopedElement scoped( this );
9983 startElement( name );
9984 return scoped;
9985 }
9986
9987 XmlWriter& endElement() {
9988 newlineIfNecessary();
9989 m_indent = m_indent.substr( 0, m_indent.size()-2 );
9990 if( m_tagIsOpen ) {
9991 m_os << "/>";
9992 m_tagIsOpen = false;
9993 }
9994 else {
9995 m_os << m_indent << "</" << m_tags.back() << ">";
9996 }
9997 m_os << std::endl;
9998 m_tags.pop_back();
9999 return *this;
10000 }
10001
10002 XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ) {
10003 if( !name.empty() && !attribute.empty() )
10004 m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
10005 return *this;
10006 }
10007
10008 XmlWriter& writeAttribute( std::string const& name, bool attribute ) {
10009 m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
10010 return *this;
10011 }
10012
10013 template<typename T>
10014 XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
10015 std::ostringstream oss;
10016 oss << attribute;
10017 return writeAttribute( name, oss.str() );
10018 }
10019
10020 XmlWriter& writeText( std::string const& text, bool indent = true ) {
10021 if( !text.empty() ){
10022 bool tagWasOpen = m_tagIsOpen;
10023 ensureTagClosed();
10024 if( tagWasOpen && indent )
10025 m_os << m_indent;
10026 m_os << XmlEncode( text );
10027 m_needsNewline = true;
10028 }
10029 return *this;
10030 }
10031
10032 XmlWriter& writeComment( std::string const& text ) {
10033 ensureTagClosed();
10034 m_os << m_indent << "<!--" << text << "-->";
10035 m_needsNewline = true;
10036 return *this;
10037 }
10038
10039 void writeStylesheetRef( std::string const& url ) {
10040 m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
10041 }
10042
10043 XmlWriter& writeBlankLine() {
10044 ensureTagClosed();
10045 m_os << '\n';
10046 return *this;
10047 }
10048
10049 void ensureTagClosed() {
10050 if( m_tagIsOpen ) {
10051 m_os << ">" << std::endl;
10052 m_tagIsOpen = false;
10053 }
10054 }
10055
10056 private:
10057 XmlWriter( XmlWriter const& );
10058 void operator=( XmlWriter const& );
10059
10060 void writeDeclaration() {
10061 m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
10062 }
10063
10064 void newlineIfNecessary() {
10065 if( m_needsNewline ) {
10066 m_os << std::endl;
10067 m_needsNewline = false;
10068 }
10069 }
10070
10071 bool m_tagIsOpen;
10072 bool m_needsNewline;
10073 std::vector<std::string> m_tags;
10074 std::string m_indent;
10075 std::ostream& m_os;
10076 };
10077
10078 }
10079
10080 namespace Catch {
10081 class XmlReporter : public StreamingReporterBase {
10082 public:
10083 XmlReporter( ReporterConfig const& _config )
10084 : StreamingReporterBase( _config ),
10085 m_xml(_config.stream()),
10086 m_sectionDepth( 0 )
10087 {
10088 m_reporterPrefs.shouldRedirectStdOut = true;
10089 }
10090
10091 virtual ~XmlReporter() CATCH_OVERRIDE;
10092
10093 static std::string getDescription() {
10094 return "Reports test results as an XML document";
10095 }
10096
10097 virtual std::string getStylesheetRef() const {
10098 return std::string();
10099 }
10100
10101 void writeSourceInfo( SourceLineInfo const& sourceInfo ) {
10102 m_xml
10103 .writeAttribute( "filename", sourceInfo.file )
10104 .writeAttribute( "line", sourceInfo.line );
10105 }
10106
10107 public: // StreamingReporterBase
10108
10109 virtual void noMatchingTestCases( std::string const& s ) CATCH_OVERRIDE {
10110 StreamingReporterBase::noMatchingTestCases( s );
10111 }
10112
10113 virtual void testRunStarting( TestRunInfo const& testInfo ) CATCH_OVERRIDE {
10114 StreamingReporterBase::testRunStarting( testInfo );
10115 std::string stylesheetRef = getStylesheetRef();
10116 if( !stylesheetRef.empty() )
10117 m_xml.writeStylesheetRef( stylesheetRef );
10118 m_xml.startElement( "Catch" );
10119 if( !m_config->name().empty() )
10120 m_xml.writeAttribute( "name", m_config->name() );
10121 }
10122
10123 virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE {
10124 StreamingReporterBase::testGroupStarting( groupInfo );
10125 m_xml.startElement( "Group" )
10126 .writeAttribute( "name", groupInfo.name );
10127 }
10128
10129 virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE {
10130 StreamingReporterBase::testCaseStarting(testInfo);
10131 m_xml.startElement( "TestCase" )
10132 .writeAttribute( "name", trim( testInfo.name ) )
10133 .writeAttribute( "description", testInfo.description )
10134 .writeAttribute( "tags", testInfo.tagsAsString );
10135
10136 writeSourceInfo( testInfo.lineInfo );
10137
10138 if ( m_config->showDurations() == ShowDurations::Always )
10139 m_testCaseTimer.start();
10140 m_xml.ensureTagClosed();
10141 }
10142
10143 virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE {
10144 StreamingReporterBase::sectionStarting( sectionInfo );
10145 if( m_sectionDepth++ > 0 ) {
10146 m_xml.startElement( "Section" )
10147 .writeAttribute( "name", trim( sectionInfo.name ) )
10148 .writeAttribute( "description", sectionInfo.description );
10149 writeSourceInfo( sectionInfo.lineInfo );
10150 m_xml.ensureTagClosed();
10151 }
10152 }
10153
10154 virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE { }
10155
10156 virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE {
10157
10158 AssertionResult const& result = assertionStats.assertionResult;
10159
10160 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
10161
10162 if( includeResults ) {
10163 // Print any info messages in <Info> tags.
10164 for( std::vector<MessageInfo>::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end();
10165 it != itEnd;
10166 ++it ) {
10167 if( it->type == ResultWas::Info ) {
10168 m_xml.scopedElement( "Info" )
10169 .writeText( it->message );
10170 } else if ( it->type == ResultWas::Warning ) {
10171 m_xml.scopedElement( "Warning" )
10172 .writeText( it->message );
10173 }
10174 }
10175 }
10176
10177 // Drop out if result was successful but we're not printing them.
10178 if( !includeResults && result.getResultType() != ResultWas::Warning )
10179 return true;
10180
10181 // Print the expression if there is one.
10182 if( result.hasExpression() ) {
10183 m_xml.startElement( "Expression" )
10184 .writeAttribute( "success", result.succeeded() )
10185 .writeAttribute( "type", result.getTestMacroName() );
10186
10187 writeSourceInfo( result.getSourceInfo() );
10188
10189 m_xml.scopedElement( "Original" )
10190 .writeText( result.getExpression() );
10191 m_xml.scopedElement( "Expanded" )
10192 .writeText( result.getExpandedExpression() );
10193 }
10194
10195 // And... Print a result applicable to each result type.
10196 switch( result.getResultType() ) {
10197 case ResultWas::ThrewException:
10198 m_xml.startElement( "Exception" );
10199 writeSourceInfo( result.getSourceInfo() );
10200 m_xml.writeText( result.getMessage() );
10201 m_xml.endElement();
10202 break;
10203 case ResultWas::FatalErrorCondition:
10204 m_xml.startElement( "FatalErrorCondition" );
10205 writeSourceInfo( result.getSourceInfo() );
10206 m_xml.writeText( result.getMessage() );
10207 m_xml.endElement();
10208 break;
10209 case ResultWas::Info:
10210 m_xml.scopedElement( "Info" )
10211 .writeText( result.getMessage() );
10212 break;
10213 case ResultWas::Warning:
10214 // Warning will already have been written
10215 break;
10216 case ResultWas::ExplicitFailure:
10217 m_xml.startElement( "Failure" );
10218 writeSourceInfo( result.getSourceInfo() );
10219 m_xml.writeText( result.getMessage() );
10220 m_xml.endElement();
10221 break;
10222 default:
10223 break;
10224 }
10225
10226 if( result.hasExpression() )
10227 m_xml.endElement();
10228
10229 return true;
10230 }
10231
10232 virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE {
10233 StreamingReporterBase::sectionEnded( sectionStats );
10234 if( --m_sectionDepth > 0 ) {
10235 XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
10236 e.writeAttribute( "successes", sectionStats.assertions.passed );
10237 e.writeAttribute( "failures", sectionStats.assertions.failed );
10238 e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
10239
10240 if ( m_config->showDurations() == ShowDurations::Always )
10241 e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
10242
10243 m_xml.endElement();
10244 }
10245 }
10246
10247 virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE {
10248 StreamingReporterBase::testCaseEnded( testCaseStats );
10249 XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
10250 e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
10251
10252 if ( m_config->showDurations() == ShowDurations::Always )
10253 e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
10254
10255 if( !testCaseStats.stdOut.empty() )
10256 m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
10257 if( !testCaseStats.stdErr.empty() )
10258 m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
10259
10260 m_xml.endElement();
10261 }
10262
10263 virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE {
10264 StreamingReporterBase::testGroupEnded( testGroupStats );
10265 // TODO: Check testGroupStats.aborting and act accordingly.
10266 m_xml.scopedElement( "OverallResults" )
10267 .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
10268 .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
10269 .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
10270 m_xml.endElement();
10271 }
10272
10273 virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE {
10274 StreamingReporterBase::testRunEnded( testRunStats );
10275 m_xml.scopedElement( "OverallResults" )
10276 .writeAttribute( "successes", testRunStats.totals.assertions.passed )
10277 .writeAttribute( "failures", testRunStats.totals.assertions.failed )
10278 .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
10279 m_xml.endElement();
10280 }
10281
10282 private:
10283 Timer m_testCaseTimer;
10284 XmlWriter m_xml;
10285 int m_sectionDepth;
10286 };
10287
10288 INTERNAL_CATCH_REGISTER_REPORTER( "xml", XmlReporter )
10289
10290 } // end namespace Catch
10291
10292 // #included from: ../reporters/catch_reporter_junit.hpp
10293 #define TWOBLUECUBES_CATCH_REPORTER_JUNIT_HPP_INCLUDED
10294
10295 #include <assert.h>
10296
10297 namespace Catch {
10298
10299 namespace {
10300 std::string getCurrentTimestamp() {
10301 // Beware, this is not reentrant because of backward compatibility issues
10302 // Also, UTC only, again because of backward compatibility (%z is C++11)
10303 time_t rawtime;
10304 std::time(&rawtime);
10305 const size_t timeStampSize = sizeof("2017-01-16T17:06:45Z");
10306
10307 #ifdef _MSC_VER
10308 std::tm timeInfo = {};
10309 gmtime_s(&timeInfo, &rawtime);
10310 #else
10311 std::tm* timeInfo;
10312 timeInfo = std::gmtime(&rawtime);
10313 #endif
10314
10315 char timeStamp[timeStampSize];
10316 const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
10317
10318 #ifdef _MSC_VER
10319 std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
10320 #else
10321 std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
10322 #endif
10323 return std::string(timeStamp);
10324 }
10325
10326 }
10327
10328 class JunitReporter : public CumulativeReporterBase {
10329 public:
10330 JunitReporter( ReporterConfig const& _config )
10331 : CumulativeReporterBase( _config ),
10332 xml( _config.stream() ),
10333 m_okToFail( false )
10334 {
10335 m_reporterPrefs.shouldRedirectStdOut = true;
10336 }
10337
10338 virtual ~JunitReporter() CATCH_OVERRIDE;
10339
10340 static std::string getDescription() {
10341 return "Reports test results in an XML format that looks like Ant's junitreport target";
10342 }
10343
10344 virtual void noMatchingTestCases( std::string const& /*spec*/ ) CATCH_OVERRIDE {}
10345
10346 virtual void testRunStarting( TestRunInfo const& runInfo ) CATCH_OVERRIDE {
10347 CumulativeReporterBase::testRunStarting( runInfo );
10348 xml.startElement( "testsuites" );
10349 }
10350
10351 virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE {
10352 suiteTimer.start();
10353 stdOutForSuite.str("");
10354 stdErrForSuite.str("");
10355 unexpectedExceptions = 0;
10356 CumulativeReporterBase::testGroupStarting( groupInfo );
10357 }
10358
10359 virtual void testCaseStarting( TestCaseInfo const& testCaseInfo ) CATCH_OVERRIDE {
10360 m_okToFail = testCaseInfo.okToFail();
10361 }
10362 virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE {
10363 if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
10364 unexpectedExceptions++;
10365 return CumulativeReporterBase::assertionEnded( assertionStats );
10366 }
10367
10368 virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE {
10369 stdOutForSuite << testCaseStats.stdOut;
10370 stdErrForSuite << testCaseStats.stdErr;
10371 CumulativeReporterBase::testCaseEnded( testCaseStats );
10372 }
10373
10374 virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE {
10375 double suiteTime = suiteTimer.getElapsedSeconds();
10376 CumulativeReporterBase::testGroupEnded( testGroupStats );
10377 writeGroup( *m_testGroups.back(), suiteTime );
10378 }
10379
10380 virtual void testRunEndedCumulative() CATCH_OVERRIDE {
10381 xml.endElement();
10382 }
10383
10384 void writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
10385 XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
10386 TestGroupStats const& stats = groupNode.value;
10387 xml.writeAttribute( "name", stats.groupInfo.name );
10388 xml.writeAttribute( "errors", unexpectedExceptions );
10389 xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
10390 xml.writeAttribute( "tests", stats.totals.assertions.total() );
10391 xml.writeAttribute( "hostname", "tbd" ); // !TBD
10392 if( m_config->showDurations() == ShowDurations::Never )
10393 xml.writeAttribute( "time", "" );
10394 else
10395 xml.writeAttribute( "time", suiteTime );
10396 xml.writeAttribute( "timestamp", getCurrentTimestamp() );
10397
10398 // Write test cases
10399 for( TestGroupNode::ChildNodes::const_iterator
10400 it = groupNode.children.begin(), itEnd = groupNode.children.end();
10401 it != itEnd;
10402 ++it )
10403 writeTestCase( **it );
10404
10405 xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite.str() ), false );
10406 xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite.str() ), false );
10407 }
10408
10409 void writeTestCase( TestCaseNode const& testCaseNode ) {
10410 TestCaseStats const& stats = testCaseNode.value;
10411
10412 // All test cases have exactly one section - which represents the
10413 // test case itself. That section may have 0-n nested sections
10414 assert( testCaseNode.children.size() == 1 );
10415 SectionNode const& rootSection = *testCaseNode.children.front();
10416
10417 std::string className = stats.testInfo.className;
10418
10419 if( className.empty() ) {
10420 if( rootSection.childSections.empty() )
10421 className = "global";
10422 }
10423 writeSection( className, "", rootSection );
10424 }
10425
10426 void writeSection( std::string const& className,
10427 std::string const& rootName,
10428 SectionNode const& sectionNode ) {
10429 std::string name = trim( sectionNode.stats.sectionInfo.name );
10430 if( !rootName.empty() )
10431 name = rootName + '/' + name;
10432
10433 if( !sectionNode.assertions.empty() ||
10434 !sectionNode.stdOut.empty() ||
10435 !sectionNode.stdErr.empty() ) {
10436 XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
10437 if( className.empty() ) {
10438 xml.writeAttribute( "classname", name );
10439 xml.writeAttribute( "name", "root" );
10440 }
10441 else {
10442 xml.writeAttribute( "classname", className );
10443 xml.writeAttribute( "name", name );
10444 }
10445 xml.writeAttribute( "time", Catch::toString( sectionNode.stats.durationInSeconds ) );
10446
10447 writeAssertions( sectionNode );
10448
10449 if( !sectionNode.stdOut.empty() )
10450 xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
10451 if( !sectionNode.stdErr.empty() )
10452 xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
10453 }
10454 for( SectionNode::ChildSections::const_iterator
10455 it = sectionNode.childSections.begin(),
10456 itEnd = sectionNode.childSections.end();
10457 it != itEnd;
10458 ++it )
10459 if( className.empty() )
10460 writeSection( name, "", **it );
10461 else
10462 writeSection( className, name, **it );
10463 }
10464
10465 void writeAssertions( SectionNode const& sectionNode ) {
10466 for( SectionNode::Assertions::const_iterator
10467 it = sectionNode.assertions.begin(), itEnd = sectionNode.assertions.end();
10468 it != itEnd;
10469 ++it )
10470 writeAssertion( *it );
10471 }
10472 void writeAssertion( AssertionStats const& stats ) {
10473 AssertionResult const& result = stats.assertionResult;
10474 if( !result.isOk() ) {
10475 std::string elementName;
10476 switch( result.getResultType() ) {
10477 case ResultWas::ThrewException:
10478 case ResultWas::FatalErrorCondition:
10479 elementName = "error";
10480 break;
10481 case ResultWas::ExplicitFailure:
10482 elementName = "failure";
10483 break;
10484 case ResultWas::ExpressionFailed:
10485 elementName = "failure";
10486 break;
10487 case ResultWas::DidntThrowException:
10488 elementName = "failure";
10489 break;
10490
10491 // We should never see these here:
10492 case ResultWas::Info:
10493 case ResultWas::Warning:
10494 case ResultWas::Ok:
10495 case ResultWas::Unknown:
10496 case ResultWas::FailureBit:
10497 case ResultWas::Exception:
10498 elementName = "internalError";
10499 break;
10500 }
10501
10502 XmlWriter::ScopedElement e = xml.scopedElement( elementName );
10503
10504 xml.writeAttribute( "message", result.getExpandedExpression() );
10505 xml.writeAttribute( "type", result.getTestMacroName() );
10506
10507 std::ostringstream oss;
10508 if( !result.getMessage().empty() )
10509 oss << result.getMessage() << '\n';
10510 for( std::vector<MessageInfo>::const_iterator
10511 it = stats.infoMessages.begin(),
10512 itEnd = stats.infoMessages.end();
10513 it != itEnd;
10514 ++it )
10515 if( it->type == ResultWas::Info )
10516 oss << it->message << '\n';
10517
10518 oss << "at " << result.getSourceInfo();
10519 xml.writeText( oss.str(), false );
10520 }
10521 }
10522
10523 XmlWriter xml;
10524 Timer suiteTimer;
10525 std::ostringstream stdOutForSuite;
10526 std::ostringstream stdErrForSuite;
10527 unsigned int unexpectedExceptions;
10528 bool m_okToFail;
10529 };
10530
10531 INTERNAL_CATCH_REGISTER_REPORTER( "junit", JunitReporter )
10532
10533 } // end namespace Catch
10534
10535 // #included from: ../reporters/catch_reporter_console.hpp
10536 #define TWOBLUECUBES_CATCH_REPORTER_CONSOLE_HPP_INCLUDED
10537
10538 #include <cfloat>
10539 #include <cstdio>
10540
10541 namespace Catch {
10542
10543 struct ConsoleReporter : StreamingReporterBase {
10544 ConsoleReporter( ReporterConfig const& _config )
10545 : StreamingReporterBase( _config ),
10546 m_headerPrinted( false )
10547 {}
10548
10549 virtual ~ConsoleReporter() CATCH_OVERRIDE;
10550 static std::string getDescription() {
10551 return "Reports test results as plain lines of text";
10552 }
10553
10554 virtual void noMatchingTestCases( std::string const& spec ) CATCH_OVERRIDE {
10555 stream << "No test cases matched '" << spec << '\'' << std::endl;
10556 }
10557
10558 virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {
10559 }
10560
10561 virtual bool assertionEnded( AssertionStats const& _assertionStats ) CATCH_OVERRIDE {
10562 AssertionResult const& result = _assertionStats.assertionResult;
10563
10564 bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
10565
10566 // Drop out if result was successful but we're not printing them.
10567 if( !includeResults && result.getResultType() != ResultWas::Warning )
10568 return false;
10569
10570 lazyPrint();
10571
10572 AssertionPrinter printer( stream, _assertionStats, includeResults );
10573 printer.print();
10574 stream << std::endl;
10575 return true;
10576 }
10577
10578 virtual void sectionStarting( SectionInfo const& _sectionInfo ) CATCH_OVERRIDE {
10579 m_headerPrinted = false;
10580 StreamingReporterBase::sectionStarting( _sectionInfo );
10581 }
10582 virtual void sectionEnded( SectionStats const& _sectionStats ) CATCH_OVERRIDE {
10583 if( _sectionStats.missingAssertions ) {
10584 lazyPrint();
10585 Colour colour( Colour::ResultError );
10586 if( m_sectionStack.size() > 1 )
10587 stream << "\nNo assertions in section";
10588 else
10589 stream << "\nNo assertions in test case";
10590 stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
10591 }
10592 if( m_config->showDurations() == ShowDurations::Always ) {
10593 stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
10594 }
10595 if( m_headerPrinted ) {
10596 m_headerPrinted = false;
10597 }
10598 StreamingReporterBase::sectionEnded( _sectionStats );
10599 }
10600
10601 virtual void testCaseEnded( TestCaseStats const& _testCaseStats ) CATCH_OVERRIDE {
10602 StreamingReporterBase::testCaseEnded( _testCaseStats );
10603 m_headerPrinted = false;
10604 }
10605 virtual void testGroupEnded( TestGroupStats const& _testGroupStats ) CATCH_OVERRIDE {
10606 if( currentGroupInfo.used ) {
10607 printSummaryDivider();
10608 stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
10609 printTotals( _testGroupStats.totals );
10610 stream << '\n' << std::endl;
10611 }
10612 StreamingReporterBase::testGroupEnded( _testGroupStats );
10613 }
10614 virtual void testRunEnded( TestRunStats const& _testRunStats ) CATCH_OVERRIDE {
10615 printTotalsDivider( _testRunStats.totals );
10616 printTotals( _testRunStats.totals );
10617 stream << std::endl;
10618 StreamingReporterBase::testRunEnded( _testRunStats );
10619 }
10620
10621 private:
10622
10623 class AssertionPrinter {
10624 void operator= ( AssertionPrinter const& );
10625 public:
10626 AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages )
10627 : stream( _stream ),
10628 stats( _stats ),
10629 result( _stats.assertionResult ),
10630 colour( Colour::None ),
10631 message( result.getMessage() ),
10632 messages( _stats.infoMessages ),
10633 printInfoMessages( _printInfoMessages )
10634 {
10635 switch( result.getResultType() ) {
10636 case ResultWas::Ok:
10637 colour = Colour::Success;
10638 passOrFail = "PASSED";
10639 //if( result.hasMessage() )
10640 if( _stats.infoMessages.size() == 1 )
10641 messageLabel = "with message";
10642 if( _stats.infoMessages.size() > 1 )
10643 messageLabel = "with messages";
10644 break;
10645 case ResultWas::ExpressionFailed:
10646 if( result.isOk() ) {
10647 colour = Colour::Success;
10648 passOrFail = "FAILED - but was ok";
10649 }
10650 else {
10651 colour = Colour::Error;
10652 passOrFail = "FAILED";
10653 }
10654 if( _stats.infoMessages.size() == 1 )
10655 messageLabel = "with message";
10656 if( _stats.infoMessages.size() > 1 )
10657 messageLabel = "with messages";
10658 break;
10659 case ResultWas::ThrewException:
10660 colour = Colour::Error;
10661 passOrFail = "FAILED";
10662 messageLabel = "due to unexpected exception with ";
10663 if (_stats.infoMessages.size() == 1)
10664 messageLabel += "message";
10665 if (_stats.infoMessages.size() > 1)
10666 messageLabel += "messages";
10667 break;
10668 case ResultWas::FatalErrorCondition:
10669 colour = Colour::Error;
10670 passOrFail = "FAILED";
10671 messageLabel = "due to a fatal error condition";
10672 break;
10673 case ResultWas::DidntThrowException:
10674 colour = Colour::Error;
10675 passOrFail = "FAILED";
10676 messageLabel = "because no exception was thrown where one was expected";
10677 break;
10678 case ResultWas::Info:
10679 messageLabel = "info";
10680 break;
10681 case ResultWas::Warning:
10682 messageLabel = "warning";
10683 break;
10684 case ResultWas::ExplicitFailure:
10685 passOrFail = "FAILED";
10686 colour = Colour::Error;
10687 if( _stats.infoMessages.size() == 1 )
10688 messageLabel = "explicitly with message";
10689 if( _stats.infoMessages.size() > 1 )
10690 messageLabel = "explicitly with messages";
10691 break;
10692 // These cases are here to prevent compiler warnings
10693 case ResultWas::Unknown:
10694 case ResultWas::FailureBit:
10695 case ResultWas::Exception:
10696 passOrFail = "** internal error **";
10697 colour = Colour::Error;
10698 break;
10699 }
10700 }
10701
10702 void print() const {
10703 printSourceInfo();
10704 if( stats.totals.assertions.total() > 0 ) {
10705 if( result.isOk() )
10706 stream << '\n';
10707 printResultType();
10708 printOriginalExpression();
10709 printReconstructedExpression();
10710 }
10711 else {
10712 stream << '\n';
10713 }
10714 printMessage();
10715 }
10716
10717 private:
10718 void printResultType() const {
10719 if( !passOrFail.empty() ) {
10720 Colour colourGuard( colour );
10721 stream << passOrFail << ":\n";
10722 }
10723 }
10724 void printOriginalExpression() const {
10725 if( result.hasExpression() ) {
10726 Colour colourGuard( Colour::OriginalExpression );
10727 stream << " ";
10728 stream << result.getExpressionInMacro();
10729 stream << '\n';
10730 }
10731 }
10732 void printReconstructedExpression() const {
10733 if( result.hasExpandedExpression() ) {
10734 stream << "with expansion:\n";
10735 Colour colourGuard( Colour::ReconstructedExpression );
10736 stream << Text( result.getExpandedExpression(), TextAttributes().setIndent(2) ) << '\n';
10737 }
10738 }
10739 void printMessage() const {
10740 if( !messageLabel.empty() )
10741 stream << messageLabel << ':' << '\n';
10742 for( std::vector<MessageInfo>::const_iterator it = messages.begin(), itEnd = messages.end();
10743 it != itEnd;
10744 ++it ) {
10745 // If this assertion is a warning ignore any INFO messages
10746 if( printInfoMessages || it->type != ResultWas::Info )
10747 stream << Text( it->message, TextAttributes().setIndent(2) ) << '\n';
10748 }
10749 }
10750 void printSourceInfo() const {
10751 Colour colourGuard( Colour::FileName );
10752 stream << result.getSourceInfo() << ": ";
10753 }
10754
10755 std::ostream& stream;
10756 AssertionStats const& stats;
10757 AssertionResult const& result;
10758 Colour::Code colour;
10759 std::string passOrFail;
10760 std::string messageLabel;
10761 std::string message;
10762 std::vector<MessageInfo> messages;
10763 bool printInfoMessages;
10764 };
10765
10766 void lazyPrint() {
10767
10768 if( !currentTestRunInfo.used )
10769 lazyPrintRunInfo();
10770 if( !currentGroupInfo.used )
10771 lazyPrintGroupInfo();
10772
10773 if( !m_headerPrinted ) {
10774 printTestCaseAndSectionHeader();
10775 m_headerPrinted = true;
10776 }
10777 }
10778 void lazyPrintRunInfo() {
10779 stream << '\n' << getLineOfChars<'~'>() << '\n';
10780 Colour colour( Colour::SecondaryText );
10781 stream << currentTestRunInfo->name
10782 << " is a Catch v" << libraryVersion() << " host application.\n"
10783 << "Run with -? for options\n\n";
10784
10785 if( m_config->rngSeed() != 0 )
10786 stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
10787
10788 currentTestRunInfo.used = true;
10789 }
10790 void lazyPrintGroupInfo() {
10791 if( !currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1 ) {
10792 printClosedHeader( "Group: " + currentGroupInfo->name );
10793 currentGroupInfo.used = true;
10794 }
10795 }
10796 void printTestCaseAndSectionHeader() {
10797 assert( !m_sectionStack.empty() );
10798 printOpenHeader( currentTestCaseInfo->name );
10799
10800 if( m_sectionStack.size() > 1 ) {
10801 Colour colourGuard( Colour::Headers );
10802
10803 std::vector<SectionInfo>::const_iterator
10804 it = m_sectionStack.begin()+1, // Skip first section (test case)
10805 itEnd = m_sectionStack.end();
10806 for( ; it != itEnd; ++it )
10807 printHeaderString( it->name, 2 );
10808 }
10809
10810 SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
10811
10812 if( !lineInfo.empty() ){
10813 stream << getLineOfChars<'-'>() << '\n';
10814 Colour colourGuard( Colour::FileName );
10815 stream << lineInfo << '\n';
10816 }
10817 stream << getLineOfChars<'.'>() << '\n' << std::endl;
10818 }
10819
10820 void printClosedHeader( std::string const& _name ) {
10821 printOpenHeader( _name );
10822 stream << getLineOfChars<'.'>() << '\n';
10823 }
10824 void printOpenHeader( std::string const& _name ) {
10825 stream << getLineOfChars<'-'>() << '\n';
10826 {
10827 Colour colourGuard( Colour::Headers );
10828 printHeaderString( _name );
10829 }
10830 }
10831
10832 // if string has a : in first line will set indent to follow it on
10833 // subsequent lines
10834 void printHeaderString( std::string const& _string, std::size_t indent = 0 ) {
10835 std::size_t i = _string.find( ": " );
10836 if( i != std::string::npos )
10837 i+=2;
10838 else
10839 i = 0;
10840 stream << Text( _string, TextAttributes()
10841 .setIndent( indent+i)
10842 .setInitialIndent( indent ) ) << '\n';
10843 }
10844
10845 struct SummaryColumn {
10846
10847 SummaryColumn( std::string const& _label, Colour::Code _colour )
10848 : label( _label ),
10849 colour( _colour )
10850 {}
10851 SummaryColumn addRow( std::size_t count ) {
10852 std::ostringstream oss;
10853 oss << count;
10854 std::string row = oss.str();
10855 for( std::vector<std::string>::iterator it = rows.begin(); it != rows.end(); ++it ) {
10856 while( it->size() < row.size() )
10857 *it = ' ' + *it;
10858 while( it->size() > row.size() )
10859 row = ' ' + row;
10860 }
10861 rows.push_back( row );
10862 return *this;
10863 }
10864
10865 std::string label;
10866 Colour::Code colour;
10867 std::vector<std::string> rows;
10868
10869 };
10870
10871 void printTotals( Totals const& totals ) {
10872 if( totals.testCases.total() == 0 ) {
10873 stream << Colour( Colour::Warning ) << "No tests ran\n";
10874 }
10875 else if( totals.assertions.total() > 0 && totals.testCases.allPassed() ) {
10876 stream << Colour( Colour::ResultSuccess ) << "All tests passed";
10877 stream << " ("
10878 << pluralise( totals.assertions.passed, "assertion" ) << " in "
10879 << pluralise( totals.testCases.passed, "test case" ) << ')'
10880 << '\n';
10881 }
10882 else {
10883
10884 std::vector<SummaryColumn> columns;
10885 columns.push_back( SummaryColumn( "", Colour::None )
10886 .addRow( totals.testCases.total() )
10887 .addRow( totals.assertions.total() ) );
10888 columns.push_back( SummaryColumn( "passed", Colour::Success )
10889 .addRow( totals.testCases.passed )
10890 .addRow( totals.assertions.passed ) );
10891 columns.push_back( SummaryColumn( "failed", Colour::ResultError )
10892 .addRow( totals.testCases.failed )
10893 .addRow( totals.assertions.failed ) );
10894 columns.push_back( SummaryColumn( "failed as expected", Colour::ResultExpectedFailure )
10895 .addRow( totals.testCases.failedButOk )
10896 .addRow( totals.assertions.failedButOk ) );
10897
10898 printSummaryRow( "test cases", columns, 0 );
10899 printSummaryRow( "assertions", columns, 1 );
10900 }
10901 }
10902 void printSummaryRow( std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row ) {
10903 for( std::vector<SummaryColumn>::const_iterator it = cols.begin(); it != cols.end(); ++it ) {
10904 std::string value = it->rows[row];
10905 if( it->label.empty() ) {
10906 stream << label << ": ";
10907 if( value != "0" )
10908 stream << value;
10909 else
10910 stream << Colour( Colour::Warning ) << "- none -";
10911 }
10912 else if( value != "0" ) {
10913 stream << Colour( Colour::LightGrey ) << " | ";
10914 stream << Colour( it->colour )
10915 << value << ' ' << it->label;
10916 }
10917 }
10918 stream << '\n';
10919 }
10920
10921 static std::size_t makeRatio( std::size_t number, std::size_t total ) {
10922 std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number/ total : 0;
10923 return ( ratio == 0 && number > 0 ) ? 1 : ratio;
10924 }
10925 static std::size_t& findMax( std::size_t& i, std::size_t& j, std::size_t& k ) {
10926 if( i > j && i > k )
10927 return i;
10928 else if( j > k )
10929 return j;
10930 else
10931 return k;
10932 }
10933
10934 void printTotalsDivider( Totals const& totals ) {
10935 if( totals.testCases.total() > 0 ) {
10936 std::size_t failedRatio = makeRatio( totals.testCases.failed, totals.testCases.total() );
10937 std::size_t failedButOkRatio = makeRatio( totals.testCases.failedButOk, totals.testCases.total() );
10938 std::size_t passedRatio = makeRatio( totals.testCases.passed, totals.testCases.total() );
10939 while( failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH-1 )
10940 findMax( failedRatio, failedButOkRatio, passedRatio )++;
10941 while( failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH-1 )
10942 findMax( failedRatio, failedButOkRatio, passedRatio )--;
10943
10944 stream << Colour( Colour::Error ) << std::string( failedRatio, '=' );
10945 stream << Colour( Colour::ResultExpectedFailure ) << std::string( failedButOkRatio, '=' );
10946 if( totals.testCases.allPassed() )
10947 stream << Colour( Colour::ResultSuccess ) << std::string( passedRatio, '=' );
10948 else
10949 stream << Colour( Colour::Success ) << std::string( passedRatio, '=' );
10950 }
10951 else {
10952 stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH-1, '=' );
10953 }
10954 stream << '\n';
10955 }
10956 void printSummaryDivider() {
10957 stream << getLineOfChars<'-'>() << '\n';
10958 }
10959
10960 private:
10961 bool m_headerPrinted;
10962 };
10963
10964 INTERNAL_CATCH_REGISTER_REPORTER( "console", ConsoleReporter )
10965
10966 } // end namespace Catch
10967
10968 // #included from: ../reporters/catch_reporter_compact.hpp
10969 #define TWOBLUECUBES_CATCH_REPORTER_COMPACT_HPP_INCLUDED
10970
10971 namespace Catch {
10972
10973 struct CompactReporter : StreamingReporterBase {
10974
10975 CompactReporter( ReporterConfig const& _config )
10976 : StreamingReporterBase( _config )
10977 {}
10978
10979 virtual ~CompactReporter();
10980
10981 static std::string getDescription() {
10982 return "Reports test results on a single line, suitable for IDEs";
10983 }
10984
10985 virtual ReporterPreferences getPreferences() const {
10986 ReporterPreferences prefs;
10987 prefs.shouldRedirectStdOut = false;
10988 return prefs;
10989 }
10990
10991 virtual void noMatchingTestCases( std::string const& spec ) {
10992 stream << "No test cases matched '" << spec << '\'' << std::endl;
10993 }
10994
10995 virtual void assertionStarting( AssertionInfo const& ) {}
10996
10997 virtual bool assertionEnded( AssertionStats const& _assertionStats ) {
10998 AssertionResult const& result = _assertionStats.assertionResult;
10999
11000 bool printInfoMessages = true;
11001
11002 // Drop out if result was successful and we're not printing those
11003 if( !m_config->includeSuccessfulResults() && result.isOk() ) {
11004 if( result.getResultType() != ResultWas::Warning )
11005 return false;
11006 printInfoMessages = false;
11007 }
11008
11009 AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
11010 printer.print();
11011
11012 stream << std::endl;
11013 return true;
11014 }
11015
11016 virtual void sectionEnded(SectionStats const& _sectionStats) CATCH_OVERRIDE {
11017 if (m_config->showDurations() == ShowDurations::Always) {
11018 stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
11019 }
11020 }
11021
11022 virtual void testRunEnded( TestRunStats const& _testRunStats ) {
11023 printTotals( _testRunStats.totals );
11024 stream << '\n' << std::endl;
11025 StreamingReporterBase::testRunEnded( _testRunStats );
11026 }
11027
11028 private:
11029 class AssertionPrinter {
11030 void operator= ( AssertionPrinter const& );
11031 public:
11032 AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages )
11033 : stream( _stream )
11034 , stats( _stats )
11035 , result( _stats.assertionResult )
11036 , messages( _stats.infoMessages )
11037 , itMessage( _stats.infoMessages.begin() )
11038 , printInfoMessages( _printInfoMessages )
11039 {}
11040
11041 void print() {
11042 printSourceInfo();
11043
11044 itMessage = messages.begin();
11045
11046 switch( result.getResultType() ) {
11047 case ResultWas::Ok:
11048 printResultType( Colour::ResultSuccess, passedString() );
11049 printOriginalExpression();
11050 printReconstructedExpression();
11051 if ( ! result.hasExpression() )
11052 printRemainingMessages( Colour::None );
11053 else
11054 printRemainingMessages();
11055 break;
11056 case ResultWas::ExpressionFailed:
11057 if( result.isOk() )
11058 printResultType( Colour::ResultSuccess, failedString() + std::string( " - but was ok" ) );
11059 else
11060 printResultType( Colour::Error, failedString() );
11061 printOriginalExpression();
11062 printReconstructedExpression();
11063 printRemainingMessages();
11064 break;
11065 case ResultWas::ThrewException:
11066 printResultType( Colour::Error, failedString() );
11067 printIssue( "unexpected exception with message:" );
11068 printMessage();
11069 printExpressionWas();
11070 printRemainingMessages();
11071 break;
11072 case ResultWas::FatalErrorCondition:
11073 printResultType( Colour::Error, failedString() );
11074 printIssue( "fatal error condition with message:" );
11075 printMessage();
11076 printExpressionWas();
11077 printRemainingMessages();
11078 break;
11079 case ResultWas::DidntThrowException:
11080 printResultType( Colour::Error, failedString() );
11081 printIssue( "expected exception, got none" );
11082 printExpressionWas();
11083 printRemainingMessages();
11084 break;
11085 case ResultWas::Info:
11086 printResultType( Colour::None, "info" );
11087 printMessage();
11088 printRemainingMessages();
11089 break;
11090 case ResultWas::Warning:
11091 printResultType( Colour::None, "warning" );
11092 printMessage();
11093 printRemainingMessages();
11094 break;
11095 case ResultWas::ExplicitFailure:
11096 printResultType( Colour::Error, failedString() );
11097 printIssue( "explicitly" );
11098 printRemainingMessages( Colour::None );
11099 break;
11100 // These cases are here to prevent compiler warnings
11101 case ResultWas::Unknown:
11102 case ResultWas::FailureBit:
11103 case ResultWas::Exception:
11104 printResultType( Colour::Error, "** internal error **" );
11105 break;
11106 }
11107 }
11108
11109 private:
11110 // Colour::LightGrey
11111
11112 static Colour::Code dimColour() { return Colour::FileName; }
11113
11114 #ifdef CATCH_PLATFORM_MAC
11115 static const char* failedString() { return "FAILED"; }
11116 static const char* passedString() { return "PASSED"; }
11117 #else
11118 static const char* failedString() { return "failed"; }
11119 static const char* passedString() { return "passed"; }
11120 #endif
11121
11122 void printSourceInfo() const {
11123 Colour colourGuard( Colour::FileName );
11124 stream << result.getSourceInfo() << ':';
11125 }
11126
11127 void printResultType( Colour::Code colour, std::string const& passOrFail ) const {
11128 if( !passOrFail.empty() ) {
11129 {
11130 Colour colourGuard( colour );
11131 stream << ' ' << passOrFail;
11132 }
11133 stream << ':';
11134 }
11135 }
11136
11137 void printIssue( std::string const& issue ) const {
11138 stream << ' ' << issue;
11139 }
11140
11141 void printExpressionWas() {
11142 if( result.hasExpression() ) {
11143 stream << ';';
11144 {
11145 Colour colour( dimColour() );
11146 stream << " expression was:";
11147 }
11148 printOriginalExpression();
11149 }
11150 }
11151
11152 void printOriginalExpression() const {
11153 if( result.hasExpression() ) {
11154 stream << ' ' << result.getExpression();
11155 }
11156 }
11157
11158 void printReconstructedExpression() const {
11159 if( result.hasExpandedExpression() ) {
11160 {
11161 Colour colour( dimColour() );
11162 stream << " for: ";
11163 }
11164 stream << result.getExpandedExpression();
11165 }
11166 }
11167
11168 void printMessage() {
11169 if ( itMessage != messages.end() ) {
11170 stream << " '" << itMessage->message << '\'';
11171 ++itMessage;
11172 }
11173 }
11174
11175 void printRemainingMessages( Colour::Code colour = dimColour() ) {
11176 if ( itMessage == messages.end() )
11177 return;
11178
11179 // using messages.end() directly yields compilation error:
11180 std::vector<MessageInfo>::const_iterator itEnd = messages.end();
11181 const std::size_t N = static_cast<std::size_t>( std::distance( itMessage, itEnd ) );
11182
11183 {
11184 Colour colourGuard( colour );
11185 stream << " with " << pluralise( N, "message" ) << ':';
11186 }
11187
11188 for(; itMessage != itEnd; ) {
11189 // If this assertion is a warning ignore any INFO messages
11190 if( printInfoMessages || itMessage->type != ResultWas::Info ) {
11191 stream << " '" << itMessage->message << '\'';
11192 if ( ++itMessage != itEnd ) {
11193 Colour colourGuard( dimColour() );
11194 stream << " and";
11195 }
11196 }
11197 }
11198 }
11199
11200 private:
11201 std::ostream& stream;
11202 AssertionStats const& stats;
11203 AssertionResult const& result;
11204 std::vector<MessageInfo> messages;
11205 std::vector<MessageInfo>::const_iterator itMessage;
11206 bool printInfoMessages;
11207 };
11208
11209 // Colour, message variants:
11210 // - white: No tests ran.
11211 // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
11212 // - white: Passed [both/all] N test cases (no assertions).
11213 // - red: Failed N tests cases, failed M assertions.
11214 // - green: Passed [both/all] N tests cases with M assertions.
11215
11216 std::string bothOrAll( std::size_t count ) const {
11217 return count == 1 ? std::string() : count == 2 ? "both " : "all " ;
11218 }
11219
11220 void printTotals( const Totals& totals ) const {
11221 if( totals.testCases.total() == 0 ) {
11222 stream << "No tests ran.";
11223 }
11224 else if( totals.testCases.failed == totals.testCases.total() ) {
11225 Colour colour( Colour::ResultError );
11226 const std::string qualify_assertions_failed =
11227 totals.assertions.failed == totals.assertions.total() ?
11228 bothOrAll( totals.assertions.failed ) : std::string();
11229 stream <<
11230 "Failed " << bothOrAll( totals.testCases.failed )
11231 << pluralise( totals.testCases.failed, "test case" ) << ", "
11232 "failed " << qualify_assertions_failed <<
11233 pluralise( totals.assertions.failed, "assertion" ) << '.';
11234 }
11235 else if( totals.assertions.total() == 0 ) {
11236 stream <<
11237 "Passed " << bothOrAll( totals.testCases.total() )
11238 << pluralise( totals.testCases.total(), "test case" )
11239 << " (no assertions).";
11240 }
11241 else if( totals.assertions.failed ) {
11242 Colour colour( Colour::ResultError );
11243 stream <<
11244 "Failed " << pluralise( totals.testCases.failed, "test case" ) << ", "
11245 "failed " << pluralise( totals.assertions.failed, "assertion" ) << '.';
11246 }
11247 else {
11248 Colour colour( Colour::ResultSuccess );
11249 stream <<
11250 "Passed " << bothOrAll( totals.testCases.passed )
11251 << pluralise( totals.testCases.passed, "test case" ) <<
11252 " with " << pluralise( totals.assertions.passed, "assertion" ) << '.';
11253 }
11254 }
11255 };
11256
11257 INTERNAL_CATCH_REGISTER_REPORTER( "compact", CompactReporter )
11258
11259 } // end namespace Catch
11260
11261 namespace Catch {
11262 // These are all here to avoid warnings about not having any out of line
11263 // virtual methods
11264 NonCopyable::~NonCopyable() {}
11265 IShared::~IShared() {}
11266 IStream::~IStream() CATCH_NOEXCEPT {}
11267 FileStream::~FileStream() CATCH_NOEXCEPT {}
11268 CoutStream::~CoutStream() CATCH_NOEXCEPT {}
11269 DebugOutStream::~DebugOutStream() CATCH_NOEXCEPT {}
11270 StreamBufBase::~StreamBufBase() CATCH_NOEXCEPT {}
11271 IContext::~IContext() {}
11272 IResultCapture::~IResultCapture() {}
11273 ITestCase::~ITestCase() {}
11274 ITestCaseRegistry::~ITestCaseRegistry() {}
11275 IRegistryHub::~IRegistryHub() {}
11276 IMutableRegistryHub::~IMutableRegistryHub() {}
11277 IExceptionTranslator::~IExceptionTranslator() {}
11278 IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() {}
11279 IReporter::~IReporter() {}
11280 IReporterFactory::~IReporterFactory() {}
11281 IReporterRegistry::~IReporterRegistry() {}
11282 IStreamingReporter::~IStreamingReporter() {}
11283 AssertionStats::~AssertionStats() {}
11284 SectionStats::~SectionStats() {}
11285 TestCaseStats::~TestCaseStats() {}
11286 TestGroupStats::~TestGroupStats() {}
11287 TestRunStats::~TestRunStats() {}
11288 CumulativeReporterBase::SectionNode::~SectionNode() {}
11289 CumulativeReporterBase::~CumulativeReporterBase() {}
11290
11291 StreamingReporterBase::~StreamingReporterBase() {}
11292 ConsoleReporter::~ConsoleReporter() {}
11293 CompactReporter::~CompactReporter() {}
11294 IRunner::~IRunner() {}
11295 IMutableContext::~IMutableContext() {}
11296 IConfig::~IConfig() {}
11297 XmlReporter::~XmlReporter() {}
11298 JunitReporter::~JunitReporter() {}
11299 TestRegistry::~TestRegistry() {}
11300 FreeFunctionTestCase::~FreeFunctionTestCase() {}
11301 IGeneratorInfo::~IGeneratorInfo() {}
11302 IGeneratorsForTest::~IGeneratorsForTest() {}
11303 WildcardPattern::~WildcardPattern() {}
11304 TestSpec::Pattern::~Pattern() {}
11305 TestSpec::NamePattern::~NamePattern() {}
11306 TestSpec::TagPattern::~TagPattern() {}
11307 TestSpec::ExcludedPattern::~ExcludedPattern() {}
11308 Matchers::Impl::MatcherUntypedBase::~MatcherUntypedBase() {}
11309
11310 void Config::dummy() {}
11311
11312 namespace TestCaseTracking {
11313 ITracker::~ITracker() {}
11314 TrackerBase::~TrackerBase() {}
11315 SectionTracker::~SectionTracker() {}
11316 IndexTracker::~IndexTracker() {}
11317 }
11318 }
11319
11320 #ifdef __clang__
11321 #pragma clang diagnostic pop
11322 #endif
11323
11324 #endif
11325
11326 #ifdef CATCH_CONFIG_MAIN
11327 // #included from: internal/catch_default_main.hpp
11328 #define TWOBLUECUBES_CATCH_DEFAULT_MAIN_HPP_INCLUDED
11329
11330 #ifndef __OBJC__
11331
11332 #if defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
11333 // Standard C/C++ Win32 Unicode wmain entry point
11334 extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
11335 #else
11336 // Standard C/C++ main entry point
11337 int main (int argc, char * argv[]) {
11338 #endif
11339
11340 int result = Catch::Session().run( argc, argv );
11341 return ( result < 0xff ? result : 0xff );
11342 }
11343
11344 #else // __OBJC__
11345
11346 // Objective-C entry point
11347 int main (int argc, char * const argv[]) {
11348 #if !CATCH_ARC_ENABLED
11349 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
11350 #endif
11351
11352 Catch::registerTestMethods();
11353 int result = Catch::Session().run( argc, (char* const*)argv );
11354
11355 #if !CATCH_ARC_ENABLED
11356 [pool drain];
11357 #endif
11358
11359 return ( result < 0xff ? result : 0xff );
11360 }
11361
11362 #endif // __OBJC__
11363
11364 #endif
11365
11366 #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
11367 # undef CLARA_CONFIG_MAIN
11368 #endif
11369
11370 //////
11371
11372 // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
11373 #ifdef CATCH_CONFIG_PREFIX_ALL
11374
11375 #if defined(CATCH_CONFIG_FAST_COMPILE)
11376 #define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, expr )
11377 #define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr )
11378 #else
11379 #define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, expr )
11380 #define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr )
11381 #endif
11382
11383 #define CATCH_REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", expr )
11384 #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
11385 #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
11386 #define CATCH_REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, expr )
11387
11388 #define CATCH_CHECK( expr ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, expr )
11389 #define CATCH_CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, expr )
11390 #define CATCH_CHECKED_IF( expr ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, expr )
11391 #define CATCH_CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, expr )
11392 #define CATCH_CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, expr )
11393
11394 #define CATCH_CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", expr )
11395 #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
11396 #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
11397 #define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, expr )
11398
11399 #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
11400
11401 #if defined(CATCH_CONFIG_FAST_COMPILE)
11402 #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT_NO_TRY( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
11403 #else
11404 #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
11405 #endif
11406
11407 #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
11408 #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
11409 #define CATCH_SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
11410 #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << Catch::toString(msg) )
11411 #define CATCH_SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << Catch::toString(msg) )
11412
11413 #ifdef CATCH_CONFIG_VARIADIC_MACROS
11414 #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
11415 #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
11416 #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
11417 #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
11418 #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
11419 #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
11420 #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
11421 #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
11422 #else
11423 #define CATCH_TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description )
11424 #define CATCH_TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description )
11425 #define CATCH_METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description )
11426 #define CATCH_REGISTER_TEST_CASE( function, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( function, name, description )
11427 #define CATCH_SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description )
11428 #define CATCH_FAIL( msg ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, msg )
11429 #define CATCH_FAIL_CHECK( msg ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, msg )
11430 #define CATCH_SUCCEED( msg ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, msg )
11431 #endif
11432 #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" )
11433
11434 #define CATCH_REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType )
11435 #define CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType )
11436
11437 #define CATCH_GENERATE( expr) INTERNAL_CATCH_GENERATE( expr )
11438
11439 // "BDD-style" convenience wrappers
11440 #ifdef CATCH_CONFIG_VARIADIC_MACROS
11441 #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
11442 #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
11443 #else
11444 #define CATCH_SCENARIO( name, tags ) CATCH_TEST_CASE( "Scenario: " name, tags )
11445 #define CATCH_SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags )
11446 #endif
11447 #define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( "Given: ") + desc, "" )
11448 #define CATCH_WHEN( desc ) CATCH_SECTION( std::string( " When: ") + desc, "" )
11449 #define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( " And: ") + desc, "" )
11450 #define CATCH_THEN( desc ) CATCH_SECTION( std::string( " Then: ") + desc, "" )
11451 #define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( " And: ") + desc, "" )
11452
11453 // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
11454 #else
11455
11456 #if defined(CATCH_CONFIG_FAST_COMPILE)
11457 #define REQUIRE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "REQUIRE", Catch::ResultDisposition::Normal, expr )
11458 #define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST_NO_TRY( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr )
11459
11460 #else
11461 #define REQUIRE( expr ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, expr )
11462 #define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, expr )
11463 #endif
11464
11465 #define REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", expr )
11466 #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
11467 #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
11468 #define REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, expr )
11469
11470 #define CHECK( expr ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, expr )
11471 #define CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, expr )
11472 #define CHECKED_IF( expr ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, expr )
11473 #define CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, expr )
11474 #define CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, expr )
11475
11476 #define CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", expr )
11477 #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
11478 #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
11479 #define CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, expr )
11480
11481 #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
11482
11483 #if defined(CATCH_CONFIG_FAST_COMPILE)
11484 #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT_NO_TRY( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
11485 #else
11486 #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
11487 #endif
11488
11489 #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
11490 #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
11491 #define SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
11492 #define CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << Catch::toString(msg) )
11493 #define SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << Catch::toString(msg) )
11494
11495 #ifdef CATCH_CONFIG_VARIADIC_MACROS
11496 #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
11497 #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
11498 #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
11499 #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
11500 #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
11501 #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
11502 #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
11503 #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
11504 #else
11505 #define TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description )
11506 #define TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description )
11507 #define METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description )
11508 #define REGISTER_TEST_CASE( method, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( method, name, description )
11509 #define SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description )
11510 #define FAIL( msg ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, msg )
11511 #define FAIL_CHECK( msg ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, msg )
11512 #define SUCCEED( msg ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, msg )
11513 #endif
11514 #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" )
11515
11516 #define REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType )
11517 #define REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType )
11518
11519 #define GENERATE( expr) INTERNAL_CATCH_GENERATE( expr )
11520
11521 #endif
11522
11523 #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
11524
11525 // "BDD-style" convenience wrappers
11526 #ifdef CATCH_CONFIG_VARIADIC_MACROS
11527 #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
11528 #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
11529 #else
11530 #define SCENARIO( name, tags ) TEST_CASE( "Scenario: " name, tags )
11531 #define SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags )
11532 #endif
11533 #define GIVEN( desc ) SECTION( std::string(" Given: ") + desc, "" )
11534 #define WHEN( desc ) SECTION( std::string(" When: ") + desc, "" )
11535 #define AND_WHEN( desc ) SECTION( std::string("And when: ") + desc, "" )
11536 #define THEN( desc ) SECTION( std::string(" Then: ") + desc, "" )
11537 #define AND_THEN( desc ) SECTION( std::string(" And: ") + desc, "" )
11538
11539 using Catch::Detail::Approx;
11540
11541 // #included from: internal/catch_reenable_warnings.h
11542
11543 #define TWOBLUECUBES_CATCH_REENABLE_WARNINGS_H_INCLUDED
11544
11545 #ifdef __clang__
11546 # ifdef __ICC // icpc defines the __clang__ macro
11547 # pragma warning(pop)
11548 # else
11549 # pragma clang diagnostic pop
11550 # endif
11551 #elif defined __GNUC__
11552 # pragma GCC diagnostic pop
11553 #endif
11554
11555 #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED
11556