🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

10445 lines
368 KiB

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