🛠️🐜 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.

10460 lines
368 KiB

  1. /*
  2. * Catch v1.5.0
  3. * Generated: 2016-04-25 18:56:14.308559
  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.2.3
  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. #if defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
  3200. #define CLARA_PLATFORM_WINDOWS
  3201. #endif
  3202. // Use optional outer namespace
  3203. #ifdef STITCH_CLARA_OPEN_NAMESPACE
  3204. STITCH_CLARA_OPEN_NAMESPACE
  3205. #endif
  3206. namespace Clara {
  3207. struct UnpositionalTag {};
  3208. extern UnpositionalTag _;
  3209. #ifdef CLARA_CONFIG_MAIN
  3210. UnpositionalTag _;
  3211. #endif
  3212. namespace Detail {
  3213. #ifdef CLARA_CONSOLE_WIDTH
  3214. const unsigned int consoleWidth = CLARA_CONFIG_CONSOLE_WIDTH;
  3215. #else
  3216. const unsigned int consoleWidth = 80;
  3217. #endif
  3218. using namespace Tbc;
  3219. inline bool startsWith( std::string const& str, std::string const& prefix ) {
  3220. return str.size() >= prefix.size() && str.substr( 0, prefix.size() ) == prefix;
  3221. }
  3222. template<typename T> struct RemoveConstRef{ typedef T type; };
  3223. template<typename T> struct RemoveConstRef<T&>{ typedef T type; };
  3224. template<typename T> struct RemoveConstRef<T const&>{ typedef T type; };
  3225. template<typename T> struct RemoveConstRef<T const>{ typedef T type; };
  3226. template<typename T> struct IsBool { static const bool value = false; };
  3227. template<> struct IsBool<bool> { static const bool value = true; };
  3228. template<typename T>
  3229. void convertInto( std::string const& _source, T& _dest ) {
  3230. std::stringstream ss;
  3231. ss << _source;
  3232. ss >> _dest;
  3233. if( ss.fail() )
  3234. throw std::runtime_error( "Unable to convert " + _source + " to destination type" );
  3235. }
  3236. inline void convertInto( std::string const& _source, std::string& _dest ) {
  3237. _dest = _source;
  3238. }
  3239. inline void convertInto( std::string const& _source, bool& _dest ) {
  3240. std::string sourceLC = _source;
  3241. std::transform( sourceLC.begin(), sourceLC.end(), sourceLC.begin(), ::tolower );
  3242. if( sourceLC == "y" || sourceLC == "1" || sourceLC == "true" || sourceLC == "yes" || sourceLC == "on" )
  3243. _dest = true;
  3244. else if( sourceLC == "n" || sourceLC == "0" || sourceLC == "false" || sourceLC == "no" || sourceLC == "off" )
  3245. _dest = false;
  3246. else
  3247. throw std::runtime_error( "Expected a boolean value but did not recognise:\n '" + _source + "'" );
  3248. }
  3249. template<typename ConfigT>
  3250. struct IArgFunction {
  3251. virtual ~IArgFunction() {}
  3252. #ifdef CLARA_CONFIG_CPP11_GENERATED_METHODS
  3253. IArgFunction() = default;
  3254. IArgFunction( IArgFunction const& ) = default;
  3255. #endif
  3256. virtual void set( ConfigT& config, std::string const& value ) const = 0;
  3257. virtual bool takesArg() const = 0;
  3258. virtual IArgFunction* clone() const = 0;
  3259. };
  3260. template<typename ConfigT>
  3261. class BoundArgFunction {
  3262. public:
  3263. BoundArgFunction() : functionObj( CLARA_NULL ) {}
  3264. BoundArgFunction( IArgFunction<ConfigT>* _functionObj ) : functionObj( _functionObj ) {}
  3265. BoundArgFunction( BoundArgFunction const& other ) : functionObj( other.functionObj ? other.functionObj->clone() : CLARA_NULL ) {}
  3266. BoundArgFunction& operator = ( BoundArgFunction const& other ) {
  3267. IArgFunction<ConfigT>* newFunctionObj = other.functionObj ? other.functionObj->clone() : CLARA_NULL;
  3268. delete functionObj;
  3269. functionObj = newFunctionObj;
  3270. return *this;
  3271. }
  3272. ~BoundArgFunction() { delete functionObj; }
  3273. void set( ConfigT& config, std::string const& value ) const {
  3274. functionObj->set( config, value );
  3275. }
  3276. bool takesArg() const { return functionObj->takesArg(); }
  3277. bool isSet() const {
  3278. return functionObj != CLARA_NULL;
  3279. }
  3280. private:
  3281. IArgFunction<ConfigT>* functionObj;
  3282. };
  3283. template<typename C>
  3284. struct NullBinder : IArgFunction<C>{
  3285. virtual void set( C&, std::string const& ) const {}
  3286. virtual bool takesArg() const { return true; }
  3287. virtual IArgFunction<C>* clone() const { return new NullBinder( *this ); }
  3288. };
  3289. template<typename C, typename M>
  3290. struct BoundDataMember : IArgFunction<C>{
  3291. BoundDataMember( M C::* _member ) : member( _member ) {}
  3292. virtual void set( C& p, std::string const& stringValue ) const {
  3293. convertInto( stringValue, p.*member );
  3294. }
  3295. virtual bool takesArg() const { return !IsBool<M>::value; }
  3296. virtual IArgFunction<C>* clone() const { return new BoundDataMember( *this ); }
  3297. M C::* member;
  3298. };
  3299. template<typename C, typename M>
  3300. struct BoundUnaryMethod : IArgFunction<C>{
  3301. BoundUnaryMethod( void (C::*_member)( M ) ) : member( _member ) {}
  3302. virtual void set( C& p, std::string const& stringValue ) const {
  3303. typename RemoveConstRef<M>::type value;
  3304. convertInto( stringValue, value );
  3305. (p.*member)( value );
  3306. }
  3307. virtual bool takesArg() const { return !IsBool<M>::value; }
  3308. virtual IArgFunction<C>* clone() const { return new BoundUnaryMethod( *this ); }
  3309. void (C::*member)( M );
  3310. };
  3311. template<typename C>
  3312. struct BoundNullaryMethod : IArgFunction<C>{
  3313. BoundNullaryMethod( void (C::*_member)() ) : member( _member ) {}
  3314. virtual void set( C& p, std::string const& stringValue ) const {
  3315. bool value;
  3316. convertInto( stringValue, value );
  3317. if( value )
  3318. (p.*member)();
  3319. }
  3320. virtual bool takesArg() const { return false; }
  3321. virtual IArgFunction<C>* clone() const { return new BoundNullaryMethod( *this ); }
  3322. void (C::*member)();
  3323. };
  3324. template<typename C>
  3325. struct BoundUnaryFunction : IArgFunction<C>{
  3326. BoundUnaryFunction( void (*_function)( C& ) ) : function( _function ) {}
  3327. virtual void set( C& obj, std::string const& stringValue ) const {
  3328. bool value;
  3329. convertInto( stringValue, value );
  3330. if( value )
  3331. function( obj );
  3332. }
  3333. virtual bool takesArg() const { return false; }
  3334. virtual IArgFunction<C>* clone() const { return new BoundUnaryFunction( *this ); }
  3335. void (*function)( C& );
  3336. };
  3337. template<typename C, typename T>
  3338. struct BoundBinaryFunction : IArgFunction<C>{
  3339. BoundBinaryFunction( void (*_function)( C&, T ) ) : function( _function ) {}
  3340. virtual void set( C& obj, std::string const& stringValue ) const {
  3341. typename RemoveConstRef<T>::type value;
  3342. convertInto( stringValue, value );
  3343. function( obj, value );
  3344. }
  3345. virtual bool takesArg() const { return !IsBool<T>::value; }
  3346. virtual IArgFunction<C>* clone() const { return new BoundBinaryFunction( *this ); }
  3347. void (*function)( C&, T );
  3348. };
  3349. } // namespace Detail
  3350. inline std::vector<std::string> argsToVector( int argc, char const* const* const argv ) {
  3351. std::vector<std::string> args( static_cast<std::size_t>( argc ) );
  3352. for( std::size_t i = 0; i < static_cast<std::size_t>( argc ); ++i )
  3353. args[i] = argv[i];
  3354. return args;
  3355. }
  3356. class Parser {
  3357. enum Mode { None, MaybeShortOpt, SlashOpt, ShortOpt, LongOpt, Positional };
  3358. Mode mode;
  3359. std::size_t from;
  3360. bool inQuotes;
  3361. public:
  3362. struct Token {
  3363. enum Type { Positional, ShortOpt, LongOpt };
  3364. Token( Type _type, std::string const& _data ) : type( _type ), data( _data ) {}
  3365. Type type;
  3366. std::string data;
  3367. };
  3368. Parser() : mode( None ), from( 0 ), inQuotes( false ){}
  3369. void parseIntoTokens( std::vector<std::string> const& args, std::vector<Token>& tokens ) {
  3370. const std::string doubleDash = "--";
  3371. for( std::size_t i = 1; i < args.size() && args[i] != doubleDash; ++i )
  3372. parseIntoTokens( args[i], tokens);
  3373. }
  3374. void parseIntoTokens( std::string const& arg, std::vector<Token>& tokens ) {
  3375. for( std::size_t i = 0; i <= arg.size(); ++i ) {
  3376. char c = arg[i];
  3377. if( c == '"' )
  3378. inQuotes = !inQuotes;
  3379. mode = handleMode( i, c, arg, tokens );
  3380. }
  3381. }
  3382. Mode handleMode( std::size_t i, char c, std::string const& arg, std::vector<Token>& tokens ) {
  3383. switch( mode ) {
  3384. case None: return handleNone( i, c );
  3385. case MaybeShortOpt: return handleMaybeShortOpt( i, c );
  3386. case ShortOpt:
  3387. case LongOpt:
  3388. case SlashOpt: return handleOpt( i, c, arg, tokens );
  3389. case Positional: return handlePositional( i, c, arg, tokens );
  3390. default: throw std::logic_error( "Unknown mode" );
  3391. }
  3392. }
  3393. Mode handleNone( std::size_t i, char c ) {
  3394. if( inQuotes ) {
  3395. from = i;
  3396. return Positional;
  3397. }
  3398. switch( c ) {
  3399. case '-': return MaybeShortOpt;
  3400. #ifdef CLARA_PLATFORM_WINDOWS
  3401. case '/': from = i+1; return SlashOpt;
  3402. #endif
  3403. default: from = i; return Positional;
  3404. }
  3405. }
  3406. Mode handleMaybeShortOpt( std::size_t i, char c ) {
  3407. switch( c ) {
  3408. case '-': from = i+1; return LongOpt;
  3409. default: from = i; return ShortOpt;
  3410. }
  3411. }
  3412. Mode handleOpt( std::size_t i, char c, std::string const& arg, std::vector<Token>& tokens ) {
  3413. if( std::string( " \t:=\0", 5 ).find( c ) == std::string::npos )
  3414. return mode;
  3415. std::string optName = arg.substr( from, i-from );
  3416. if( mode == ShortOpt )
  3417. for( std::size_t j = 0; j < optName.size(); ++j )
  3418. tokens.push_back( Token( Token::ShortOpt, optName.substr( j, 1 ) ) );
  3419. else if( mode == SlashOpt && optName.size() == 1 )
  3420. tokens.push_back( Token( Token::ShortOpt, optName ) );
  3421. else
  3422. tokens.push_back( Token( Token::LongOpt, optName ) );
  3423. return None;
  3424. }
  3425. Mode handlePositional( std::size_t i, char c, std::string const& arg, std::vector<Token>& tokens ) {
  3426. if( inQuotes || std::string( " \t\0", 3 ).find( c ) == std::string::npos )
  3427. return mode;
  3428. std::string data = arg.substr( from, i-from );
  3429. tokens.push_back( Token( Token::Positional, data ) );
  3430. return None;
  3431. }
  3432. };
  3433. template<typename ConfigT>
  3434. struct CommonArgProperties {
  3435. CommonArgProperties() {}
  3436. CommonArgProperties( Detail::BoundArgFunction<ConfigT> const& _boundField ) : boundField( _boundField ) {}
  3437. Detail::BoundArgFunction<ConfigT> boundField;
  3438. std::string description;
  3439. std::string detail;
  3440. std::string placeholder; // Only value if boundField takes an arg
  3441. bool takesArg() const {
  3442. return !placeholder.empty();
  3443. }
  3444. void validate() const {
  3445. if( !boundField.isSet() )
  3446. throw std::logic_error( "option not bound" );
  3447. }
  3448. };
  3449. struct OptionArgProperties {
  3450. std::vector<std::string> shortNames;
  3451. std::string longName;
  3452. bool hasShortName( std::string const& shortName ) const {
  3453. return std::find( shortNames.begin(), shortNames.end(), shortName ) != shortNames.end();
  3454. }
  3455. bool hasLongName( std::string const& _longName ) const {
  3456. return _longName == longName;
  3457. }
  3458. };
  3459. struct PositionalArgProperties {
  3460. PositionalArgProperties() : position( -1 ) {}
  3461. int position; // -1 means non-positional (floating)
  3462. bool isFixedPositional() const {
  3463. return position != -1;
  3464. }
  3465. };
  3466. template<typename ConfigT>
  3467. class CommandLine {
  3468. struct Arg : CommonArgProperties<ConfigT>, OptionArgProperties, PositionalArgProperties {
  3469. Arg() {}
  3470. Arg( Detail::BoundArgFunction<ConfigT> const& _boundField ) : CommonArgProperties<ConfigT>( _boundField ) {}
  3471. using CommonArgProperties<ConfigT>::placeholder; // !TBD
  3472. std::string dbgName() const {
  3473. if( !longName.empty() )
  3474. return "--" + longName;
  3475. if( !shortNames.empty() )
  3476. return "-" + shortNames[0];
  3477. return "positional args";
  3478. }
  3479. std::string commands() const {
  3480. std::ostringstream oss;
  3481. bool first = true;
  3482. std::vector<std::string>::const_iterator it = shortNames.begin(), itEnd = shortNames.end();
  3483. for(; it != itEnd; ++it ) {
  3484. if( first )
  3485. first = false;
  3486. else
  3487. oss << ", ";
  3488. oss << "-" << *it;
  3489. }
  3490. if( !longName.empty() ) {
  3491. if( !first )
  3492. oss << ", ";
  3493. oss << "--" << longName;
  3494. }
  3495. if( !placeholder.empty() )
  3496. oss << " <" << placeholder << ">";
  3497. return oss.str();
  3498. }
  3499. };
  3500. typedef CLARA_AUTO_PTR( Arg ) ArgAutoPtr;
  3501. friend void addOptName( Arg& arg, std::string const& optName )
  3502. {
  3503. if( optName.empty() )
  3504. return;
  3505. if( Detail::startsWith( optName, "--" ) ) {
  3506. if( !arg.longName.empty() )
  3507. throw std::logic_error( "Only one long opt may be specified. '"
  3508. + arg.longName
  3509. + "' already specified, now attempting to add '"
  3510. + optName + "'" );
  3511. arg.longName = optName.substr( 2 );
  3512. }
  3513. else if( Detail::startsWith( optName, "-" ) )
  3514. arg.shortNames.push_back( optName.substr( 1 ) );
  3515. else
  3516. throw std::logic_error( "option must begin with - or --. Option was: '" + optName + "'" );
  3517. }
  3518. friend void setPositionalArg( Arg& arg, int position )
  3519. {
  3520. arg.position = position;
  3521. }
  3522. class ArgBuilder {
  3523. public:
  3524. ArgBuilder( Arg* arg ) : m_arg( arg ) {}
  3525. // Bind a non-boolean data member (requires placeholder string)
  3526. template<typename C, typename M>
  3527. void bind( M C::* field, std::string const& placeholder ) {
  3528. m_arg->boundField = new Detail::BoundDataMember<C,M>( field );
  3529. m_arg->placeholder = placeholder;
  3530. }
  3531. // Bind a boolean data member (no placeholder required)
  3532. template<typename C>
  3533. void bind( bool C::* field ) {
  3534. m_arg->boundField = new Detail::BoundDataMember<C,bool>( field );
  3535. }
  3536. // Bind a method taking a single, non-boolean argument (requires a placeholder string)
  3537. template<typename C, typename M>
  3538. void bind( void (C::* unaryMethod)( M ), std::string const& placeholder ) {
  3539. m_arg->boundField = new Detail::BoundUnaryMethod<C,M>( unaryMethod );
  3540. m_arg->placeholder = placeholder;
  3541. }
  3542. // Bind a method taking a single, boolean argument (no placeholder string required)
  3543. template<typename C>
  3544. void bind( void (C::* unaryMethod)( bool ) ) {
  3545. m_arg->boundField = new Detail::BoundUnaryMethod<C,bool>( unaryMethod );
  3546. }
  3547. // Bind a method that takes no arguments (will be called if opt is present)
  3548. template<typename C>
  3549. void bind( void (C::* nullaryMethod)() ) {
  3550. m_arg->boundField = new Detail::BoundNullaryMethod<C>( nullaryMethod );
  3551. }
  3552. // Bind a free function taking a single argument - the object to operate on (no placeholder string required)
  3553. template<typename C>
  3554. void bind( void (* unaryFunction)( C& ) ) {
  3555. m_arg->boundField = new Detail::BoundUnaryFunction<C>( unaryFunction );
  3556. }
  3557. // Bind a free function taking a single argument - the object to operate on (requires a placeholder string)
  3558. template<typename C, typename T>
  3559. void bind( void (* binaryFunction)( C&, T ), std::string const& placeholder ) {
  3560. m_arg->boundField = new Detail::BoundBinaryFunction<C, T>( binaryFunction );
  3561. m_arg->placeholder = placeholder;
  3562. }
  3563. ArgBuilder& describe( std::string const& description ) {
  3564. m_arg->description = description;
  3565. return *this;
  3566. }
  3567. ArgBuilder& detail( std::string const& detail ) {
  3568. m_arg->detail = detail;
  3569. return *this;
  3570. }
  3571. protected:
  3572. Arg* m_arg;
  3573. };
  3574. class OptBuilder : public ArgBuilder {
  3575. public:
  3576. OptBuilder( Arg* arg ) : ArgBuilder( arg ) {}
  3577. OptBuilder( OptBuilder& other ) : ArgBuilder( other ) {}
  3578. OptBuilder& operator[]( std::string const& optName ) {
  3579. addOptName( *ArgBuilder::m_arg, optName );
  3580. return *this;
  3581. }
  3582. };
  3583. public:
  3584. CommandLine()
  3585. : m_boundProcessName( new Detail::NullBinder<ConfigT>() ),
  3586. m_highestSpecifiedArgPosition( 0 ),
  3587. m_throwOnUnrecognisedTokens( false )
  3588. {}
  3589. CommandLine( CommandLine const& other )
  3590. : m_boundProcessName( other.m_boundProcessName ),
  3591. m_options ( other.m_options ),
  3592. m_positionalArgs( other.m_positionalArgs ),
  3593. m_highestSpecifiedArgPosition( other.m_highestSpecifiedArgPosition ),
  3594. m_throwOnUnrecognisedTokens( other.m_throwOnUnrecognisedTokens )
  3595. {
  3596. if( other.m_floatingArg.get() )
  3597. m_floatingArg.reset( new Arg( *other.m_floatingArg ) );
  3598. }
  3599. CommandLine& setThrowOnUnrecognisedTokens( bool shouldThrow = true ) {
  3600. m_throwOnUnrecognisedTokens = shouldThrow;
  3601. return *this;
  3602. }
  3603. OptBuilder operator[]( std::string const& optName ) {
  3604. m_options.push_back( Arg() );
  3605. addOptName( m_options.back(), optName );
  3606. OptBuilder builder( &m_options.back() );
  3607. return builder;
  3608. }
  3609. ArgBuilder operator[]( int position ) {
  3610. m_positionalArgs.insert( std::make_pair( position, Arg() ) );
  3611. if( position > m_highestSpecifiedArgPosition )
  3612. m_highestSpecifiedArgPosition = position;
  3613. setPositionalArg( m_positionalArgs[position], position );
  3614. ArgBuilder builder( &m_positionalArgs[position] );
  3615. return builder;
  3616. }
  3617. // Invoke this with the _ instance
  3618. ArgBuilder operator[]( UnpositionalTag ) {
  3619. if( m_floatingArg.get() )
  3620. throw std::logic_error( "Only one unpositional argument can be added" );
  3621. m_floatingArg.reset( new Arg() );
  3622. ArgBuilder builder( m_floatingArg.get() );
  3623. return builder;
  3624. }
  3625. template<typename C, typename M>
  3626. void bindProcessName( M C::* field ) {
  3627. m_boundProcessName = new Detail::BoundDataMember<C,M>( field );
  3628. }
  3629. template<typename C, typename M>
  3630. void bindProcessName( void (C::*_unaryMethod)( M ) ) {
  3631. m_boundProcessName = new Detail::BoundUnaryMethod<C,M>( _unaryMethod );
  3632. }
  3633. void optUsage( std::ostream& os, std::size_t indent = 0, std::size_t width = Detail::consoleWidth ) const {
  3634. typename std::vector<Arg>::const_iterator itBegin = m_options.begin(), itEnd = m_options.end(), it;
  3635. std::size_t maxWidth = 0;
  3636. for( it = itBegin; it != itEnd; ++it )
  3637. maxWidth = (std::max)( maxWidth, it->commands().size() );
  3638. for( it = itBegin; it != itEnd; ++it ) {
  3639. Detail::Text usage( it->commands(), Detail::TextAttributes()
  3640. .setWidth( maxWidth+indent )
  3641. .setIndent( indent ) );
  3642. Detail::Text desc( it->description, Detail::TextAttributes()
  3643. .setWidth( width - maxWidth - 3 ) );
  3644. for( std::size_t i = 0; i < (std::max)( usage.size(), desc.size() ); ++i ) {
  3645. std::string usageCol = i < usage.size() ? usage[i] : "";
  3646. os << usageCol;
  3647. if( i < desc.size() && !desc[i].empty() )
  3648. os << std::string( indent + 2 + maxWidth - usageCol.size(), ' ' )
  3649. << desc[i];
  3650. os << "\n";
  3651. }
  3652. }
  3653. }
  3654. std::string optUsage() const {
  3655. std::ostringstream oss;
  3656. optUsage( oss );
  3657. return oss.str();
  3658. }
  3659. void argSynopsis( std::ostream& os ) const {
  3660. for( int i = 1; i <= m_highestSpecifiedArgPosition; ++i ) {
  3661. if( i > 1 )
  3662. os << " ";
  3663. typename std::map<int, Arg>::const_iterator it = m_positionalArgs.find( i );
  3664. if( it != m_positionalArgs.end() )
  3665. os << "<" << it->second.placeholder << ">";
  3666. else if( m_floatingArg.get() )
  3667. os << "<" << m_floatingArg->placeholder << ">";
  3668. else
  3669. throw std::logic_error( "non consecutive positional arguments with no floating args" );
  3670. }
  3671. // !TBD No indication of mandatory args
  3672. if( m_floatingArg.get() ) {
  3673. if( m_highestSpecifiedArgPosition > 1 )
  3674. os << " ";
  3675. os << "[<" << m_floatingArg->placeholder << "> ...]";
  3676. }
  3677. }
  3678. std::string argSynopsis() const {
  3679. std::ostringstream oss;
  3680. argSynopsis( oss );
  3681. return oss.str();
  3682. }
  3683. void usage( std::ostream& os, std::string const& procName ) const {
  3684. validate();
  3685. os << "usage:\n " << procName << " ";
  3686. argSynopsis( os );
  3687. if( !m_options.empty() ) {
  3688. os << " [options]\n\nwhere options are: \n";
  3689. optUsage( os, 2 );
  3690. }
  3691. os << "\n";
  3692. }
  3693. std::string usage( std::string const& procName ) const {
  3694. std::ostringstream oss;
  3695. usage( oss, procName );
  3696. return oss.str();
  3697. }
  3698. ConfigT parse( std::vector<std::string> const& args ) const {
  3699. ConfigT config;
  3700. parseInto( args, config );
  3701. return config;
  3702. }
  3703. std::vector<Parser::Token> parseInto( std::vector<std::string> const& args, ConfigT& config ) const {
  3704. std::string processName = args[0];
  3705. std::size_t lastSlash = processName.find_last_of( "/\\" );
  3706. if( lastSlash != std::string::npos )
  3707. processName = processName.substr( lastSlash+1 );
  3708. m_boundProcessName.set( config, processName );
  3709. std::vector<Parser::Token> tokens;
  3710. Parser parser;
  3711. parser.parseIntoTokens( args, tokens );
  3712. return populate( tokens, config );
  3713. }
  3714. std::vector<Parser::Token> populate( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {
  3715. validate();
  3716. std::vector<Parser::Token> unusedTokens = populateOptions( tokens, config );
  3717. unusedTokens = populateFixedArgs( unusedTokens, config );
  3718. unusedTokens = populateFloatingArgs( unusedTokens, config );
  3719. return unusedTokens;
  3720. }
  3721. std::vector<Parser::Token> populateOptions( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {
  3722. std::vector<Parser::Token> unusedTokens;
  3723. std::vector<std::string> errors;
  3724. for( std::size_t i = 0; i < tokens.size(); ++i ) {
  3725. Parser::Token const& token = tokens[i];
  3726. typename std::vector<Arg>::const_iterator it = m_options.begin(), itEnd = m_options.end();
  3727. for(; it != itEnd; ++it ) {
  3728. Arg const& arg = *it;
  3729. try {
  3730. if( ( token.type == Parser::Token::ShortOpt && arg.hasShortName( token.data ) ) ||
  3731. ( token.type == Parser::Token::LongOpt && arg.hasLongName( token.data ) ) ) {
  3732. if( arg.takesArg() ) {
  3733. if( i == tokens.size()-1 || tokens[i+1].type != Parser::Token::Positional )
  3734. errors.push_back( "Expected argument to option: " + token.data );
  3735. else
  3736. arg.boundField.set( config, tokens[++i].data );
  3737. }
  3738. else {
  3739. arg.boundField.set( config, "true" );
  3740. }
  3741. break;
  3742. }
  3743. }
  3744. catch( std::exception& ex ) {
  3745. errors.push_back( std::string( ex.what() ) + "\n- while parsing: (" + arg.commands() + ")" );
  3746. }
  3747. }
  3748. if( it == itEnd ) {
  3749. if( token.type == Parser::Token::Positional || !m_throwOnUnrecognisedTokens )
  3750. unusedTokens.push_back( token );
  3751. else if( errors.empty() && m_throwOnUnrecognisedTokens )
  3752. errors.push_back( "unrecognised option: " + token.data );
  3753. }
  3754. }
  3755. if( !errors.empty() ) {
  3756. std::ostringstream oss;
  3757. for( std::vector<std::string>::const_iterator it = errors.begin(), itEnd = errors.end();
  3758. it != itEnd;
  3759. ++it ) {
  3760. if( it != errors.begin() )
  3761. oss << "\n";
  3762. oss << *it;
  3763. }
  3764. throw std::runtime_error( oss.str() );
  3765. }
  3766. return unusedTokens;
  3767. }
  3768. std::vector<Parser::Token> populateFixedArgs( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {
  3769. std::vector<Parser::Token> unusedTokens;
  3770. int position = 1;
  3771. for( std::size_t i = 0; i < tokens.size(); ++i ) {
  3772. Parser::Token const& token = tokens[i];
  3773. typename std::map<int, Arg>::const_iterator it = m_positionalArgs.find( position );
  3774. if( it != m_positionalArgs.end() )
  3775. it->second.boundField.set( config, token.data );
  3776. else
  3777. unusedTokens.push_back( token );
  3778. if( token.type == Parser::Token::Positional )
  3779. position++;
  3780. }
  3781. return unusedTokens;
  3782. }
  3783. std::vector<Parser::Token> populateFloatingArgs( std::vector<Parser::Token> const& tokens, ConfigT& config ) const {
  3784. if( !m_floatingArg.get() )
  3785. return tokens;
  3786. std::vector<Parser::Token> unusedTokens;
  3787. for( std::size_t i = 0; i < tokens.size(); ++i ) {
  3788. Parser::Token const& token = tokens[i];
  3789. if( token.type == Parser::Token::Positional )
  3790. m_floatingArg->boundField.set( config, token.data );
  3791. else
  3792. unusedTokens.push_back( token );
  3793. }
  3794. return unusedTokens;
  3795. }
  3796. void validate() const
  3797. {
  3798. if( m_options.empty() && m_positionalArgs.empty() && !m_floatingArg.get() )
  3799. throw std::logic_error( "No options or arguments specified" );
  3800. for( typename std::vector<Arg>::const_iterator it = m_options.begin(),
  3801. itEnd = m_options.end();
  3802. it != itEnd; ++it )
  3803. it->validate();
  3804. }
  3805. private:
  3806. Detail::BoundArgFunction<ConfigT> m_boundProcessName;
  3807. std::vector<Arg> m_options;
  3808. std::map<int, Arg> m_positionalArgs;
  3809. ArgAutoPtr m_floatingArg;
  3810. int m_highestSpecifiedArgPosition;
  3811. bool m_throwOnUnrecognisedTokens;
  3812. };
  3813. } // end namespace Clara
  3814. STITCH_CLARA_CLOSE_NAMESPACE
  3815. #undef STITCH_CLARA_OPEN_NAMESPACE
  3816. #undef STITCH_CLARA_CLOSE_NAMESPACE
  3817. #endif // TWOBLUECUBES_CLARA_H_INCLUDED
  3818. #undef STITCH_CLARA_OPEN_NAMESPACE
  3819. // Restore Clara's value for console width, if present
  3820. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  3821. #define CLARA_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  3822. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  3823. #endif
  3824. #include <fstream>
  3825. namespace Catch {
  3826. inline void abortAfterFirst( ConfigData& config ) { config.abortAfter = 1; }
  3827. inline void abortAfterX( ConfigData& config, int x ) {
  3828. if( x < 1 )
  3829. throw std::runtime_error( "Value after -x or --abortAfter must be greater than zero" );
  3830. config.abortAfter = x;
  3831. }
  3832. inline void addTestOrTags( ConfigData& config, std::string const& _testSpec ) { config.testsOrTags.push_back( _testSpec ); }
  3833. inline void addReporterName( ConfigData& config, std::string const& _reporterName ) { config.reporterNames.push_back( _reporterName ); }
  3834. inline void addWarning( ConfigData& config, std::string const& _warning ) {
  3835. if( _warning == "NoAssertions" )
  3836. config.warnings = static_cast<WarnAbout::What>( config.warnings | WarnAbout::NoAssertions );
  3837. else
  3838. throw std::runtime_error( "Unrecognised warning: '" + _warning + "'" );
  3839. }
  3840. inline void setOrder( ConfigData& config, std::string const& order ) {
  3841. if( startsWith( "declared", order ) )
  3842. config.runOrder = RunTests::InDeclarationOrder;
  3843. else if( startsWith( "lexical", order ) )
  3844. config.runOrder = RunTests::InLexicographicalOrder;
  3845. else if( startsWith( "random", order ) )
  3846. config.runOrder = RunTests::InRandomOrder;
  3847. else
  3848. throw std::runtime_error( "Unrecognised ordering: '" + order + "'" );
  3849. }
  3850. inline void setRngSeed( ConfigData& config, std::string const& seed ) {
  3851. if( seed == "time" ) {
  3852. config.rngSeed = static_cast<unsigned int>( std::time(0) );
  3853. }
  3854. else {
  3855. std::stringstream ss;
  3856. ss << seed;
  3857. ss >> config.rngSeed;
  3858. if( ss.fail() )
  3859. throw std::runtime_error( "Argment to --rng-seed should be the word 'time' or a number" );
  3860. }
  3861. }
  3862. inline void setVerbosity( ConfigData& config, int level ) {
  3863. // !TBD: accept strings?
  3864. config.verbosity = static_cast<Verbosity::Level>( level );
  3865. }
  3866. inline void setShowDurations( ConfigData& config, bool _showDurations ) {
  3867. config.showDurations = _showDurations
  3868. ? ShowDurations::Always
  3869. : ShowDurations::Never;
  3870. }
  3871. inline void setUseColour( ConfigData& config, std::string const& value ) {
  3872. std::string mode = toLower( value );
  3873. if( mode == "yes" )
  3874. config.useColour = UseColour::Yes;
  3875. else if( mode == "no" )
  3876. config.useColour = UseColour::No;
  3877. else if( mode == "auto" )
  3878. config.useColour = UseColour::Auto;
  3879. else
  3880. throw std::runtime_error( "colour mode must be one of: auto, yes or no" );
  3881. }
  3882. inline void forceColour( ConfigData& config ) {
  3883. config.useColour = UseColour::Yes;
  3884. }
  3885. inline void loadTestNamesFromFile( ConfigData& config, std::string const& _filename ) {
  3886. std::ifstream f( _filename.c_str() );
  3887. if( !f.is_open() )
  3888. throw std::domain_error( "Unable to load input file: " + _filename );
  3889. std::string line;
  3890. while( std::getline( f, line ) ) {
  3891. line = trim(line);
  3892. if( !line.empty() && !startsWith( line, "#" ) )
  3893. addTestOrTags( config, "\"" + line + "\"," );
  3894. }
  3895. }
  3896. inline Clara::CommandLine<ConfigData> makeCommandLineParser() {
  3897. using namespace Clara;
  3898. CommandLine<ConfigData> cli;
  3899. cli.bindProcessName( &ConfigData::processName );
  3900. cli["-?"]["-h"]["--help"]
  3901. .describe( "display usage information" )
  3902. .bind( &ConfigData::showHelp );
  3903. cli["-l"]["--list-tests"]
  3904. .describe( "list all/matching test cases" )
  3905. .bind( &ConfigData::listTests );
  3906. cli["-t"]["--list-tags"]
  3907. .describe( "list all/matching tags" )
  3908. .bind( &ConfigData::listTags );
  3909. cli["-s"]["--success"]
  3910. .describe( "include successful tests in output" )
  3911. .bind( &ConfigData::showSuccessfulTests );
  3912. cli["-b"]["--break"]
  3913. .describe( "break into debugger on failure" )
  3914. .bind( &ConfigData::shouldDebugBreak );
  3915. cli["-e"]["--nothrow"]
  3916. .describe( "skip exception tests" )
  3917. .bind( &ConfigData::noThrow );
  3918. cli["-i"]["--invisibles"]
  3919. .describe( "show invisibles (tabs, newlines)" )
  3920. .bind( &ConfigData::showInvisibles );
  3921. cli["-o"]["--out"]
  3922. .describe( "output filename" )
  3923. .bind( &ConfigData::outputFilename, "filename" );
  3924. cli["-r"]["--reporter"]
  3925. // .placeholder( "name[:filename]" )
  3926. .describe( "reporter to use (defaults to console)" )
  3927. .bind( &addReporterName, "name" );
  3928. cli["-n"]["--name"]
  3929. .describe( "suite name" )
  3930. .bind( &ConfigData::name, "name" );
  3931. cli["-a"]["--abort"]
  3932. .describe( "abort at first failure" )
  3933. .bind( &abortAfterFirst );
  3934. cli["-x"]["--abortx"]
  3935. .describe( "abort after x failures" )
  3936. .bind( &abortAfterX, "no. failures" );
  3937. cli["-w"]["--warn"]
  3938. .describe( "enable warnings" )
  3939. .bind( &addWarning, "warning name" );
  3940. // - needs updating if reinstated
  3941. // cli.into( &setVerbosity )
  3942. // .describe( "level of verbosity (0=no output)" )
  3943. // .shortOpt( "v")
  3944. // .longOpt( "verbosity" )
  3945. // .placeholder( "level" );
  3946. cli[_]
  3947. .describe( "which test or tests to use" )
  3948. .bind( &addTestOrTags, "test name, pattern or tags" );
  3949. cli["-d"]["--durations"]
  3950. .describe( "show test durations" )
  3951. .bind( &setShowDurations, "yes|no" );
  3952. cli["-f"]["--input-file"]
  3953. .describe( "load test names to run from a file" )
  3954. .bind( &loadTestNamesFromFile, "filename" );
  3955. cli["-#"]["--filenames-as-tags"]
  3956. .describe( "adds a tag for the filename" )
  3957. .bind( &ConfigData::filenamesAsTags );
  3958. // Less common commands which don't have a short form
  3959. cli["--list-test-names-only"]
  3960. .describe( "list all/matching test cases names only" )
  3961. .bind( &ConfigData::listTestNamesOnly );
  3962. cli["--list-reporters"]
  3963. .describe( "list all reporters" )
  3964. .bind( &ConfigData::listReporters );
  3965. cli["--order"]
  3966. .describe( "test case order (defaults to decl)" )
  3967. .bind( &setOrder, "decl|lex|rand" );
  3968. cli["--rng-seed"]
  3969. .describe( "set a specific seed for random numbers" )
  3970. .bind( &setRngSeed, "'time'|number" );
  3971. cli["--force-colour"]
  3972. .describe( "force colourised output (deprecated)" )
  3973. .bind( &forceColour );
  3974. cli["--use-colour"]
  3975. .describe( "should output be colourised" )
  3976. .bind( &setUseColour, "yes|no" );
  3977. return cli;
  3978. }
  3979. } // end namespace Catch
  3980. // #included from: internal/catch_list.hpp
  3981. #define TWOBLUECUBES_CATCH_LIST_HPP_INCLUDED
  3982. // #included from: catch_text.h
  3983. #define TWOBLUECUBES_CATCH_TEXT_H_INCLUDED
  3984. #define TBC_TEXT_FORMAT_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH
  3985. #define CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE Catch
  3986. // #included from: ../external/tbc_text_format.h
  3987. // Only use header guard if we are not using an outer namespace
  3988. #ifndef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
  3989. # ifdef TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED
  3990. # ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
  3991. # define TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
  3992. # endif
  3993. # else
  3994. # define TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED
  3995. # endif
  3996. #endif
  3997. #ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
  3998. #include <string>
  3999. #include <vector>
  4000. #include <sstream>
  4001. // Use optional outer namespace
  4002. #ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
  4003. namespace CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE {
  4004. #endif
  4005. namespace Tbc {
  4006. #ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH
  4007. const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH;
  4008. #else
  4009. const unsigned int consoleWidth = 80;
  4010. #endif
  4011. struct TextAttributes {
  4012. TextAttributes()
  4013. : initialIndent( std::string::npos ),
  4014. indent( 0 ),
  4015. width( consoleWidth-1 ),
  4016. tabChar( '\t' )
  4017. {}
  4018. TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; }
  4019. TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; }
  4020. TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; }
  4021. TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; }
  4022. std::size_t initialIndent; // indent of first line, or npos
  4023. std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos
  4024. std::size_t width; // maximum width of text, including indent. Longer text will wrap
  4025. char tabChar; // If this char is seen the indent is changed to current pos
  4026. };
  4027. class Text {
  4028. public:
  4029. Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() )
  4030. : attr( _attr )
  4031. {
  4032. std::string wrappableChars = " [({.,/|\\-";
  4033. std::size_t indent = _attr.initialIndent != std::string::npos
  4034. ? _attr.initialIndent
  4035. : _attr.indent;
  4036. std::string remainder = _str;
  4037. while( !remainder.empty() ) {
  4038. if( lines.size() >= 1000 ) {
  4039. lines.push_back( "... message truncated due to excessive size" );
  4040. return;
  4041. }
  4042. std::size_t tabPos = std::string::npos;
  4043. std::size_t width = (std::min)( remainder.size(), _attr.width - indent );
  4044. std::size_t pos = remainder.find_first_of( '\n' );
  4045. if( pos <= width ) {
  4046. width = pos;
  4047. }
  4048. pos = remainder.find_last_of( _attr.tabChar, width );
  4049. if( pos != std::string::npos ) {
  4050. tabPos = pos;
  4051. if( remainder[width] == '\n' )
  4052. width--;
  4053. remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 );
  4054. }
  4055. if( width == remainder.size() ) {
  4056. spliceLine( indent, remainder, width );
  4057. }
  4058. else if( remainder[width] == '\n' ) {
  4059. spliceLine( indent, remainder, width );
  4060. if( width <= 1 || remainder.size() != 1 )
  4061. remainder = remainder.substr( 1 );
  4062. indent = _attr.indent;
  4063. }
  4064. else {
  4065. pos = remainder.find_last_of( wrappableChars, width );
  4066. if( pos != std::string::npos && pos > 0 ) {
  4067. spliceLine( indent, remainder, pos );
  4068. if( remainder[0] == ' ' )
  4069. remainder = remainder.substr( 1 );
  4070. }
  4071. else {
  4072. spliceLine( indent, remainder, width-1 );
  4073. lines.back() += "-";
  4074. }
  4075. if( lines.size() == 1 )
  4076. indent = _attr.indent;
  4077. if( tabPos != std::string::npos )
  4078. indent += tabPos;
  4079. }
  4080. }
  4081. }
  4082. void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) {
  4083. lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) );
  4084. _remainder = _remainder.substr( _pos );
  4085. }
  4086. typedef std::vector<std::string>::const_iterator const_iterator;
  4087. const_iterator begin() const { return lines.begin(); }
  4088. const_iterator end() const { return lines.end(); }
  4089. std::string const& last() const { return lines.back(); }
  4090. std::size_t size() const { return lines.size(); }
  4091. std::string const& operator[]( std::size_t _index ) const { return lines[_index]; }
  4092. std::string toString() const {
  4093. std::ostringstream oss;
  4094. oss << *this;
  4095. return oss.str();
  4096. }
  4097. inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) {
  4098. for( Text::const_iterator it = _text.begin(), itEnd = _text.end();
  4099. it != itEnd; ++it ) {
  4100. if( it != _text.begin() )
  4101. _stream << "\n";
  4102. _stream << *it;
  4103. }
  4104. return _stream;
  4105. }
  4106. private:
  4107. std::string str;
  4108. TextAttributes attr;
  4109. std::vector<std::string> lines;
  4110. };
  4111. } // end namespace Tbc
  4112. #ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
  4113. } // end outer namespace
  4114. #endif
  4115. #endif // TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED
  4116. #undef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE
  4117. namespace Catch {
  4118. using Tbc::Text;
  4119. using Tbc::TextAttributes;
  4120. }
  4121. // #included from: catch_console_colour.hpp
  4122. #define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_HPP_INCLUDED
  4123. namespace Catch {
  4124. struct Colour {
  4125. enum Code {
  4126. None = 0,
  4127. White,
  4128. Red,
  4129. Green,
  4130. Blue,
  4131. Cyan,
  4132. Yellow,
  4133. Grey,
  4134. Bright = 0x10,
  4135. BrightRed = Bright | Red,
  4136. BrightGreen = Bright | Green,
  4137. LightGrey = Bright | Grey,
  4138. BrightWhite = Bright | White,
  4139. // By intention
  4140. FileName = LightGrey,
  4141. Warning = Yellow,
  4142. ResultError = BrightRed,
  4143. ResultSuccess = BrightGreen,
  4144. ResultExpectedFailure = Warning,
  4145. Error = BrightRed,
  4146. Success = Green,
  4147. OriginalExpression = Cyan,
  4148. ReconstructedExpression = Yellow,
  4149. SecondaryText = LightGrey,
  4150. Headers = White
  4151. };
  4152. // Use constructed object for RAII guard
  4153. Colour( Code _colourCode );
  4154. Colour( Colour const& other );
  4155. ~Colour();
  4156. // Use static method for one-shot changes
  4157. static void use( Code _colourCode );
  4158. private:
  4159. bool m_moved;
  4160. };
  4161. inline std::ostream& operator << ( std::ostream& os, Colour const& ) { return os; }
  4162. } // end namespace Catch
  4163. // #included from: catch_interfaces_reporter.h
  4164. #define TWOBLUECUBES_CATCH_INTERFACES_REPORTER_H_INCLUDED
  4165. #include <string>
  4166. #include <ostream>
  4167. #include <map>
  4168. #include <assert.h>
  4169. namespace Catch
  4170. {
  4171. struct ReporterConfig {
  4172. explicit ReporterConfig( Ptr<IConfig const> const& _fullConfig )
  4173. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  4174. ReporterConfig( Ptr<IConfig const> const& _fullConfig, std::ostream& _stream )
  4175. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  4176. std::ostream& stream() const { return *m_stream; }
  4177. Ptr<IConfig const> fullConfig() const { return m_fullConfig; }
  4178. private:
  4179. std::ostream* m_stream;
  4180. Ptr<IConfig const> m_fullConfig;
  4181. };
  4182. struct ReporterPreferences {
  4183. ReporterPreferences()
  4184. : shouldRedirectStdOut( false )
  4185. {}
  4186. bool shouldRedirectStdOut;
  4187. };
  4188. template<typename T>
  4189. struct LazyStat : Option<T> {
  4190. LazyStat() : used( false ) {}
  4191. LazyStat& operator=( T const& _value ) {
  4192. Option<T>::operator=( _value );
  4193. used = false;
  4194. return *this;
  4195. }
  4196. void reset() {
  4197. Option<T>::reset();
  4198. used = false;
  4199. }
  4200. bool used;
  4201. };
  4202. struct TestRunInfo {
  4203. TestRunInfo( std::string const& _name ) : name( _name ) {}
  4204. std::string name;
  4205. };
  4206. struct GroupInfo {
  4207. GroupInfo( std::string const& _name,
  4208. std::size_t _groupIndex,
  4209. std::size_t _groupsCount )
  4210. : name( _name ),
  4211. groupIndex( _groupIndex ),
  4212. groupsCounts( _groupsCount )
  4213. {}
  4214. std::string name;
  4215. std::size_t groupIndex;
  4216. std::size_t groupsCounts;
  4217. };
  4218. struct AssertionStats {
  4219. AssertionStats( AssertionResult const& _assertionResult,
  4220. std::vector<MessageInfo> const& _infoMessages,
  4221. Totals const& _totals )
  4222. : assertionResult( _assertionResult ),
  4223. infoMessages( _infoMessages ),
  4224. totals( _totals )
  4225. {
  4226. if( assertionResult.hasMessage() ) {
  4227. // Copy message into messages list.
  4228. // !TBD This should have been done earlier, somewhere
  4229. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  4230. builder << assertionResult.getMessage();
  4231. builder.m_info.message = builder.m_stream.str();
  4232. infoMessages.push_back( builder.m_info );
  4233. }
  4234. }
  4235. virtual ~AssertionStats();
  4236. # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
  4237. AssertionStats( AssertionStats const& ) = default;
  4238. AssertionStats( AssertionStats && ) = default;
  4239. AssertionStats& operator = ( AssertionStats const& ) = default;
  4240. AssertionStats& operator = ( AssertionStats && ) = default;
  4241. # endif
  4242. AssertionResult assertionResult;
  4243. std::vector<MessageInfo> infoMessages;
  4244. Totals totals;
  4245. };
  4246. struct SectionStats {
  4247. SectionStats( SectionInfo const& _sectionInfo,
  4248. Counts const& _assertions,
  4249. double _durationInSeconds,
  4250. bool _missingAssertions )
  4251. : sectionInfo( _sectionInfo ),
  4252. assertions( _assertions ),
  4253. durationInSeconds( _durationInSeconds ),
  4254. missingAssertions( _missingAssertions )
  4255. {}
  4256. virtual ~SectionStats();
  4257. # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
  4258. SectionStats( SectionStats const& ) = default;
  4259. SectionStats( SectionStats && ) = default;
  4260. SectionStats& operator = ( SectionStats const& ) = default;
  4261. SectionStats& operator = ( SectionStats && ) = default;
  4262. # endif
  4263. SectionInfo sectionInfo;
  4264. Counts assertions;
  4265. double durationInSeconds;
  4266. bool missingAssertions;
  4267. };
  4268. struct TestCaseStats {
  4269. TestCaseStats( TestCaseInfo const& _testInfo,
  4270. Totals const& _totals,
  4271. std::string const& _stdOut,
  4272. std::string const& _stdErr,
  4273. bool _aborting )
  4274. : testInfo( _testInfo ),
  4275. totals( _totals ),
  4276. stdOut( _stdOut ),
  4277. stdErr( _stdErr ),
  4278. aborting( _aborting )
  4279. {}
  4280. virtual ~TestCaseStats();
  4281. # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
  4282. TestCaseStats( TestCaseStats const& ) = default;
  4283. TestCaseStats( TestCaseStats && ) = default;
  4284. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  4285. TestCaseStats& operator = ( TestCaseStats && ) = default;
  4286. # endif
  4287. TestCaseInfo testInfo;
  4288. Totals totals;
  4289. std::string stdOut;
  4290. std::string stdErr;
  4291. bool aborting;
  4292. };
  4293. struct TestGroupStats {
  4294. TestGroupStats( GroupInfo const& _groupInfo,
  4295. Totals const& _totals,
  4296. bool _aborting )
  4297. : groupInfo( _groupInfo ),
  4298. totals( _totals ),
  4299. aborting( _aborting )
  4300. {}
  4301. TestGroupStats( GroupInfo const& _groupInfo )
  4302. : groupInfo( _groupInfo ),
  4303. aborting( false )
  4304. {}
  4305. virtual ~TestGroupStats();
  4306. # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS
  4307. TestGroupStats( TestGroupStats const& ) = default;
  4308. TestGroupStats( TestGroupStats && ) = default;
  4309. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  4310. TestGroupStats& operator = ( TestGroupStats && ) = default;
  4311. # endif
  4312. GroupInfo groupInfo;
  4313. Totals totals;
  4314. bool aborting;
  4315. };
  4316. struct TestRunStats {
  4317. TestRunStats( TestRunInfo const& _runInfo,
  4318. Totals const& _totals,
  4319. bool _aborting )
  4320. : runInfo( _runInfo ),
  4321. totals( _totals ),
  4322. aborting( _aborting )
  4323. {}
  4324. virtual ~TestRunStats();
  4325. # ifndef CATCH_CONFIG_CPP11_GENERATED_METHODS
  4326. TestRunStats( TestRunStats const& _other )
  4327. : runInfo( _other.runInfo ),
  4328. totals( _other.totals ),
  4329. aborting( _other.aborting )
  4330. {}
  4331. # else
  4332. TestRunStats( TestRunStats const& ) = default;
  4333. TestRunStats( TestRunStats && ) = default;
  4334. TestRunStats& operator = ( TestRunStats const& ) = default;
  4335. TestRunStats& operator = ( TestRunStats && ) = default;
  4336. # endif
  4337. TestRunInfo runInfo;
  4338. Totals totals;
  4339. bool aborting;
  4340. };
  4341. struct IStreamingReporter : IShared {
  4342. virtual ~IStreamingReporter();
  4343. // Implementing class must also provide the following static method:
  4344. // static std::string getDescription();
  4345. virtual ReporterPreferences getPreferences() const = 0;
  4346. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  4347. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  4348. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  4349. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  4350. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  4351. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  4352. // The return value indicates if the messages buffer should be cleared:
  4353. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  4354. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  4355. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  4356. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  4357. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  4358. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  4359. };
  4360. struct IReporterFactory : IShared {
  4361. virtual ~IReporterFactory();
  4362. virtual IStreamingReporter* create( ReporterConfig const& config ) const = 0;
  4363. virtual std::string getDescription() const = 0;
  4364. };
  4365. struct IReporterRegistry {
  4366. typedef std::map<std::string, Ptr<IReporterFactory> > FactoryMap;
  4367. typedef std::vector<Ptr<IReporterFactory> > Listeners;
  4368. virtual ~IReporterRegistry();
  4369. virtual IStreamingReporter* create( std::string const& name, Ptr<IConfig const> const& config ) const = 0;
  4370. virtual FactoryMap const& getFactories() const = 0;
  4371. virtual Listeners const& getListeners() const = 0;
  4372. };
  4373. Ptr<IStreamingReporter> addReporter( Ptr<IStreamingReporter> const& existingReporter, Ptr<IStreamingReporter> const& additionalReporter );
  4374. }
  4375. #include <limits>
  4376. #include <algorithm>
  4377. namespace Catch {
  4378. inline std::size_t listTests( Config const& config ) {
  4379. TestSpec testSpec = config.testSpec();
  4380. if( config.testSpec().hasFilters() )
  4381. Catch::cout() << "Matching test cases:\n";
  4382. else {
  4383. Catch::cout() << "All available test cases:\n";
  4384. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  4385. }
  4386. std::size_t matchedTests = 0;
  4387. TextAttributes nameAttr, tagsAttr;
  4388. nameAttr.setInitialIndent( 2 ).setIndent( 4 );
  4389. tagsAttr.setIndent( 6 );
  4390. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  4391. for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();
  4392. it != itEnd;
  4393. ++it ) {
  4394. matchedTests++;
  4395. TestCaseInfo const& testCaseInfo = it->getTestCaseInfo();
  4396. Colour::Code colour = testCaseInfo.isHidden()
  4397. ? Colour::SecondaryText
  4398. : Colour::None;
  4399. Colour colourGuard( colour );
  4400. Catch::cout() << Text( testCaseInfo.name, nameAttr ) << std::endl;
  4401. if( !testCaseInfo.tags.empty() )
  4402. Catch::cout() << Text( testCaseInfo.tagsAsString, tagsAttr ) << std::endl;
  4403. }
  4404. if( !config.testSpec().hasFilters() )
  4405. Catch::cout() << pluralise( matchedTests, "test case" ) << "\n" << std::endl;
  4406. else
  4407. Catch::cout() << pluralise( matchedTests, "matching test case" ) << "\n" << std::endl;
  4408. return matchedTests;
  4409. }
  4410. inline std::size_t listTestsNamesOnly( Config const& config ) {
  4411. TestSpec testSpec = config.testSpec();
  4412. if( !config.testSpec().hasFilters() )
  4413. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  4414. std::size_t matchedTests = 0;
  4415. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  4416. for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();
  4417. it != itEnd;
  4418. ++it ) {
  4419. matchedTests++;
  4420. TestCaseInfo const& testCaseInfo = it->getTestCaseInfo();
  4421. Catch::cout() << testCaseInfo.name << std::endl;
  4422. }
  4423. return matchedTests;
  4424. }
  4425. struct TagInfo {
  4426. TagInfo() : count ( 0 ) {}
  4427. void add( std::string const& spelling ) {
  4428. ++count;
  4429. spellings.insert( spelling );
  4430. }
  4431. std::string all() const {
  4432. std::string out;
  4433. for( std::set<std::string>::const_iterator it = spellings.begin(), itEnd = spellings.end();
  4434. it != itEnd;
  4435. ++it )
  4436. out += "[" + *it + "]";
  4437. return out;
  4438. }
  4439. std::set<std::string> spellings;
  4440. std::size_t count;
  4441. };
  4442. inline std::size_t listTags( Config const& config ) {
  4443. TestSpec testSpec = config.testSpec();
  4444. if( config.testSpec().hasFilters() )
  4445. Catch::cout() << "Tags for matching test cases:\n";
  4446. else {
  4447. Catch::cout() << "All available tags:\n";
  4448. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  4449. }
  4450. std::map<std::string, TagInfo> tagCounts;
  4451. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  4452. for( std::vector<TestCase>::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end();
  4453. it != itEnd;
  4454. ++it ) {
  4455. for( std::set<std::string>::const_iterator tagIt = it->getTestCaseInfo().tags.begin(),
  4456. tagItEnd = it->getTestCaseInfo().tags.end();
  4457. tagIt != tagItEnd;
  4458. ++tagIt ) {
  4459. std::string tagName = *tagIt;
  4460. std::string lcaseTagName = toLower( tagName );
  4461. std::map<std::string, TagInfo>::iterator countIt = tagCounts.find( lcaseTagName );
  4462. if( countIt == tagCounts.end() )
  4463. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  4464. countIt->second.add( tagName );
  4465. }
  4466. }
  4467. for( std::map<std::string, TagInfo>::const_iterator countIt = tagCounts.begin(),
  4468. countItEnd = tagCounts.end();
  4469. countIt != countItEnd;
  4470. ++countIt ) {
  4471. std::ostringstream oss;
  4472. oss << " " << std::setw(2) << countIt->second.count << " ";
  4473. Text wrapper( countIt->second.all(), TextAttributes()
  4474. .setInitialIndent( 0 )
  4475. .setIndent( oss.str().size() )
  4476. .setWidth( CATCH_CONFIG_CONSOLE_WIDTH-10 ) );
  4477. Catch::cout() << oss.str() << wrapper << "\n";
  4478. }
  4479. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << "\n" << std::endl;
  4480. return tagCounts.size();
  4481. }
  4482. inline std::size_t listReporters( Config const& /*config*/ ) {
  4483. Catch::cout() << "Available reporters:\n";
  4484. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  4485. IReporterRegistry::FactoryMap::const_iterator itBegin = factories.begin(), itEnd = factories.end(), it;
  4486. std::size_t maxNameLen = 0;
  4487. for(it = itBegin; it != itEnd; ++it )
  4488. maxNameLen = (std::max)( maxNameLen, it->first.size() );
  4489. for(it = itBegin; it != itEnd; ++it ) {
  4490. Text wrapper( it->second->getDescription(), TextAttributes()
  4491. .setInitialIndent( 0 )
  4492. .setIndent( 7+maxNameLen )
  4493. .setWidth( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) );
  4494. Catch::cout() << " "
  4495. << it->first
  4496. << ":"
  4497. << std::string( maxNameLen - it->first.size() + 2, ' ' )
  4498. << wrapper << "\n";
  4499. }
  4500. Catch::cout() << std::endl;
  4501. return factories.size();
  4502. }
  4503. inline Option<std::size_t> list( Config const& config ) {
  4504. Option<std::size_t> listedCount;
  4505. if( config.listTests() )
  4506. listedCount = listedCount.valueOr(0) + listTests( config );
  4507. if( config.listTestNamesOnly() )
  4508. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
  4509. if( config.listTags() )
  4510. listedCount = listedCount.valueOr(0) + listTags( config );
  4511. if( config.listReporters() )
  4512. listedCount = listedCount.valueOr(0) + listReporters( config );
  4513. return listedCount;
  4514. }
  4515. } // end namespace Catch
  4516. // #included from: internal/catch_run_context.hpp
  4517. #define TWOBLUECUBES_CATCH_RUNNER_IMPL_HPP_INCLUDED
  4518. // #included from: catch_test_case_tracker.hpp
  4519. #define TWOBLUECUBES_CATCH_TEST_CASE_TRACKER_HPP_INCLUDED
  4520. #include <map>
  4521. #include <string>
  4522. #include <assert.h>
  4523. #include <vector>
  4524. namespace Catch {
  4525. namespace TestCaseTracking {
  4526. struct ITracker : SharedImpl<> {
  4527. virtual ~ITracker();
  4528. // static queries
  4529. virtual std::string name() const = 0;
  4530. // dynamic queries
  4531. virtual bool isComplete() const = 0; // Successfully completed or failed
  4532. virtual bool isSuccessfullyCompleted() const = 0;
  4533. virtual bool isOpen() const = 0; // Started but not complete
  4534. virtual bool hasChildren() const = 0;
  4535. virtual ITracker& parent() = 0;
  4536. // actions
  4537. virtual void close() = 0; // Successfully complete
  4538. virtual void fail() = 0;
  4539. virtual void markAsNeedingAnotherRun() = 0;
  4540. virtual void addChild( Ptr<ITracker> const& child ) = 0;
  4541. virtual ITracker* findChild( std::string const& name ) = 0;
  4542. virtual void openChild() = 0;
  4543. };
  4544. class TrackerContext {
  4545. enum RunState {
  4546. NotStarted,
  4547. Executing,
  4548. CompletedCycle
  4549. };
  4550. Ptr<ITracker> m_rootTracker;
  4551. ITracker* m_currentTracker;
  4552. RunState m_runState;
  4553. public:
  4554. static TrackerContext& instance() {
  4555. static TrackerContext s_instance;
  4556. return s_instance;
  4557. }
  4558. TrackerContext()
  4559. : m_currentTracker( CATCH_NULL ),
  4560. m_runState( NotStarted )
  4561. {}
  4562. ITracker& startRun();
  4563. void endRun() {
  4564. m_rootTracker.reset();
  4565. m_currentTracker = CATCH_NULL;
  4566. m_runState = NotStarted;
  4567. }
  4568. void startCycle() {
  4569. m_currentTracker = m_rootTracker.get();
  4570. m_runState = Executing;
  4571. }
  4572. void completeCycle() {
  4573. m_runState = CompletedCycle;
  4574. }
  4575. bool completedCycle() const {
  4576. return m_runState == CompletedCycle;
  4577. }
  4578. ITracker& currentTracker() {
  4579. return *m_currentTracker;
  4580. }
  4581. void setCurrentTracker( ITracker* tracker ) {
  4582. m_currentTracker = tracker;
  4583. }
  4584. };
  4585. class TrackerBase : public ITracker {
  4586. protected:
  4587. enum CycleState {
  4588. NotStarted,
  4589. Executing,
  4590. ExecutingChildren,
  4591. NeedsAnotherRun,
  4592. CompletedSuccessfully,
  4593. Failed
  4594. };
  4595. class TrackerHasName {
  4596. std::string m_name;
  4597. public:
  4598. TrackerHasName( std::string const& name ) : m_name( name ) {}
  4599. bool operator ()( Ptr<ITracker> const& tracker ) {
  4600. return tracker->name() == m_name;
  4601. }
  4602. };
  4603. typedef std::vector<Ptr<ITracker> > Children;
  4604. std::string m_name;
  4605. TrackerContext& m_ctx;
  4606. ITracker* m_parent;
  4607. Children m_children;
  4608. CycleState m_runState;
  4609. public:
  4610. TrackerBase( std::string const& name, TrackerContext& ctx, ITracker* parent )
  4611. : m_name( name ),
  4612. m_ctx( ctx ),
  4613. m_parent( parent ),
  4614. m_runState( NotStarted )
  4615. {}
  4616. virtual ~TrackerBase();
  4617. virtual std::string name() const CATCH_OVERRIDE {
  4618. return m_name;
  4619. }
  4620. virtual bool isComplete() const CATCH_OVERRIDE {
  4621. return m_runState == CompletedSuccessfully || m_runState == Failed;
  4622. }
  4623. virtual bool isSuccessfullyCompleted() const CATCH_OVERRIDE {
  4624. return m_runState == CompletedSuccessfully;
  4625. }
  4626. virtual bool isOpen() const CATCH_OVERRIDE {
  4627. return m_runState != NotStarted && !isComplete();
  4628. }
  4629. virtual bool hasChildren() const CATCH_OVERRIDE {
  4630. return !m_children.empty();
  4631. }
  4632. virtual void addChild( Ptr<ITracker> const& child ) CATCH_OVERRIDE {
  4633. m_children.push_back( child );
  4634. }
  4635. virtual ITracker* findChild( std::string const& name ) CATCH_OVERRIDE {
  4636. Children::const_iterator it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( name ) );
  4637. return( it != m_children.end() )
  4638. ? it->get()
  4639. : CATCH_NULL;
  4640. }
  4641. virtual ITracker& parent() CATCH_OVERRIDE {
  4642. assert( m_parent ); // Should always be non-null except for root
  4643. return *m_parent;
  4644. }
  4645. virtual void openChild() CATCH_OVERRIDE {
  4646. if( m_runState != ExecutingChildren ) {
  4647. m_runState = ExecutingChildren;
  4648. if( m_parent )
  4649. m_parent->openChild();
  4650. }
  4651. }
  4652. void open() {
  4653. m_runState = Executing;
  4654. moveToThis();
  4655. if( m_parent )
  4656. m_parent->openChild();
  4657. }
  4658. virtual void close() CATCH_OVERRIDE {
  4659. // Close any still open children (e.g. generators)
  4660. while( &m_ctx.currentTracker() != this )
  4661. m_ctx.currentTracker().close();
  4662. switch( m_runState ) {
  4663. case NotStarted:
  4664. case CompletedSuccessfully:
  4665. case Failed:
  4666. throw std::logic_error( "Illogical state" );
  4667. case NeedsAnotherRun:
  4668. break;;
  4669. case Executing:
  4670. m_runState = CompletedSuccessfully;
  4671. break;
  4672. case ExecutingChildren:
  4673. if( m_children.empty() || m_children.back()->isComplete() )
  4674. m_runState = CompletedSuccessfully;
  4675. break;
  4676. default:
  4677. throw std::logic_error( "Unexpected state" );
  4678. }
  4679. moveToParent();
  4680. m_ctx.completeCycle();
  4681. }
  4682. virtual void fail() CATCH_OVERRIDE {
  4683. m_runState = Failed;
  4684. if( m_parent )
  4685. m_parent->markAsNeedingAnotherRun();
  4686. moveToParent();
  4687. m_ctx.completeCycle();
  4688. }
  4689. virtual void markAsNeedingAnotherRun() CATCH_OVERRIDE {
  4690. m_runState = NeedsAnotherRun;
  4691. }
  4692. private:
  4693. void moveToParent() {
  4694. assert( m_parent );
  4695. m_ctx.setCurrentTracker( m_parent );
  4696. }
  4697. void moveToThis() {
  4698. m_ctx.setCurrentTracker( this );
  4699. }
  4700. };
  4701. class SectionTracker : public TrackerBase {
  4702. public:
  4703. SectionTracker( std::string const& name, TrackerContext& ctx, ITracker* parent )
  4704. : TrackerBase( name, ctx, parent )
  4705. {}
  4706. virtual ~SectionTracker();
  4707. static SectionTracker& acquire( TrackerContext& ctx, std::string const& name ) {
  4708. SectionTracker* section = CATCH_NULL;
  4709. ITracker& currentTracker = ctx.currentTracker();
  4710. if( ITracker* childTracker = currentTracker.findChild( name ) ) {
  4711. section = dynamic_cast<SectionTracker*>( childTracker );
  4712. assert( section );
  4713. }
  4714. else {
  4715. section = new SectionTracker( name, ctx, &currentTracker );
  4716. currentTracker.addChild( section );
  4717. }
  4718. if( !ctx.completedCycle() && !section->isComplete() ) {
  4719. section->open();
  4720. }
  4721. return *section;
  4722. }
  4723. };
  4724. class IndexTracker : public TrackerBase {
  4725. int m_size;
  4726. int m_index;
  4727. public:
  4728. IndexTracker( std::string const& name, TrackerContext& ctx, ITracker* parent, int size )
  4729. : TrackerBase( name, ctx, parent ),
  4730. m_size( size ),
  4731. m_index( -1 )
  4732. {}
  4733. virtual ~IndexTracker();
  4734. static IndexTracker& acquire( TrackerContext& ctx, std::string const& name, int size ) {
  4735. IndexTracker* tracker = CATCH_NULL;
  4736. ITracker& currentTracker = ctx.currentTracker();
  4737. if( ITracker* childTracker = currentTracker.findChild( name ) ) {
  4738. tracker = dynamic_cast<IndexTracker*>( childTracker );
  4739. assert( tracker );
  4740. }
  4741. else {
  4742. tracker = new IndexTracker( name, ctx, &currentTracker, size );
  4743. currentTracker.addChild( tracker );
  4744. }
  4745. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  4746. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  4747. tracker->moveNext();
  4748. tracker->open();
  4749. }
  4750. return *tracker;
  4751. }
  4752. int index() const { return m_index; }
  4753. void moveNext() {
  4754. m_index++;
  4755. m_children.clear();
  4756. }
  4757. virtual void close() CATCH_OVERRIDE {
  4758. TrackerBase::close();
  4759. if( m_runState == CompletedSuccessfully && m_index < m_size-1 )
  4760. m_runState = Executing;
  4761. }
  4762. };
  4763. inline ITracker& TrackerContext::startRun() {
  4764. m_rootTracker = new SectionTracker( "{root}", *this, CATCH_NULL );
  4765. m_currentTracker = CATCH_NULL;
  4766. m_runState = Executing;
  4767. return *m_rootTracker;
  4768. }
  4769. } // namespace TestCaseTracking
  4770. using TestCaseTracking::ITracker;
  4771. using TestCaseTracking::TrackerContext;
  4772. using TestCaseTracking::SectionTracker;
  4773. using TestCaseTracking::IndexTracker;
  4774. } // namespace Catch
  4775. // #included from: catch_fatal_condition.hpp
  4776. #define TWOBLUECUBES_CATCH_FATAL_CONDITION_H_INCLUDED
  4777. namespace Catch {
  4778. // Report the error condition then exit the process
  4779. inline void fatal( std::string const& message, int exitCode ) {
  4780. IContext& context = Catch::getCurrentContext();
  4781. IResultCapture* resultCapture = context.getResultCapture();
  4782. resultCapture->handleFatalErrorCondition( message );
  4783. if( Catch::alwaysTrue() ) // avoids "no return" warnings
  4784. exit( exitCode );
  4785. }
  4786. } // namespace Catch
  4787. #if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
  4788. namespace Catch {
  4789. struct FatalConditionHandler {
  4790. void reset() {}
  4791. };
  4792. } // namespace Catch
  4793. #else // Not Windows - assumed to be POSIX compatible //////////////////////////
  4794. #include <signal.h>
  4795. namespace Catch {
  4796. struct SignalDefs { int id; const char* name; };
  4797. extern SignalDefs signalDefs[];
  4798. SignalDefs signalDefs[] = {
  4799. { SIGINT, "SIGINT - Terminal interrupt signal" },
  4800. { SIGILL, "SIGILL - Illegal instruction signal" },
  4801. { SIGFPE, "SIGFPE - Floating point error signal" },
  4802. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  4803. { SIGTERM, "SIGTERM - Termination request signal" },
  4804. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  4805. };
  4806. struct FatalConditionHandler {
  4807. static void handleSignal( int sig ) {
  4808. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i )
  4809. if( sig == signalDefs[i].id )
  4810. fatal( signalDefs[i].name, -sig );
  4811. fatal( "<unknown signal>", -sig );
  4812. }
  4813. FatalConditionHandler() : m_isSet( true ) {
  4814. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i )
  4815. signal( signalDefs[i].id, handleSignal );
  4816. }
  4817. ~FatalConditionHandler() {
  4818. reset();
  4819. }
  4820. void reset() {
  4821. if( m_isSet ) {
  4822. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i )
  4823. signal( signalDefs[i].id, SIG_DFL );
  4824. m_isSet = false;
  4825. }
  4826. }
  4827. bool m_isSet;
  4828. };
  4829. } // namespace Catch
  4830. #endif // not Windows
  4831. #include <set>
  4832. #include <string>
  4833. namespace Catch {
  4834. class StreamRedirect {
  4835. public:
  4836. StreamRedirect( std::ostream& stream, std::string& targetString )
  4837. : m_stream( stream ),
  4838. m_prevBuf( stream.rdbuf() ),
  4839. m_targetString( targetString )
  4840. {
  4841. stream.rdbuf( m_oss.rdbuf() );
  4842. }
  4843. ~StreamRedirect() {
  4844. m_targetString += m_oss.str();
  4845. m_stream.rdbuf( m_prevBuf );
  4846. }
  4847. private:
  4848. std::ostream& m_stream;
  4849. std::streambuf* m_prevBuf;
  4850. std::ostringstream m_oss;
  4851. std::string& m_targetString;
  4852. };
  4853. ///////////////////////////////////////////////////////////////////////////
  4854. class RunContext : public IResultCapture, public IRunner {
  4855. RunContext( RunContext const& );
  4856. void operator =( RunContext const& );
  4857. public:
  4858. explicit RunContext( Ptr<IConfig const> const& _config, Ptr<IStreamingReporter> const& reporter )
  4859. : m_runInfo( _config->name() ),
  4860. m_context( getCurrentMutableContext() ),
  4861. m_activeTestCase( CATCH_NULL ),
  4862. m_config( _config ),
  4863. m_reporter( reporter )
  4864. {
  4865. m_context.setRunner( this );
  4866. m_context.setConfig( m_config );
  4867. m_context.setResultCapture( this );
  4868. m_reporter->testRunStarting( m_runInfo );
  4869. }
  4870. virtual ~RunContext() {
  4871. m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, aborting() ) );
  4872. }
  4873. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ) {
  4874. m_reporter->testGroupStarting( GroupInfo( testSpec, groupIndex, groupsCount ) );
  4875. }
  4876. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ) {
  4877. m_reporter->testGroupEnded( TestGroupStats( GroupInfo( testSpec, groupIndex, groupsCount ), totals, aborting() ) );
  4878. }
  4879. Totals runTest( TestCase const& testCase ) {
  4880. Totals prevTotals = m_totals;
  4881. std::string redirectedCout;
  4882. std::string redirectedCerr;
  4883. TestCaseInfo testInfo = testCase.getTestCaseInfo();
  4884. m_reporter->testCaseStarting( testInfo );
  4885. m_activeTestCase = &testCase;
  4886. do {
  4887. m_trackerContext.startRun();
  4888. do {
  4889. m_trackerContext.startCycle();
  4890. m_testCaseTracker = &SectionTracker::acquire( m_trackerContext, testInfo.name );
  4891. runCurrentTest( redirectedCout, redirectedCerr );
  4892. }
  4893. while( !m_testCaseTracker->isSuccessfullyCompleted() && !aborting() );
  4894. }
  4895. // !TBD: deprecated - this will be replaced by indexed trackers
  4896. while( getCurrentContext().advanceGeneratorsForCurrentTest() && !aborting() );
  4897. Totals deltaTotals = m_totals.delta( prevTotals );
  4898. if( testInfo.expectedToFail() && deltaTotals.testCases.passed > 0 ) {
  4899. deltaTotals.assertions.failed++;
  4900. deltaTotals.testCases.passed--;
  4901. deltaTotals.testCases.failed++;
  4902. }
  4903. m_totals.testCases += deltaTotals.testCases;
  4904. m_reporter->testCaseEnded( TestCaseStats( testInfo,
  4905. deltaTotals,
  4906. redirectedCout,
  4907. redirectedCerr,
  4908. aborting() ) );
  4909. m_activeTestCase = CATCH_NULL;
  4910. m_testCaseTracker = CATCH_NULL;
  4911. return deltaTotals;
  4912. }
  4913. Ptr<IConfig const> config() const {
  4914. return m_config;
  4915. }
  4916. private: // IResultCapture
  4917. virtual void assertionEnded( AssertionResult const& result ) {
  4918. if( result.getResultType() == ResultWas::Ok ) {
  4919. m_totals.assertions.passed++;
  4920. }
  4921. else if( !result.isOk() ) {
  4922. m_totals.assertions.failed++;
  4923. }
  4924. if( m_reporter->assertionEnded( AssertionStats( result, m_messages, m_totals ) ) )
  4925. m_messages.clear();
  4926. // Reset working state
  4927. m_lastAssertionInfo = AssertionInfo( "", m_lastAssertionInfo.lineInfo, "{Unknown expression after the reported line}" , m_lastAssertionInfo.resultDisposition );
  4928. m_lastResult = result;
  4929. }
  4930. virtual bool sectionStarted (
  4931. SectionInfo const& sectionInfo,
  4932. Counts& assertions
  4933. )
  4934. {
  4935. std::ostringstream oss;
  4936. oss << sectionInfo.name << "@" << sectionInfo.lineInfo;
  4937. ITracker& sectionTracker = SectionTracker::acquire( m_trackerContext, oss.str() );
  4938. if( !sectionTracker.isOpen() )
  4939. return false;
  4940. m_activeSections.push_back( &sectionTracker );
  4941. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  4942. m_reporter->sectionStarting( sectionInfo );
  4943. assertions = m_totals.assertions;
  4944. return true;
  4945. }
  4946. bool testForMissingAssertions( Counts& assertions ) {
  4947. if( assertions.total() != 0 )
  4948. return false;
  4949. if( !m_config->warnAboutMissingAssertions() )
  4950. return false;
  4951. if( m_trackerContext.currentTracker().hasChildren() )
  4952. return false;
  4953. m_totals.assertions.failed++;
  4954. assertions.failed++;
  4955. return true;
  4956. }
  4957. virtual void sectionEnded( SectionEndInfo const& endInfo ) {
  4958. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  4959. bool missingAssertions = testForMissingAssertions( assertions );
  4960. if( !m_activeSections.empty() ) {
  4961. m_activeSections.back()->close();
  4962. m_activeSections.pop_back();
  4963. }
  4964. m_reporter->sectionEnded( SectionStats( endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions ) );
  4965. m_messages.clear();
  4966. }
  4967. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) {
  4968. if( m_unfinishedSections.empty() )
  4969. m_activeSections.back()->fail();
  4970. else
  4971. m_activeSections.back()->close();
  4972. m_activeSections.pop_back();
  4973. m_unfinishedSections.push_back( endInfo );
  4974. }
  4975. virtual void pushScopedMessage( MessageInfo const& message ) {
  4976. m_messages.push_back( message );
  4977. }
  4978. virtual void popScopedMessage( MessageInfo const& message ) {
  4979. m_messages.erase( std::remove( m_messages.begin(), m_messages.end(), message ), m_messages.end() );
  4980. }
  4981. virtual std::string getCurrentTestName() const {
  4982. return m_activeTestCase
  4983. ? m_activeTestCase->getTestCaseInfo().name
  4984. : "";
  4985. }
  4986. virtual const AssertionResult* getLastResult() const {
  4987. return &m_lastResult;
  4988. }
  4989. virtual void handleFatalErrorCondition( std::string const& message ) {
  4990. ResultBuilder resultBuilder = makeUnexpectedResultBuilder();
  4991. resultBuilder.setResultType( ResultWas::FatalErrorCondition );
  4992. resultBuilder << message;
  4993. resultBuilder.captureExpression();
  4994. handleUnfinishedSections();
  4995. // Recreate section for test case (as we will lose the one that was in scope)
  4996. TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  4997. SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description );
  4998. Counts assertions;
  4999. assertions.failed = 1;
  5000. SectionStats testCaseSectionStats( testCaseSection, assertions, 0, false );
  5001. m_reporter->sectionEnded( testCaseSectionStats );
  5002. TestCaseInfo testInfo = m_activeTestCase->getTestCaseInfo();
  5003. Totals deltaTotals;
  5004. deltaTotals.testCases.failed = 1;
  5005. m_reporter->testCaseEnded( TestCaseStats( testInfo,
  5006. deltaTotals,
  5007. "",
  5008. "",
  5009. false ) );
  5010. m_totals.testCases.failed++;
  5011. testGroupEnded( "", m_totals, 1, 1 );
  5012. m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, false ) );
  5013. }
  5014. public:
  5015. // !TBD We need to do this another way!
  5016. bool aborting() const {
  5017. return m_totals.assertions.failed == static_cast<std::size_t>( m_config->abortAfter() );
  5018. }
  5019. private:
  5020. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ) {
  5021. TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  5022. SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description );
  5023. m_reporter->sectionStarting( testCaseSection );
  5024. Counts prevAssertions = m_totals.assertions;
  5025. double duration = 0;
  5026. try {
  5027. m_lastAssertionInfo = AssertionInfo( "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal );
  5028. seedRng( *m_config );
  5029. Timer timer;
  5030. timer.start();
  5031. if( m_reporter->getPreferences().shouldRedirectStdOut ) {
  5032. StreamRedirect coutRedir( Catch::cout(), redirectedCout );
  5033. StreamRedirect cerrRedir( Catch::cerr(), redirectedCerr );
  5034. invokeActiveTestCase();
  5035. }
  5036. else {
  5037. invokeActiveTestCase();
  5038. }
  5039. duration = timer.getElapsedSeconds();
  5040. }
  5041. catch( TestFailureException& ) {
  5042. // This just means the test was aborted due to failure
  5043. }
  5044. catch(...) {
  5045. makeUnexpectedResultBuilder().useActiveException();
  5046. }
  5047. m_testCaseTracker->close();
  5048. handleUnfinishedSections();
  5049. m_messages.clear();
  5050. Counts assertions = m_totals.assertions - prevAssertions;
  5051. bool missingAssertions = testForMissingAssertions( assertions );
  5052. if( testCaseInfo.okToFail() ) {
  5053. std::swap( assertions.failedButOk, assertions.failed );
  5054. m_totals.assertions.failed -= assertions.failedButOk;
  5055. m_totals.assertions.failedButOk += assertions.failedButOk;
  5056. }
  5057. SectionStats testCaseSectionStats( testCaseSection, assertions, duration, missingAssertions );
  5058. m_reporter->sectionEnded( testCaseSectionStats );
  5059. }
  5060. void invokeActiveTestCase() {
  5061. FatalConditionHandler fatalConditionHandler; // Handle signals
  5062. m_activeTestCase->invoke();
  5063. fatalConditionHandler.reset();
  5064. }
  5065. private:
  5066. ResultBuilder makeUnexpectedResultBuilder() const {
  5067. return ResultBuilder( m_lastAssertionInfo.macroName.c_str(),
  5068. m_lastAssertionInfo.lineInfo,
  5069. m_lastAssertionInfo.capturedExpression.c_str(),
  5070. m_lastAssertionInfo.resultDisposition );
  5071. }
  5072. void handleUnfinishedSections() {
  5073. // If sections ended prematurely due to an exception we stored their
  5074. // infos here so we can tear them down outside the unwind process.
  5075. for( std::vector<SectionEndInfo>::const_reverse_iterator it = m_unfinishedSections.rbegin(),
  5076. itEnd = m_unfinishedSections.rend();
  5077. it != itEnd;
  5078. ++it )
  5079. sectionEnded( *it );
  5080. m_unfinishedSections.clear();
  5081. }
  5082. TestRunInfo m_runInfo;
  5083. IMutableContext& m_context;
  5084. TestCase const* m_activeTestCase;
  5085. ITracker* m_testCaseTracker;
  5086. ITracker* m_currentSectionTracker;
  5087. AssertionResult m_lastResult;
  5088. Ptr<IConfig const> m_config;
  5089. Totals m_totals;
  5090. Ptr<IStreamingReporter> m_reporter;
  5091. std::vector<MessageInfo> m_messages;
  5092. AssertionInfo m_lastAssertionInfo;
  5093. std::vector<SectionEndInfo> m_unfinishedSections;
  5094. std::vector<ITracker*> m_activeSections;
  5095. TrackerContext m_trackerContext;
  5096. };
  5097. IResultCapture& getResultCapture() {
  5098. if( IResultCapture* capture = getCurrentContext().getResultCapture() )
  5099. return *capture;
  5100. else
  5101. throw std::logic_error( "No result capture instance" );
  5102. }
  5103. } // end namespace Catch
  5104. // #included from: internal/catch_version.h
  5105. #define TWOBLUECUBES_CATCH_VERSION_H_INCLUDED
  5106. namespace Catch {
  5107. // Versioning information
  5108. struct Version {
  5109. Version( unsigned int _majorVersion,
  5110. unsigned int _minorVersion,
  5111. unsigned int _patchNumber,
  5112. std::string const& _branchName,
  5113. unsigned int _buildNumber );
  5114. unsigned int const majorVersion;
  5115. unsigned int const minorVersion;
  5116. unsigned int const patchNumber;
  5117. // buildNumber is only used if branchName is not null
  5118. std::string const branchName;
  5119. unsigned int const buildNumber;
  5120. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  5121. private:
  5122. void operator=( Version const& );
  5123. };
  5124. extern Version libraryVersion;
  5125. }
  5126. #include <fstream>
  5127. #include <stdlib.h>
  5128. #include <limits>
  5129. namespace Catch {
  5130. Ptr<IStreamingReporter> createReporter( std::string const& reporterName, Ptr<Config> const& config ) {
  5131. Ptr<IStreamingReporter> reporter = getRegistryHub().getReporterRegistry().create( reporterName, config.get() );
  5132. if( !reporter ) {
  5133. std::ostringstream oss;
  5134. oss << "No reporter registered with name: '" << reporterName << "'";
  5135. throw std::domain_error( oss.str() );
  5136. }
  5137. return reporter;
  5138. }
  5139. Ptr<IStreamingReporter> makeReporter( Ptr<Config> const& config ) {
  5140. std::vector<std::string> reporters = config->getReporterNames();
  5141. if( reporters.empty() )
  5142. reporters.push_back( "console" );
  5143. Ptr<IStreamingReporter> reporter;
  5144. for( std::vector<std::string>::const_iterator it = reporters.begin(), itEnd = reporters.end();
  5145. it != itEnd;
  5146. ++it )
  5147. reporter = addReporter( reporter, createReporter( *it, config ) );
  5148. return reporter;
  5149. }
  5150. Ptr<IStreamingReporter> addListeners( Ptr<IConfig const> const& config, Ptr<IStreamingReporter> reporters ) {
  5151. IReporterRegistry::Listeners listeners = getRegistryHub().getReporterRegistry().getListeners();
  5152. for( IReporterRegistry::Listeners::const_iterator it = listeners.begin(), itEnd = listeners.end();
  5153. it != itEnd;
  5154. ++it )
  5155. reporters = addReporter(reporters, (*it)->create( ReporterConfig( config ) ) );
  5156. return reporters;
  5157. }
  5158. Totals runTests( Ptr<Config> const& config ) {
  5159. Ptr<IConfig const> iconfig = config.get();
  5160. Ptr<IStreamingReporter> reporter = makeReporter( config );
  5161. reporter = addListeners( iconfig, reporter );
  5162. RunContext context( iconfig, reporter );
  5163. Totals totals;
  5164. context.testGroupStarting( config->name(), 1, 1 );
  5165. TestSpec testSpec = config->testSpec();
  5166. if( !testSpec.hasFilters() )
  5167. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "~[.]" ).testSpec(); // All not hidden tests
  5168. std::vector<TestCase> const& allTestCases = getAllTestCasesSorted( *iconfig );
  5169. for( std::vector<TestCase>::const_iterator it = allTestCases.begin(), itEnd = allTestCases.end();
  5170. it != itEnd;
  5171. ++it ) {
  5172. if( !context.aborting() && matchTest( *it, testSpec, *iconfig ) )
  5173. totals += context.runTest( *it );
  5174. else
  5175. reporter->skipTest( *it );
  5176. }
  5177. context.testGroupEnded( iconfig->name(), totals, 1, 1 );
  5178. return totals;
  5179. }
  5180. void applyFilenamesAsTags( IConfig const& config ) {
  5181. std::vector<TestCase> const& tests = getAllTestCasesSorted( config );
  5182. for(std::size_t i = 0; i < tests.size(); ++i ) {
  5183. TestCase& test = const_cast<TestCase&>( tests[i] );
  5184. std::set<std::string> tags = test.tags;
  5185. std::string filename = test.lineInfo.file;
  5186. std::string::size_type lastSlash = filename.find_last_of( "\\/" );
  5187. if( lastSlash != std::string::npos )
  5188. filename = filename.substr( lastSlash+1 );
  5189. std::string::size_type lastDot = filename.find_last_of( "." );
  5190. if( lastDot != std::string::npos )
  5191. filename = filename.substr( 0, lastDot );
  5192. tags.insert( "#" + filename );
  5193. setTags( test, tags );
  5194. }
  5195. }
  5196. class Session : NonCopyable {
  5197. static bool alreadyInstantiated;
  5198. public:
  5199. struct OnUnusedOptions { enum DoWhat { Ignore, Fail }; };
  5200. Session()
  5201. : m_cli( makeCommandLineParser() ) {
  5202. if( alreadyInstantiated ) {
  5203. std::string msg = "Only one instance of Catch::Session can ever be used";
  5204. Catch::cerr() << msg << std::endl;
  5205. throw std::logic_error( msg );
  5206. }
  5207. alreadyInstantiated = true;
  5208. }
  5209. ~Session() {
  5210. Catch::cleanUp();
  5211. }
  5212. void showHelp( std::string const& processName ) {
  5213. Catch::cout() << "\nCatch v" << libraryVersion << "\n";
  5214. m_cli.usage( Catch::cout(), processName );
  5215. Catch::cout() << "For more detail usage please see the project docs\n" << std::endl;
  5216. }
  5217. int applyCommandLine( int argc, char const* const* const argv, OnUnusedOptions::DoWhat unusedOptionBehaviour = OnUnusedOptions::Fail ) {
  5218. try {
  5219. m_cli.setThrowOnUnrecognisedTokens( unusedOptionBehaviour == OnUnusedOptions::Fail );
  5220. m_unusedTokens = m_cli.parseInto( Clara::argsToVector( argc, argv ), m_configData );
  5221. if( m_configData.showHelp )
  5222. showHelp( m_configData.processName );
  5223. m_config.reset();
  5224. }
  5225. catch( std::exception& ex ) {
  5226. {
  5227. Colour colourGuard( Colour::Red );
  5228. Catch::cerr()
  5229. << "\nError(s) in input:\n"
  5230. << Text( ex.what(), TextAttributes().setIndent(2) )
  5231. << "\n\n";
  5232. }
  5233. m_cli.usage( Catch::cout(), m_configData.processName );
  5234. return (std::numeric_limits<int>::max)();
  5235. }
  5236. return 0;
  5237. }
  5238. void useConfigData( ConfigData const& _configData ) {
  5239. m_configData = _configData;
  5240. m_config.reset();
  5241. }
  5242. int run( int argc, char const* const* const argv ) {
  5243. int returnCode = applyCommandLine( argc, argv );
  5244. if( returnCode == 0 )
  5245. returnCode = run();
  5246. return returnCode;
  5247. }
  5248. int run() {
  5249. if( m_configData.showHelp )
  5250. return 0;
  5251. try
  5252. {
  5253. config(); // Force config to be constructed
  5254. seedRng( *m_config );
  5255. if( m_configData.filenamesAsTags )
  5256. applyFilenamesAsTags( *m_config );
  5257. // Handle list request
  5258. if( Option<std::size_t> listed = list( config() ) )
  5259. return static_cast<int>( *listed );
  5260. return static_cast<int>( runTests( m_config ).assertions.failed );
  5261. }
  5262. catch( std::exception& ex ) {
  5263. Catch::cerr() << ex.what() << std::endl;
  5264. return (std::numeric_limits<int>::max)();
  5265. }
  5266. }
  5267. Clara::CommandLine<ConfigData> const& cli() const {
  5268. return m_cli;
  5269. }
  5270. std::vector<Clara::Parser::Token> const& unusedTokens() const {
  5271. return m_unusedTokens;
  5272. }
  5273. ConfigData& configData() {
  5274. return m_configData;
  5275. }
  5276. Config& config() {
  5277. if( !m_config )
  5278. m_config = new Config( m_configData );
  5279. return *m_config;
  5280. }
  5281. private:
  5282. Clara::CommandLine<ConfigData> m_cli;
  5283. std::vector<Clara::Parser::Token> m_unusedTokens;
  5284. ConfigData m_configData;
  5285. Ptr<Config> m_config;
  5286. };
  5287. bool Session::alreadyInstantiated = false;
  5288. } // end namespace Catch
  5289. // #included from: catch_registry_hub.hpp
  5290. #define TWOBLUECUBES_CATCH_REGISTRY_HUB_HPP_INCLUDED
  5291. // #included from: catch_test_case_registry_impl.hpp
  5292. #define TWOBLUECUBES_CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED
  5293. #include <vector>
  5294. #include <set>
  5295. #include <sstream>
  5296. #include <iostream>
  5297. #include <algorithm>
  5298. namespace Catch {
  5299. struct LexSort {
  5300. bool operator() (TestCase i,TestCase j) const { return (i<j);}
  5301. };
  5302. struct RandomNumberGenerator {
  5303. int operator()( int n ) const { return std::rand() % n; }
  5304. };
  5305. inline std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  5306. std::vector<TestCase> sorted = unsortedTestCases;
  5307. switch( config.runOrder() ) {
  5308. case RunTests::InLexicographicalOrder:
  5309. std::sort( sorted.begin(), sorted.end(), LexSort() );
  5310. break;
  5311. case RunTests::InRandomOrder:
  5312. {
  5313. seedRng( config );
  5314. RandomNumberGenerator rng;
  5315. std::random_shuffle( sorted.begin(), sorted.end(), rng );
  5316. }
  5317. break;
  5318. case RunTests::InDeclarationOrder:
  5319. // already in declaration order
  5320. break;
  5321. }
  5322. return sorted;
  5323. }
  5324. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  5325. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  5326. }
  5327. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  5328. std::set<TestCase> seenFunctions;
  5329. for( std::vector<TestCase>::const_iterator it = functions.begin(), itEnd = functions.end();
  5330. it != itEnd;
  5331. ++it ) {
  5332. std::pair<std::set<TestCase>::const_iterator, bool> prev = seenFunctions.insert( *it );
  5333. if( !prev.second ){
  5334. Catch::cerr()
  5335. << Colour( Colour::Red )
  5336. << "error: TEST_CASE( \"" << it->name << "\" ) already defined.\n"
  5337. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  5338. << "\tRedefined at " << it->getTestCaseInfo().lineInfo << std::endl;
  5339. exit(1);
  5340. }
  5341. }
  5342. }
  5343. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  5344. std::vector<TestCase> filtered;
  5345. filtered.reserve( testCases.size() );
  5346. for( std::vector<TestCase>::const_iterator it = testCases.begin(), itEnd = testCases.end();
  5347. it != itEnd;
  5348. ++it )
  5349. if( matchTest( *it, testSpec, config ) )
  5350. filtered.push_back( *it );
  5351. return filtered;
  5352. }
  5353. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  5354. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  5355. }
  5356. class TestRegistry : public ITestCaseRegistry {
  5357. public:
  5358. TestRegistry()
  5359. : m_currentSortOrder( RunTests::InDeclarationOrder ),
  5360. m_unnamedCount( 0 )
  5361. {}
  5362. virtual ~TestRegistry();
  5363. virtual void registerTest( TestCase const& testCase ) {
  5364. std::string name = testCase.getTestCaseInfo().name;
  5365. if( name == "" ) {
  5366. std::ostringstream oss;
  5367. oss << "Anonymous test case " << ++m_unnamedCount;
  5368. return registerTest( testCase.withName( oss.str() ) );
  5369. }
  5370. m_functions.push_back( testCase );
  5371. }
  5372. virtual std::vector<TestCase> const& getAllTests() const {
  5373. return m_functions;
  5374. }
  5375. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const {
  5376. if( m_sortedFunctions.empty() )
  5377. enforceNoDuplicateTestCases( m_functions );
  5378. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  5379. m_sortedFunctions = sortTests( config, m_functions );
  5380. m_currentSortOrder = config.runOrder();
  5381. }
  5382. return m_sortedFunctions;
  5383. }
  5384. private:
  5385. std::vector<TestCase> m_functions;
  5386. mutable RunTests::InWhatOrder m_currentSortOrder;
  5387. mutable std::vector<TestCase> m_sortedFunctions;
  5388. size_t m_unnamedCount;
  5389. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  5390. };
  5391. ///////////////////////////////////////////////////////////////////////////
  5392. class FreeFunctionTestCase : public SharedImpl<ITestCase> {
  5393. public:
  5394. FreeFunctionTestCase( TestFunction fun ) : m_fun( fun ) {}
  5395. virtual void invoke() const {
  5396. m_fun();
  5397. }
  5398. private:
  5399. virtual ~FreeFunctionTestCase();
  5400. TestFunction m_fun;
  5401. };
  5402. inline std::string extractClassName( std::string const& classOrQualifiedMethodName ) {
  5403. std::string className = classOrQualifiedMethodName;
  5404. if( startsWith( className, "&" ) )
  5405. {
  5406. std::size_t lastColons = className.rfind( "::" );
  5407. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  5408. if( penultimateColons == std::string::npos )
  5409. penultimateColons = 1;
  5410. className = className.substr( penultimateColons, lastColons-penultimateColons );
  5411. }
  5412. return className;
  5413. }
  5414. void registerTestCase
  5415. ( ITestCase* testCase,
  5416. char const* classOrQualifiedMethodName,
  5417. NameAndDesc const& nameAndDesc,
  5418. SourceLineInfo const& lineInfo ) {
  5419. getMutableRegistryHub().registerTest
  5420. ( makeTestCase
  5421. ( testCase,
  5422. extractClassName( classOrQualifiedMethodName ),
  5423. nameAndDesc.name,
  5424. nameAndDesc.description,
  5425. lineInfo ) );
  5426. }
  5427. void registerTestCaseFunction
  5428. ( TestFunction function,
  5429. SourceLineInfo const& lineInfo,
  5430. NameAndDesc const& nameAndDesc ) {
  5431. registerTestCase( new FreeFunctionTestCase( function ), "", nameAndDesc, lineInfo );
  5432. }
  5433. ///////////////////////////////////////////////////////////////////////////
  5434. AutoReg::AutoReg
  5435. ( TestFunction function,
  5436. SourceLineInfo const& lineInfo,
  5437. NameAndDesc const& nameAndDesc ) {
  5438. registerTestCaseFunction( function, lineInfo, nameAndDesc );
  5439. }
  5440. AutoReg::~AutoReg() {}
  5441. } // end namespace Catch
  5442. // #included from: catch_reporter_registry.hpp
  5443. #define TWOBLUECUBES_CATCH_REPORTER_REGISTRY_HPP_INCLUDED
  5444. #include <map>
  5445. namespace Catch {
  5446. class ReporterRegistry : public IReporterRegistry {
  5447. public:
  5448. virtual ~ReporterRegistry() CATCH_OVERRIDE {}
  5449. virtual IStreamingReporter* create( std::string const& name, Ptr<IConfig const> const& config ) const CATCH_OVERRIDE {
  5450. FactoryMap::const_iterator it = m_factories.find( name );
  5451. if( it == m_factories.end() )
  5452. return CATCH_NULL;
  5453. return it->second->create( ReporterConfig( config ) );
  5454. }
  5455. void registerReporter( std::string const& name, Ptr<IReporterFactory> const& factory ) {
  5456. m_factories.insert( std::make_pair( name, factory ) );
  5457. }
  5458. void registerListener( Ptr<IReporterFactory> const& factory ) {
  5459. m_listeners.push_back( factory );
  5460. }
  5461. virtual FactoryMap const& getFactories() const CATCH_OVERRIDE {
  5462. return m_factories;
  5463. }
  5464. virtual Listeners const& getListeners() const CATCH_OVERRIDE {
  5465. return m_listeners;
  5466. }
  5467. private:
  5468. FactoryMap m_factories;
  5469. Listeners m_listeners;
  5470. };
  5471. }
  5472. // #included from: catch_exception_translator_registry.hpp
  5473. #define TWOBLUECUBES_CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED
  5474. #ifdef __OBJC__
  5475. #import "Foundation/Foundation.h"
  5476. #endif
  5477. namespace Catch {
  5478. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  5479. public:
  5480. ~ExceptionTranslatorRegistry() {
  5481. deleteAll( m_translators );
  5482. }
  5483. virtual void registerTranslator( const IExceptionTranslator* translator ) {
  5484. m_translators.push_back( translator );
  5485. }
  5486. virtual std::string translateActiveException() const {
  5487. try {
  5488. #ifdef __OBJC__
  5489. // In Objective-C try objective-c exceptions first
  5490. @try {
  5491. return tryTranslators();
  5492. }
  5493. @catch (NSException *exception) {
  5494. return Catch::toString( [exception description] );
  5495. }
  5496. #else
  5497. return tryTranslators();
  5498. #endif
  5499. }
  5500. catch( TestFailureException& ) {
  5501. throw;
  5502. }
  5503. catch( std::exception& ex ) {
  5504. return ex.what();
  5505. }
  5506. catch( std::string& msg ) {
  5507. return msg;
  5508. }
  5509. catch( const char* msg ) {
  5510. return msg;
  5511. }
  5512. catch(...) {
  5513. return "Unknown exception";
  5514. }
  5515. }
  5516. std::string tryTranslators() const {
  5517. if( m_translators.empty() )
  5518. throw;
  5519. else
  5520. return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() );
  5521. }
  5522. private:
  5523. std::vector<const IExceptionTranslator*> m_translators;
  5524. };
  5525. }
  5526. namespace Catch {
  5527. namespace {
  5528. class RegistryHub : public IRegistryHub, public IMutableRegistryHub {
  5529. RegistryHub( RegistryHub const& );
  5530. void operator=( RegistryHub const& );
  5531. public: // IRegistryHub
  5532. RegistryHub() {
  5533. }
  5534. virtual IReporterRegistry const& getReporterRegistry() const CATCH_OVERRIDE {
  5535. return m_reporterRegistry;
  5536. }
  5537. virtual ITestCaseRegistry const& getTestCaseRegistry() const CATCH_OVERRIDE {
  5538. return m_testCaseRegistry;
  5539. }
  5540. virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() CATCH_OVERRIDE {
  5541. return m_exceptionTranslatorRegistry;
  5542. }
  5543. public: // IMutableRegistryHub
  5544. virtual void registerReporter( std::string const& name, Ptr<IReporterFactory> const& factory ) CATCH_OVERRIDE {
  5545. m_reporterRegistry.registerReporter( name, factory );
  5546. }
  5547. virtual void registerListener( Ptr<IReporterFactory> const& factory ) CATCH_OVERRIDE {
  5548. m_reporterRegistry.registerListener( factory );
  5549. }
  5550. virtual void registerTest( TestCase const& testInfo ) CATCH_OVERRIDE {
  5551. m_testCaseRegistry.registerTest( testInfo );
  5552. }
  5553. virtual void registerTranslator( const IExceptionTranslator* translator ) CATCH_OVERRIDE {
  5554. m_exceptionTranslatorRegistry.registerTranslator( translator );
  5555. }
  5556. private:
  5557. TestRegistry m_testCaseRegistry;
  5558. ReporterRegistry m_reporterRegistry;
  5559. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  5560. };
  5561. // Single, global, instance
  5562. inline RegistryHub*& getTheRegistryHub() {
  5563. static RegistryHub* theRegistryHub = CATCH_NULL;
  5564. if( !theRegistryHub )
  5565. theRegistryHub = new RegistryHub();
  5566. return theRegistryHub;
  5567. }
  5568. }
  5569. IRegistryHub& getRegistryHub() {
  5570. return *getTheRegistryHub();
  5571. }
  5572. IMutableRegistryHub& getMutableRegistryHub() {
  5573. return *getTheRegistryHub();
  5574. }
  5575. void cleanUp() {
  5576. delete getTheRegistryHub();
  5577. getTheRegistryHub() = CATCH_NULL;
  5578. cleanUpContext();
  5579. }
  5580. std::string translateActiveException() {
  5581. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  5582. }
  5583. } // end namespace Catch
  5584. // #included from: catch_notimplemented_exception.hpp
  5585. #define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_HPP_INCLUDED
  5586. #include <ostream>
  5587. namespace Catch {
  5588. NotImplementedException::NotImplementedException( SourceLineInfo const& lineInfo )
  5589. : m_lineInfo( lineInfo ) {
  5590. std::ostringstream oss;
  5591. oss << lineInfo << ": function ";
  5592. oss << "not implemented";
  5593. m_what = oss.str();
  5594. }
  5595. const char* NotImplementedException::what() const CATCH_NOEXCEPT {
  5596. return m_what.c_str();
  5597. }
  5598. } // end namespace Catch
  5599. // #included from: catch_context_impl.hpp
  5600. #define TWOBLUECUBES_CATCH_CONTEXT_IMPL_HPP_INCLUDED
  5601. // #included from: catch_stream.hpp
  5602. #define TWOBLUECUBES_CATCH_STREAM_HPP_INCLUDED
  5603. #include <stdexcept>
  5604. #include <cstdio>
  5605. #include <iostream>
  5606. namespace Catch {
  5607. template<typename WriterF, size_t bufferSize=256>
  5608. class StreamBufImpl : public StreamBufBase {
  5609. char data[bufferSize];
  5610. WriterF m_writer;
  5611. public:
  5612. StreamBufImpl() {
  5613. setp( data, data + sizeof(data) );
  5614. }
  5615. ~StreamBufImpl() CATCH_NOEXCEPT {
  5616. sync();
  5617. }
  5618. private:
  5619. int overflow( int c ) {
  5620. sync();
  5621. if( c != EOF ) {
  5622. if( pbase() == epptr() )
  5623. m_writer( std::string( 1, static_cast<char>( c ) ) );
  5624. else
  5625. sputc( static_cast<char>( c ) );
  5626. }
  5627. return 0;
  5628. }
  5629. int sync() {
  5630. if( pbase() != pptr() ) {
  5631. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  5632. setp( pbase(), epptr() );
  5633. }
  5634. return 0;
  5635. }
  5636. };
  5637. ///////////////////////////////////////////////////////////////////////////
  5638. FileStream::FileStream( std::string const& filename ) {
  5639. m_ofs.open( filename.c_str() );
  5640. if( m_ofs.fail() ) {
  5641. std::ostringstream oss;
  5642. oss << "Unable to open file: '" << filename << "'";
  5643. throw std::domain_error( oss.str() );
  5644. }
  5645. }
  5646. std::ostream& FileStream::stream() const {
  5647. return m_ofs;
  5648. }
  5649. struct OutputDebugWriter {
  5650. void operator()( std::string const&str ) {
  5651. writeToDebugConsole( str );
  5652. }
  5653. };
  5654. DebugOutStream::DebugOutStream()
  5655. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  5656. m_os( m_streamBuf.get() )
  5657. {}
  5658. std::ostream& DebugOutStream::stream() const {
  5659. return m_os;
  5660. }
  5661. // Store the streambuf from cout up-front because
  5662. // cout may get redirected when running tests
  5663. CoutStream::CoutStream()
  5664. : m_os( Catch::cout().rdbuf() )
  5665. {}
  5666. std::ostream& CoutStream::stream() const {
  5667. return m_os;
  5668. }
  5669. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  5670. std::ostream& cout() {
  5671. return std::cout;
  5672. }
  5673. std::ostream& cerr() {
  5674. return std::cerr;
  5675. }
  5676. #endif
  5677. }
  5678. namespace Catch {
  5679. class Context : public IMutableContext {
  5680. Context() : m_config( CATCH_NULL ), m_runner( CATCH_NULL ), m_resultCapture( CATCH_NULL ) {}
  5681. Context( Context const& );
  5682. void operator=( Context const& );
  5683. public: // IContext
  5684. virtual IResultCapture* getResultCapture() {
  5685. return m_resultCapture;
  5686. }
  5687. virtual IRunner* getRunner() {
  5688. return m_runner;
  5689. }
  5690. virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) {
  5691. return getGeneratorsForCurrentTest()
  5692. .getGeneratorInfo( fileInfo, totalSize )
  5693. .getCurrentIndex();
  5694. }
  5695. virtual bool advanceGeneratorsForCurrentTest() {
  5696. IGeneratorsForTest* generators = findGeneratorsForCurrentTest();
  5697. return generators && generators->moveNext();
  5698. }
  5699. virtual Ptr<IConfig const> getConfig() const {
  5700. return m_config;
  5701. }
  5702. public: // IMutableContext
  5703. virtual void setResultCapture( IResultCapture* resultCapture ) {
  5704. m_resultCapture = resultCapture;
  5705. }
  5706. virtual void setRunner( IRunner* runner ) {
  5707. m_runner = runner;
  5708. }
  5709. virtual void setConfig( Ptr<IConfig const> const& config ) {
  5710. m_config = config;
  5711. }
  5712. friend IMutableContext& getCurrentMutableContext();
  5713. private:
  5714. IGeneratorsForTest* findGeneratorsForCurrentTest() {
  5715. std::string testName = getResultCapture()->getCurrentTestName();
  5716. std::map<std::string, IGeneratorsForTest*>::const_iterator it =
  5717. m_generatorsByTestName.find( testName );
  5718. return it != m_generatorsByTestName.end()
  5719. ? it->second
  5720. : CATCH_NULL;
  5721. }
  5722. IGeneratorsForTest& getGeneratorsForCurrentTest() {
  5723. IGeneratorsForTest* generators = findGeneratorsForCurrentTest();
  5724. if( !generators ) {
  5725. std::string testName = getResultCapture()->getCurrentTestName();
  5726. generators = createGeneratorsForTest();
  5727. m_generatorsByTestName.insert( std::make_pair( testName, generators ) );
  5728. }
  5729. return *generators;
  5730. }
  5731. private:
  5732. Ptr<IConfig const> m_config;
  5733. IRunner* m_runner;
  5734. IResultCapture* m_resultCapture;
  5735. std::map<std::string, IGeneratorsForTest*> m_generatorsByTestName;
  5736. };
  5737. namespace {
  5738. Context* currentContext = CATCH_NULL;
  5739. }
  5740. IMutableContext& getCurrentMutableContext() {
  5741. if( !currentContext )
  5742. currentContext = new Context();
  5743. return *currentContext;
  5744. }
  5745. IContext& getCurrentContext() {
  5746. return getCurrentMutableContext();
  5747. }
  5748. void cleanUpContext() {
  5749. delete currentContext;
  5750. currentContext = CATCH_NULL;
  5751. }
  5752. }
  5753. // #included from: catch_console_colour_impl.hpp
  5754. #define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_IMPL_HPP_INCLUDED
  5755. namespace Catch {
  5756. namespace {
  5757. struct IColourImpl {
  5758. virtual ~IColourImpl() {}
  5759. virtual void use( Colour::Code _colourCode ) = 0;
  5760. };
  5761. struct NoColourImpl : IColourImpl {
  5762. void use( Colour::Code ) {}
  5763. static IColourImpl* instance() {
  5764. static NoColourImpl s_instance;
  5765. return &s_instance;
  5766. }
  5767. };
  5768. } // anon namespace
  5769. } // namespace Catch
  5770. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  5771. # ifdef CATCH_PLATFORM_WINDOWS
  5772. # define CATCH_CONFIG_COLOUR_WINDOWS
  5773. # else
  5774. # define CATCH_CONFIG_COLOUR_ANSI
  5775. # endif
  5776. #endif
  5777. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  5778. #ifndef NOMINMAX
  5779. #define NOMINMAX
  5780. #endif
  5781. #ifdef __AFXDLL
  5782. #include <AfxWin.h>
  5783. #else
  5784. #include <windows.h>
  5785. #endif
  5786. namespace Catch {
  5787. namespace {
  5788. class Win32ColourImpl : public IColourImpl {
  5789. public:
  5790. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  5791. {
  5792. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  5793. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  5794. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  5795. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  5796. }
  5797. virtual void use( Colour::Code _colourCode ) {
  5798. switch( _colourCode ) {
  5799. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  5800. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5801. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  5802. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  5803. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  5804. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  5805. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  5806. case Colour::Grey: return setTextAttribute( 0 );
  5807. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  5808. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  5809. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  5810. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5811. case Colour::Bright: throw std::logic_error( "not a colour" );
  5812. }
  5813. }
  5814. private:
  5815. void setTextAttribute( WORD _textAttribute ) {
  5816. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  5817. }
  5818. HANDLE stdoutHandle;
  5819. WORD originalForegroundAttributes;
  5820. WORD originalBackgroundAttributes;
  5821. };
  5822. IColourImpl* platformColourInstance() {
  5823. static Win32ColourImpl s_instance;
  5824. Ptr<IConfig const> config = getCurrentContext().getConfig();
  5825. UseColour::YesOrNo colourMode = config
  5826. ? config->useColour()
  5827. : UseColour::Auto;
  5828. if( colourMode == UseColour::Auto )
  5829. colourMode = !isDebuggerActive()
  5830. ? UseColour::Yes
  5831. : UseColour::No;
  5832. return colourMode == UseColour::Yes
  5833. ? &s_instance
  5834. : NoColourImpl::instance();
  5835. }
  5836. } // end anon namespace
  5837. } // end namespace Catch
  5838. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  5839. #include <unistd.h>
  5840. namespace Catch {
  5841. namespace {
  5842. // use POSIX/ ANSI console terminal codes
  5843. // Thanks to Adam Strzelecki for original contribution
  5844. // (http://github.com/nanoant)
  5845. // https://github.com/philsquared/Catch/pull/131
  5846. class PosixColourImpl : public IColourImpl {
  5847. public:
  5848. virtual void use( Colour::Code _colourCode ) {
  5849. switch( _colourCode ) {
  5850. case Colour::None:
  5851. case Colour::White: return setColour( "[0m" );
  5852. case Colour::Red: return setColour( "[0;31m" );
  5853. case Colour::Green: return setColour( "[0;32m" );
  5854. case Colour::Blue: return setColour( "[0:34m" );
  5855. case Colour::Cyan: return setColour( "[0;36m" );
  5856. case Colour::Yellow: return setColour( "[0;33m" );
  5857. case Colour::Grey: return setColour( "[1;30m" );
  5858. case Colour::LightGrey: return setColour( "[0;37m" );
  5859. case Colour::BrightRed: return setColour( "[1;31m" );
  5860. case Colour::BrightGreen: return setColour( "[1;32m" );
  5861. case Colour::BrightWhite: return setColour( "[1;37m" );
  5862. case Colour::Bright: throw std::logic_error( "not a colour" );
  5863. }
  5864. }
  5865. static IColourImpl* instance() {
  5866. static PosixColourImpl s_instance;
  5867. return &s_instance;
  5868. }
  5869. private:
  5870. void setColour( const char* _escapeCode ) {
  5871. Catch::cout() << '\033' << _escapeCode;
  5872. }
  5873. };
  5874. IColourImpl* platformColourInstance() {
  5875. Ptr<IConfig const> config = getCurrentContext().getConfig();
  5876. UseColour::YesOrNo colourMode = config
  5877. ? config->useColour()
  5878. : UseColour::Auto;
  5879. if( colourMode == UseColour::Auto )
  5880. colourMode = (!isDebuggerActive() && isatty(STDOUT_FILENO) )
  5881. ? UseColour::Yes
  5882. : UseColour::No;
  5883. return colourMode == UseColour::Yes
  5884. ? PosixColourImpl::instance()
  5885. : NoColourImpl::instance();
  5886. }
  5887. } // end anon namespace
  5888. } // end namespace Catch
  5889. #else // not Windows or ANSI ///////////////////////////////////////////////
  5890. namespace Catch {
  5891. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  5892. } // end namespace Catch
  5893. #endif // Windows/ ANSI/ None
  5894. namespace Catch {
  5895. Colour::Colour( Code _colourCode ) : m_moved( false ) { use( _colourCode ); }
  5896. Colour::Colour( Colour const& _other ) : m_moved( false ) { const_cast<Colour&>( _other ).m_moved = true; }
  5897. Colour::~Colour(){ if( !m_moved ) use( None ); }
  5898. void Colour::use( Code _colourCode ) {
  5899. static IColourImpl* impl = platformColourInstance();
  5900. impl->use( _colourCode );
  5901. }
  5902. } // end namespace Catch
  5903. // #included from: catch_generators_impl.hpp
  5904. #define TWOBLUECUBES_CATCH_GENERATORS_IMPL_HPP_INCLUDED
  5905. #include <vector>
  5906. #include <string>
  5907. #include <map>
  5908. namespace Catch {
  5909. struct GeneratorInfo : IGeneratorInfo {
  5910. GeneratorInfo( std::size_t size )
  5911. : m_size( size ),
  5912. m_currentIndex( 0 )
  5913. {}
  5914. bool moveNext() {
  5915. if( ++m_currentIndex == m_size ) {
  5916. m_currentIndex = 0;
  5917. return false;
  5918. }
  5919. return true;
  5920. }
  5921. std::size_t getCurrentIndex() const {
  5922. return m_currentIndex;
  5923. }
  5924. std::size_t m_size;
  5925. std::size_t m_currentIndex;
  5926. };
  5927. ///////////////////////////////////////////////////////////////////////////
  5928. class GeneratorsForTest : public IGeneratorsForTest {
  5929. public:
  5930. ~GeneratorsForTest() {
  5931. deleteAll( m_generatorsInOrder );
  5932. }
  5933. IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) {
  5934. std::map<std::string, IGeneratorInfo*>::const_iterator it = m_generatorsByName.find( fileInfo );
  5935. if( it == m_generatorsByName.end() ) {
  5936. IGeneratorInfo* info = new GeneratorInfo( size );
  5937. m_generatorsByName.insert( std::make_pair( fileInfo, info ) );
  5938. m_generatorsInOrder.push_back( info );
  5939. return *info;
  5940. }
  5941. return *it->second;
  5942. }
  5943. bool moveNext() {
  5944. std::vector<IGeneratorInfo*>::const_iterator it = m_generatorsInOrder.begin();
  5945. std::vector<IGeneratorInfo*>::const_iterator itEnd = m_generatorsInOrder.end();
  5946. for(; it != itEnd; ++it ) {
  5947. if( (*it)->moveNext() )
  5948. return true;
  5949. }
  5950. return false;
  5951. }
  5952. private:
  5953. std::map<std::string, IGeneratorInfo*> m_generatorsByName;
  5954. std::vector<IGeneratorInfo*> m_generatorsInOrder;
  5955. };
  5956. IGeneratorsForTest* createGeneratorsForTest()
  5957. {
  5958. return new GeneratorsForTest();
  5959. }
  5960. } // end namespace Catch
  5961. // #included from: catch_assertionresult.hpp
  5962. #define TWOBLUECUBES_CATCH_ASSERTIONRESULT_HPP_INCLUDED
  5963. namespace Catch {
  5964. AssertionInfo::AssertionInfo( std::string const& _macroName,
  5965. SourceLineInfo const& _lineInfo,
  5966. std::string const& _capturedExpression,
  5967. ResultDisposition::Flags _resultDisposition )
  5968. : macroName( _macroName ),
  5969. lineInfo( _lineInfo ),
  5970. capturedExpression( _capturedExpression ),
  5971. resultDisposition( _resultDisposition )
  5972. {}
  5973. AssertionResult::AssertionResult() {}
  5974. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  5975. : m_info( info ),
  5976. m_resultData( data )
  5977. {}
  5978. AssertionResult::~AssertionResult() {}
  5979. // Result was a success
  5980. bool AssertionResult::succeeded() const {
  5981. return Catch::isOk( m_resultData.resultType );
  5982. }
  5983. // Result was a success, or failure is suppressed
  5984. bool AssertionResult::isOk() const {
  5985. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  5986. }
  5987. ResultWas::OfType AssertionResult::getResultType() const {
  5988. return m_resultData.resultType;
  5989. }
  5990. bool AssertionResult::hasExpression() const {
  5991. return !m_info.capturedExpression.empty();
  5992. }
  5993. bool AssertionResult::hasMessage() const {
  5994. return !m_resultData.message.empty();
  5995. }
  5996. std::string AssertionResult::getExpression() const {
  5997. if( isFalseTest( m_info.resultDisposition ) )
  5998. return "!" + m_info.capturedExpression;
  5999. else
  6000. return m_info.capturedExpression;
  6001. }
  6002. std::string AssertionResult::getExpressionInMacro() const {
  6003. if( m_info.macroName.empty() )
  6004. return m_info.capturedExpression;
  6005. else
  6006. return m_info.macroName + "( " + m_info.capturedExpression + " )";
  6007. }
  6008. bool AssertionResult::hasExpandedExpression() const {
  6009. return hasExpression() && getExpandedExpression() != getExpression();
  6010. }
  6011. std::string AssertionResult::getExpandedExpression() const {
  6012. return m_resultData.reconstructedExpression;
  6013. }
  6014. std::string AssertionResult::getMessage() const {
  6015. return m_resultData.message;
  6016. }
  6017. SourceLineInfo AssertionResult::getSourceInfo() const {
  6018. return m_info.lineInfo;
  6019. }
  6020. std::string AssertionResult::getTestMacroName() const {
  6021. return m_info.macroName;
  6022. }
  6023. } // end namespace Catch
  6024. // #included from: catch_test_case_info.hpp
  6025. #define TWOBLUECUBES_CATCH_TEST_CASE_INFO_HPP_INCLUDED
  6026. namespace Catch {
  6027. inline TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  6028. if( startsWith( tag, "." ) ||
  6029. tag == "hide" ||
  6030. tag == "!hide" )
  6031. return TestCaseInfo::IsHidden;
  6032. else if( tag == "!throws" )
  6033. return TestCaseInfo::Throws;
  6034. else if( tag == "!shouldfail" )
  6035. return TestCaseInfo::ShouldFail;
  6036. else if( tag == "!mayfail" )
  6037. return TestCaseInfo::MayFail;
  6038. else
  6039. return TestCaseInfo::None;
  6040. }
  6041. inline bool isReservedTag( std::string const& tag ) {
  6042. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !isalnum( tag[0] );
  6043. }
  6044. inline void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  6045. if( isReservedTag( tag ) ) {
  6046. {
  6047. Colour colourGuard( Colour::Red );
  6048. Catch::cerr()
  6049. << "Tag name [" << tag << "] not allowed.\n"
  6050. << "Tag names starting with non alpha-numeric characters are reserved\n";
  6051. }
  6052. {
  6053. Colour colourGuard( Colour::FileName );
  6054. Catch::cerr() << _lineInfo << std::endl;
  6055. }
  6056. exit(1);
  6057. }
  6058. }
  6059. TestCase makeTestCase( ITestCase* _testCase,
  6060. std::string const& _className,
  6061. std::string const& _name,
  6062. std::string const& _descOrTags,
  6063. SourceLineInfo const& _lineInfo )
  6064. {
  6065. bool isHidden( startsWith( _name, "./" ) ); // Legacy support
  6066. // Parse out tags
  6067. std::set<std::string> tags;
  6068. std::string desc, tag;
  6069. bool inTag = false;
  6070. for( std::size_t i = 0; i < _descOrTags.size(); ++i ) {
  6071. char c = _descOrTags[i];
  6072. if( !inTag ) {
  6073. if( c == '[' )
  6074. inTag = true;
  6075. else
  6076. desc += c;
  6077. }
  6078. else {
  6079. if( c == ']' ) {
  6080. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  6081. if( prop == TestCaseInfo::IsHidden )
  6082. isHidden = true;
  6083. else if( prop == TestCaseInfo::None )
  6084. enforceNotReservedTag( tag, _lineInfo );
  6085. tags.insert( tag );
  6086. tag.clear();
  6087. inTag = false;
  6088. }
  6089. else
  6090. tag += c;
  6091. }
  6092. }
  6093. if( isHidden ) {
  6094. tags.insert( "hide" );
  6095. tags.insert( "." );
  6096. }
  6097. TestCaseInfo info( _name, _className, desc, tags, _lineInfo );
  6098. return TestCase( _testCase, info );
  6099. }
  6100. void setTags( TestCaseInfo& testCaseInfo, std::set<std::string> const& tags )
  6101. {
  6102. testCaseInfo.tags = tags;
  6103. testCaseInfo.lcaseTags.clear();
  6104. std::ostringstream oss;
  6105. for( std::set<std::string>::const_iterator it = tags.begin(), itEnd = tags.end(); it != itEnd; ++it ) {
  6106. oss << "[" << *it << "]";
  6107. std::string lcaseTag = toLower( *it );
  6108. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  6109. testCaseInfo.lcaseTags.insert( lcaseTag );
  6110. }
  6111. testCaseInfo.tagsAsString = oss.str();
  6112. }
  6113. TestCaseInfo::TestCaseInfo( std::string const& _name,
  6114. std::string const& _className,
  6115. std::string const& _description,
  6116. std::set<std::string> const& _tags,
  6117. SourceLineInfo const& _lineInfo )
  6118. : name( _name ),
  6119. className( _className ),
  6120. description( _description ),
  6121. lineInfo( _lineInfo ),
  6122. properties( None )
  6123. {
  6124. setTags( *this, _tags );
  6125. }
  6126. TestCaseInfo::TestCaseInfo( TestCaseInfo const& other )
  6127. : name( other.name ),
  6128. className( other.className ),
  6129. description( other.description ),
  6130. tags( other.tags ),
  6131. lcaseTags( other.lcaseTags ),
  6132. tagsAsString( other.tagsAsString ),
  6133. lineInfo( other.lineInfo ),
  6134. properties( other.properties )
  6135. {}
  6136. bool TestCaseInfo::isHidden() const {
  6137. return ( properties & IsHidden ) != 0;
  6138. }
  6139. bool TestCaseInfo::throws() const {
  6140. return ( properties & Throws ) != 0;
  6141. }
  6142. bool TestCaseInfo::okToFail() const {
  6143. return ( properties & (ShouldFail | MayFail ) ) != 0;
  6144. }
  6145. bool TestCaseInfo::expectedToFail() const {
  6146. return ( properties & (ShouldFail ) ) != 0;
  6147. }
  6148. TestCase::TestCase( ITestCase* testCase, TestCaseInfo const& info ) : TestCaseInfo( info ), test( testCase ) {}
  6149. TestCase::TestCase( TestCase const& other )
  6150. : TestCaseInfo( other ),
  6151. test( other.test )
  6152. {}
  6153. TestCase TestCase::withName( std::string const& _newName ) const {
  6154. TestCase other( *this );
  6155. other.name = _newName;
  6156. return other;
  6157. }
  6158. void TestCase::swap( TestCase& other ) {
  6159. test.swap( other.test );
  6160. name.swap( other.name );
  6161. className.swap( other.className );
  6162. description.swap( other.description );
  6163. tags.swap( other.tags );
  6164. lcaseTags.swap( other.lcaseTags );
  6165. tagsAsString.swap( other.tagsAsString );
  6166. std::swap( TestCaseInfo::properties, static_cast<TestCaseInfo&>( other ).properties );
  6167. std::swap( lineInfo, other.lineInfo );
  6168. }
  6169. void TestCase::invoke() const {
  6170. test->invoke();
  6171. }
  6172. bool TestCase::operator == ( TestCase const& other ) const {
  6173. return test.get() == other.test.get() &&
  6174. name == other.name &&
  6175. className == other.className;
  6176. }
  6177. bool TestCase::operator < ( TestCase const& other ) const {
  6178. return name < other.name;
  6179. }
  6180. TestCase& TestCase::operator = ( TestCase const& other ) {
  6181. TestCase temp( other );
  6182. swap( temp );
  6183. return *this;
  6184. }
  6185. TestCaseInfo const& TestCase::getTestCaseInfo() const
  6186. {
  6187. return *this;
  6188. }
  6189. } // end namespace Catch
  6190. // #included from: catch_version.hpp
  6191. #define TWOBLUECUBES_CATCH_VERSION_HPP_INCLUDED
  6192. namespace Catch {
  6193. Version::Version
  6194. ( unsigned int _majorVersion,
  6195. unsigned int _minorVersion,
  6196. unsigned int _patchNumber,
  6197. std::string const& _branchName,
  6198. unsigned int _buildNumber )
  6199. : majorVersion( _majorVersion ),
  6200. minorVersion( _minorVersion ),
  6201. patchNumber( _patchNumber ),
  6202. branchName( _branchName ),
  6203. buildNumber( _buildNumber )
  6204. {}
  6205. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  6206. os << version.majorVersion << "."
  6207. << version.minorVersion << "."
  6208. << version.patchNumber;
  6209. if( !version.branchName.empty() ) {
  6210. os << "-" << version.branchName
  6211. << "." << version.buildNumber;
  6212. }
  6213. return os;
  6214. }
  6215. Version libraryVersion( 1, 5, 0, "", 0 );
  6216. }
  6217. // #included from: catch_message.hpp
  6218. #define TWOBLUECUBES_CATCH_MESSAGE_HPP_INCLUDED
  6219. namespace Catch {
  6220. MessageInfo::MessageInfo( std::string const& _macroName,
  6221. SourceLineInfo const& _lineInfo,
  6222. ResultWas::OfType _type )
  6223. : macroName( _macroName ),
  6224. lineInfo( _lineInfo ),
  6225. type( _type ),
  6226. sequence( ++globalCount )
  6227. {}
  6228. // This may need protecting if threading support is added
  6229. unsigned int MessageInfo::globalCount = 0;
  6230. ////////////////////////////////////////////////////////////////////////////
  6231. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  6232. : m_info( builder.m_info )
  6233. {
  6234. m_info.message = builder.m_stream.str();
  6235. getResultCapture().pushScopedMessage( m_info );
  6236. }
  6237. ScopedMessage::ScopedMessage( ScopedMessage const& other )
  6238. : m_info( other.m_info )
  6239. {}
  6240. ScopedMessage::~ScopedMessage() {
  6241. getResultCapture().popScopedMessage( m_info );
  6242. }
  6243. } // end namespace Catch
  6244. // #included from: catch_legacy_reporter_adapter.hpp
  6245. #define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_HPP_INCLUDED
  6246. // #included from: catch_legacy_reporter_adapter.h
  6247. #define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_H_INCLUDED
  6248. namespace Catch
  6249. {
  6250. // Deprecated
  6251. struct IReporter : IShared {
  6252. virtual ~IReporter();
  6253. virtual bool shouldRedirectStdout() const = 0;
  6254. virtual void StartTesting() = 0;
  6255. virtual void EndTesting( Totals const& totals ) = 0;
  6256. virtual void StartGroup( std::string const& groupName ) = 0;
  6257. virtual void EndGroup( std::string const& groupName, Totals const& totals ) = 0;
  6258. virtual void StartTestCase( TestCaseInfo const& testInfo ) = 0;
  6259. virtual void EndTestCase( TestCaseInfo const& testInfo, Totals const& totals, std::string const& stdOut, std::string const& stdErr ) = 0;
  6260. virtual void StartSection( std::string const& sectionName, std::string const& description ) = 0;
  6261. virtual void EndSection( std::string const& sectionName, Counts const& assertions ) = 0;
  6262. virtual void NoAssertionsInSection( std::string const& sectionName ) = 0;
  6263. virtual void NoAssertionsInTestCase( std::string const& testName ) = 0;
  6264. virtual void Aborted() = 0;
  6265. virtual void Result( AssertionResult const& result ) = 0;
  6266. };
  6267. class LegacyReporterAdapter : public SharedImpl<IStreamingReporter>
  6268. {
  6269. public:
  6270. LegacyReporterAdapter( Ptr<IReporter> const& legacyReporter );
  6271. virtual ~LegacyReporterAdapter();
  6272. virtual ReporterPreferences getPreferences() const;
  6273. virtual void noMatchingTestCases( std::string const& );
  6274. virtual void testRunStarting( TestRunInfo const& );
  6275. virtual void testGroupStarting( GroupInfo const& groupInfo );
  6276. virtual void testCaseStarting( TestCaseInfo const& testInfo );
  6277. virtual void sectionStarting( SectionInfo const& sectionInfo );
  6278. virtual void assertionStarting( AssertionInfo const& );
  6279. virtual bool assertionEnded( AssertionStats const& assertionStats );
  6280. virtual void sectionEnded( SectionStats const& sectionStats );
  6281. virtual void testCaseEnded( TestCaseStats const& testCaseStats );
  6282. virtual void testGroupEnded( TestGroupStats const& testGroupStats );
  6283. virtual void testRunEnded( TestRunStats const& testRunStats );
  6284. virtual void skipTest( TestCaseInfo const& );
  6285. private:
  6286. Ptr<IReporter> m_legacyReporter;
  6287. };
  6288. }
  6289. namespace Catch
  6290. {
  6291. LegacyReporterAdapter::LegacyReporterAdapter( Ptr<IReporter> const& legacyReporter )
  6292. : m_legacyReporter( legacyReporter )
  6293. {}
  6294. LegacyReporterAdapter::~LegacyReporterAdapter() {}
  6295. ReporterPreferences LegacyReporterAdapter::getPreferences() const {
  6296. ReporterPreferences prefs;
  6297. prefs.shouldRedirectStdOut = m_legacyReporter->shouldRedirectStdout();
  6298. return prefs;
  6299. }
  6300. void LegacyReporterAdapter::noMatchingTestCases( std::string const& ) {}
  6301. void LegacyReporterAdapter::testRunStarting( TestRunInfo const& ) {
  6302. m_legacyReporter->StartTesting();
  6303. }
  6304. void LegacyReporterAdapter::testGroupStarting( GroupInfo const& groupInfo ) {
  6305. m_legacyReporter->StartGroup( groupInfo.name );
  6306. }
  6307. void LegacyReporterAdapter::testCaseStarting( TestCaseInfo const& testInfo ) {
  6308. m_legacyReporter->StartTestCase( testInfo );
  6309. }
  6310. void LegacyReporterAdapter::sectionStarting( SectionInfo const& sectionInfo ) {
  6311. m_legacyReporter->StartSection( sectionInfo.name, sectionInfo.description );
  6312. }
  6313. void LegacyReporterAdapter::assertionStarting( AssertionInfo const& ) {
  6314. // Not on legacy interface
  6315. }
  6316. bool LegacyReporterAdapter::assertionEnded( AssertionStats const& assertionStats ) {
  6317. if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) {
  6318. for( std::vector<MessageInfo>::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end();
  6319. it != itEnd;
  6320. ++it ) {
  6321. if( it->type == ResultWas::Info ) {
  6322. ResultBuilder rb( it->macroName.c_str(), it->lineInfo, "", ResultDisposition::Normal );
  6323. rb << it->message;
  6324. rb.setResultType( ResultWas::Info );
  6325. AssertionResult result = rb.build();
  6326. m_legacyReporter->Result( result );
  6327. }
  6328. }
  6329. }
  6330. m_legacyReporter->Result( assertionStats.assertionResult );
  6331. return true;
  6332. }
  6333. void LegacyReporterAdapter::sectionEnded( SectionStats const& sectionStats ) {
  6334. if( sectionStats.missingAssertions )
  6335. m_legacyReporter->NoAssertionsInSection( sectionStats.sectionInfo.name );
  6336. m_legacyReporter->EndSection( sectionStats.sectionInfo.name, sectionStats.assertions );
  6337. }
  6338. void LegacyReporterAdapter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  6339. m_legacyReporter->EndTestCase
  6340. ( testCaseStats.testInfo,
  6341. testCaseStats.totals,
  6342. testCaseStats.stdOut,
  6343. testCaseStats.stdErr );
  6344. }
  6345. void LegacyReporterAdapter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  6346. if( testGroupStats.aborting )
  6347. m_legacyReporter->Aborted();
  6348. m_legacyReporter->EndGroup( testGroupStats.groupInfo.name, testGroupStats.totals );
  6349. }
  6350. void LegacyReporterAdapter::testRunEnded( TestRunStats const& testRunStats ) {
  6351. m_legacyReporter->EndTesting( testRunStats.totals );
  6352. }
  6353. void LegacyReporterAdapter::skipTest( TestCaseInfo const& ) {
  6354. }
  6355. }
  6356. // #included from: catch_timer.hpp
  6357. #ifdef __clang__
  6358. #pragma clang diagnostic push
  6359. #pragma clang diagnostic ignored "-Wc++11-long-long"
  6360. #endif
  6361. #ifdef CATCH_PLATFORM_WINDOWS
  6362. #include <windows.h>
  6363. #else
  6364. #include <sys/time.h>
  6365. #endif
  6366. namespace Catch {
  6367. namespace {
  6368. #ifdef CATCH_PLATFORM_WINDOWS
  6369. uint64_t getCurrentTicks() {
  6370. static uint64_t hz=0, hzo=0;
  6371. if (!hz) {
  6372. QueryPerformanceFrequency( reinterpret_cast<LARGE_INTEGER*>( &hz ) );
  6373. QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER*>( &hzo ) );
  6374. }
  6375. uint64_t t;
  6376. QueryPerformanceCounter( reinterpret_cast<LARGE_INTEGER*>( &t ) );
  6377. return ((t-hzo)*1000000)/hz;
  6378. }
  6379. #else
  6380. uint64_t getCurrentTicks() {
  6381. timeval t;
  6382. gettimeofday(&t,CATCH_NULL);
  6383. return static_cast<uint64_t>( t.tv_sec ) * 1000000ull + static_cast<uint64_t>( t.tv_usec );
  6384. }
  6385. #endif
  6386. }
  6387. void Timer::start() {
  6388. m_ticks = getCurrentTicks();
  6389. }
  6390. unsigned int Timer::getElapsedMicroseconds() const {
  6391. return static_cast<unsigned int>(getCurrentTicks() - m_ticks);
  6392. }
  6393. unsigned int Timer::getElapsedMilliseconds() const {
  6394. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  6395. }
  6396. double Timer::getElapsedSeconds() const {
  6397. return getElapsedMicroseconds()/1000000.0;
  6398. }
  6399. } // namespace Catch
  6400. #ifdef __clang__
  6401. #pragma clang diagnostic pop
  6402. #endif
  6403. // #included from: catch_common.hpp
  6404. #define TWOBLUECUBES_CATCH_COMMON_HPP_INCLUDED
  6405. namespace Catch {
  6406. bool startsWith( std::string const& s, std::string const& prefix ) {
  6407. return s.size() >= prefix.size() && s.substr( 0, prefix.size() ) == prefix;
  6408. }
  6409. bool endsWith( std::string const& s, std::string const& suffix ) {
  6410. return s.size() >= suffix.size() && s.substr( s.size()-suffix.size(), suffix.size() ) == suffix;
  6411. }
  6412. bool contains( std::string const& s, std::string const& infix ) {
  6413. return s.find( infix ) != std::string::npos;
  6414. }
  6415. void toLowerInPlace( std::string& s ) {
  6416. std::transform( s.begin(), s.end(), s.begin(), ::tolower );
  6417. }
  6418. std::string toLower( std::string const& s ) {
  6419. std::string lc = s;
  6420. toLowerInPlace( lc );
  6421. return lc;
  6422. }
  6423. std::string trim( std::string const& str ) {
  6424. static char const* whitespaceChars = "\n\r\t ";
  6425. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  6426. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  6427. return start != std::string::npos ? str.substr( start, 1+end-start ) : "";
  6428. }
  6429. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  6430. bool replaced = false;
  6431. std::size_t i = str.find( replaceThis );
  6432. while( i != std::string::npos ) {
  6433. replaced = true;
  6434. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  6435. if( i < str.size()-withThis.size() )
  6436. i = str.find( replaceThis, i+withThis.size() );
  6437. else
  6438. i = std::string::npos;
  6439. }
  6440. return replaced;
  6441. }
  6442. pluralise::pluralise( std::size_t count, std::string const& label )
  6443. : m_count( count ),
  6444. m_label( label )
  6445. {}
  6446. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  6447. os << pluraliser.m_count << " " << pluraliser.m_label;
  6448. if( pluraliser.m_count != 1 )
  6449. os << "s";
  6450. return os;
  6451. }
  6452. SourceLineInfo::SourceLineInfo() : line( 0 ){}
  6453. SourceLineInfo::SourceLineInfo( char const* _file, std::size_t _line )
  6454. : file( _file ),
  6455. line( _line )
  6456. {}
  6457. SourceLineInfo::SourceLineInfo( SourceLineInfo const& other )
  6458. : file( other.file ),
  6459. line( other.line )
  6460. {}
  6461. bool SourceLineInfo::empty() const {
  6462. return file.empty();
  6463. }
  6464. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const {
  6465. return line == other.line && file == other.file;
  6466. }
  6467. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const {
  6468. return line < other.line || ( line == other.line && file < other.file );
  6469. }
  6470. void seedRng( IConfig const& config ) {
  6471. if( config.rngSeed() != 0 )
  6472. std::srand( config.rngSeed() );
  6473. }
  6474. unsigned int rngSeed() {
  6475. return getCurrentContext().getConfig()->rngSeed();
  6476. }
  6477. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  6478. #ifndef __GNUG__
  6479. os << info.file << "(" << info.line << ")";
  6480. #else
  6481. os << info.file << ":" << info.line;
  6482. #endif
  6483. return os;
  6484. }
  6485. void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ) {
  6486. std::ostringstream oss;
  6487. oss << locationInfo << ": Internal Catch error: '" << message << "'";
  6488. if( alwaysTrue() )
  6489. throw std::logic_error( oss.str() );
  6490. }
  6491. }
  6492. // #included from: catch_section.hpp
  6493. #define TWOBLUECUBES_CATCH_SECTION_HPP_INCLUDED
  6494. namespace Catch {
  6495. SectionInfo::SectionInfo
  6496. ( SourceLineInfo const& _lineInfo,
  6497. std::string const& _name,
  6498. std::string const& _description )
  6499. : name( _name ),
  6500. description( _description ),
  6501. lineInfo( _lineInfo )
  6502. {}
  6503. Section::Section( SectionInfo const& info )
  6504. : m_info( info ),
  6505. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  6506. {
  6507. m_timer.start();
  6508. }
  6509. Section::~Section() {
  6510. if( m_sectionIncluded ) {
  6511. SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() );
  6512. if( std::uncaught_exception() )
  6513. getResultCapture().sectionEndedEarly( endInfo );
  6514. else
  6515. getResultCapture().sectionEnded( endInfo );
  6516. }
  6517. }
  6518. // This indicates whether the section should be executed or not
  6519. Section::operator bool() const {
  6520. return m_sectionIncluded;
  6521. }
  6522. } // end namespace Catch
  6523. // #included from: catch_debugger.hpp
  6524. #define TWOBLUECUBES_CATCH_DEBUGGER_HPP_INCLUDED
  6525. #include <iostream>
  6526. #ifdef CATCH_PLATFORM_MAC
  6527. #include <assert.h>
  6528. #include <stdbool.h>
  6529. #include <sys/types.h>
  6530. #include <unistd.h>
  6531. #include <sys/sysctl.h>
  6532. namespace Catch{
  6533. // The following function is taken directly from the following technical note:
  6534. // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  6535. // Returns true if the current process is being debugged (either
  6536. // running under the debugger or has a debugger attached post facto).
  6537. bool isDebuggerActive(){
  6538. int mib[4];
  6539. struct kinfo_proc info;
  6540. size_t size;
  6541. // Initialize the flags so that, if sysctl fails for some bizarre
  6542. // reason, we get a predictable result.
  6543. info.kp_proc.p_flag = 0;
  6544. // Initialize mib, which tells sysctl the info we want, in this case
  6545. // we're looking for information about a specific process ID.
  6546. mib[0] = CTL_KERN;
  6547. mib[1] = KERN_PROC;
  6548. mib[2] = KERN_PROC_PID;
  6549. mib[3] = getpid();
  6550. // Call sysctl.
  6551. size = sizeof(info);
  6552. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, CATCH_NULL, 0) != 0 ) {
  6553. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  6554. return false;
  6555. }
  6556. // We're being debugged if the P_TRACED flag is set.
  6557. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  6558. }
  6559. } // namespace Catch
  6560. #elif defined(_MSC_VER)
  6561. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  6562. namespace Catch {
  6563. bool isDebuggerActive() {
  6564. return IsDebuggerPresent() != 0;
  6565. }
  6566. }
  6567. #elif defined(__MINGW32__)
  6568. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  6569. namespace Catch {
  6570. bool isDebuggerActive() {
  6571. return IsDebuggerPresent() != 0;
  6572. }
  6573. }
  6574. #else
  6575. namespace Catch {
  6576. inline bool isDebuggerActive() { return false; }
  6577. }
  6578. #endif // Platform
  6579. #ifdef CATCH_PLATFORM_WINDOWS
  6580. extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA( const char* );
  6581. namespace Catch {
  6582. void writeToDebugConsole( std::string const& text ) {
  6583. ::OutputDebugStringA( text.c_str() );
  6584. }
  6585. }
  6586. #else
  6587. namespace Catch {
  6588. void writeToDebugConsole( std::string const& text ) {
  6589. // !TBD: Need a version for Mac/ XCode and other IDEs
  6590. Catch::cout() << text;
  6591. }
  6592. }
  6593. #endif // Platform
  6594. // #included from: catch_tostring.hpp
  6595. #define TWOBLUECUBES_CATCH_TOSTRING_HPP_INCLUDED
  6596. namespace Catch {
  6597. namespace Detail {
  6598. const std::string unprintableString = "{?}";
  6599. namespace {
  6600. const int hexThreshold = 255;
  6601. struct Endianness {
  6602. enum Arch { Big, Little };
  6603. static Arch which() {
  6604. union _{
  6605. int asInt;
  6606. char asChar[sizeof (int)];
  6607. } u;
  6608. u.asInt = 1;
  6609. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  6610. }
  6611. };
  6612. }
  6613. std::string rawMemoryToString( const void *object, std::size_t size )
  6614. {
  6615. // Reverse order for little endian architectures
  6616. int i = 0, end = static_cast<int>( size ), inc = 1;
  6617. if( Endianness::which() == Endianness::Little ) {
  6618. i = end-1;
  6619. end = inc = -1;
  6620. }
  6621. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  6622. std::ostringstream os;
  6623. os << "0x" << std::setfill('0') << std::hex;
  6624. for( ; i != end; i += inc )
  6625. os << std::setw(2) << static_cast<unsigned>(bytes[i]);
  6626. return os.str();
  6627. }
  6628. }
  6629. std::string toString( std::string const& value ) {
  6630. std::string s = value;
  6631. if( getCurrentContext().getConfig()->showInvisibles() ) {
  6632. for(size_t i = 0; i < s.size(); ++i ) {
  6633. std::string subs;
  6634. switch( s[i] ) {
  6635. case '\n': subs = "\\n"; break;
  6636. case '\t': subs = "\\t"; break;
  6637. default: break;
  6638. }
  6639. if( !subs.empty() ) {
  6640. s = s.substr( 0, i ) + subs + s.substr( i+1 );
  6641. ++i;
  6642. }
  6643. }
  6644. }
  6645. return "\"" + s + "\"";
  6646. }
  6647. std::string toString( std::wstring const& value ) {
  6648. std::string s;
  6649. s.reserve( value.size() );
  6650. for(size_t i = 0; i < value.size(); ++i )
  6651. s += value[i] <= 0xff ? static_cast<char>( value[i] ) : '?';
  6652. return Catch::toString( s );
  6653. }
  6654. std::string toString( const char* const value ) {
  6655. return value ? Catch::toString( std::string( value ) ) : std::string( "{null string}" );
  6656. }
  6657. std::string toString( char* const value ) {
  6658. return Catch::toString( static_cast<const char*>( value ) );
  6659. }
  6660. std::string toString( const wchar_t* const value )
  6661. {
  6662. return value ? Catch::toString( std::wstring(value) ) : std::string( "{null string}" );
  6663. }
  6664. std::string toString( wchar_t* const value )
  6665. {
  6666. return Catch::toString( static_cast<const wchar_t*>( value ) );
  6667. }
  6668. std::string toString( int value ) {
  6669. std::ostringstream oss;
  6670. oss << value;
  6671. if( value > Detail::hexThreshold )
  6672. oss << " (0x" << std::hex << value << ")";
  6673. return oss.str();
  6674. }
  6675. std::string toString( unsigned long value ) {
  6676. std::ostringstream oss;
  6677. oss << value;
  6678. if( value > Detail::hexThreshold )
  6679. oss << " (0x" << std::hex << value << ")";
  6680. return oss.str();
  6681. }
  6682. std::string toString( unsigned int value ) {
  6683. return Catch::toString( static_cast<unsigned long>( value ) );
  6684. }
  6685. template<typename T>
  6686. std::string fpToString( T value, int precision ) {
  6687. std::ostringstream oss;
  6688. oss << std::setprecision( precision )
  6689. << std::fixed
  6690. << value;
  6691. std::string d = oss.str();
  6692. std::size_t i = d.find_last_not_of( '0' );
  6693. if( i != std::string::npos && i != d.size()-1 ) {
  6694. if( d[i] == '.' )
  6695. i++;
  6696. d = d.substr( 0, i+1 );
  6697. }
  6698. return d;
  6699. }
  6700. std::string toString( const double value ) {
  6701. return fpToString( value, 10 );
  6702. }
  6703. std::string toString( const float value ) {
  6704. return fpToString( value, 5 ) + "f";
  6705. }
  6706. std::string toString( bool value ) {
  6707. return value ? "true" : "false";
  6708. }
  6709. std::string toString( char value ) {
  6710. return value < ' '
  6711. ? toString( static_cast<unsigned int>( value ) )
  6712. : Detail::makeString( value );
  6713. }
  6714. std::string toString( signed char value ) {
  6715. return toString( static_cast<char>( value ) );
  6716. }
  6717. std::string toString( unsigned char value ) {
  6718. return toString( static_cast<char>( value ) );
  6719. }
  6720. #ifdef CATCH_CONFIG_CPP11_LONG_LONG
  6721. std::string toString( long long value ) {
  6722. std::ostringstream oss;
  6723. oss << value;
  6724. if( value > Detail::hexThreshold )
  6725. oss << " (0x" << std::hex << value << ")";
  6726. return oss.str();
  6727. }
  6728. std::string toString( unsigned long long value ) {
  6729. std::ostringstream oss;
  6730. oss << value;
  6731. if( value > Detail::hexThreshold )
  6732. oss << " (0x" << std::hex << value << ")";
  6733. return oss.str();
  6734. }
  6735. #endif
  6736. #ifdef CATCH_CONFIG_CPP11_NULLPTR
  6737. std::string toString( std::nullptr_t ) {
  6738. return "nullptr";
  6739. }
  6740. #endif
  6741. #ifdef __OBJC__
  6742. std::string toString( NSString const * const& nsstring ) {
  6743. if( !nsstring )
  6744. return "nil";
  6745. return "@" + toString([nsstring UTF8String]);
  6746. }
  6747. std::string toString( NSString * CATCH_ARC_STRONG const& nsstring ) {
  6748. if( !nsstring )
  6749. return "nil";
  6750. return "@" + toString([nsstring UTF8String]);
  6751. }
  6752. std::string toString( NSObject* const& nsObject ) {
  6753. return toString( [nsObject description] );
  6754. }
  6755. #endif
  6756. } // end namespace Catch
  6757. // #included from: catch_result_builder.hpp
  6758. #define TWOBLUECUBES_CATCH_RESULT_BUILDER_HPP_INCLUDED
  6759. namespace Catch {
  6760. std::string capturedExpressionWithSecondArgument( std::string const& capturedExpression, std::string const& secondArg ) {
  6761. return secondArg.empty() || secondArg == "\"\""
  6762. ? capturedExpression
  6763. : capturedExpression + ", " + secondArg;
  6764. }
  6765. ResultBuilder::ResultBuilder( char const* macroName,
  6766. SourceLineInfo const& lineInfo,
  6767. char const* capturedExpression,
  6768. ResultDisposition::Flags resultDisposition,
  6769. char const* secondArg )
  6770. : m_assertionInfo( macroName, lineInfo, capturedExpressionWithSecondArgument( capturedExpression, secondArg ), resultDisposition ),
  6771. m_shouldDebugBreak( false ),
  6772. m_shouldThrow( false )
  6773. {}
  6774. ResultBuilder& ResultBuilder::setResultType( ResultWas::OfType result ) {
  6775. m_data.resultType = result;
  6776. return *this;
  6777. }
  6778. ResultBuilder& ResultBuilder::setResultType( bool result ) {
  6779. m_data.resultType = result ? ResultWas::Ok : ResultWas::ExpressionFailed;
  6780. return *this;
  6781. }
  6782. ResultBuilder& ResultBuilder::setLhs( std::string const& lhs ) {
  6783. m_exprComponents.lhs = lhs;
  6784. return *this;
  6785. }
  6786. ResultBuilder& ResultBuilder::setRhs( std::string const& rhs ) {
  6787. m_exprComponents.rhs = rhs;
  6788. return *this;
  6789. }
  6790. ResultBuilder& ResultBuilder::setOp( std::string const& op ) {
  6791. m_exprComponents.op = op;
  6792. return *this;
  6793. }
  6794. void ResultBuilder::endExpression() {
  6795. m_exprComponents.testFalse = isFalseTest( m_assertionInfo.resultDisposition );
  6796. captureExpression();
  6797. }
  6798. void ResultBuilder::useActiveException( ResultDisposition::Flags resultDisposition ) {
  6799. m_assertionInfo.resultDisposition = resultDisposition;
  6800. m_stream.oss << Catch::translateActiveException();
  6801. captureResult( ResultWas::ThrewException );
  6802. }
  6803. void ResultBuilder::captureResult( ResultWas::OfType resultType ) {
  6804. setResultType( resultType );
  6805. captureExpression();
  6806. }
  6807. void ResultBuilder::captureExpectedException( std::string const& expectedMessage ) {
  6808. if( expectedMessage.empty() )
  6809. captureExpectedException( Matchers::Impl::Generic::AllOf<std::string>() );
  6810. else
  6811. captureExpectedException( Matchers::Equals( expectedMessage ) );
  6812. }
  6813. void ResultBuilder::captureExpectedException( Matchers::Impl::Matcher<std::string> const& matcher ) {
  6814. assert( m_exprComponents.testFalse == false );
  6815. AssertionResultData data = m_data;
  6816. data.resultType = ResultWas::Ok;
  6817. data.reconstructedExpression = m_assertionInfo.capturedExpression;
  6818. std::string actualMessage = Catch::translateActiveException();
  6819. if( !matcher.match( actualMessage ) ) {
  6820. data.resultType = ResultWas::ExpressionFailed;
  6821. data.reconstructedExpression = actualMessage;
  6822. }
  6823. AssertionResult result( m_assertionInfo, data );
  6824. handleResult( result );
  6825. }
  6826. void ResultBuilder::captureExpression() {
  6827. AssertionResult result = build();
  6828. handleResult( result );
  6829. }
  6830. void ResultBuilder::handleResult( AssertionResult const& result )
  6831. {
  6832. getResultCapture().assertionEnded( result );
  6833. if( !result.isOk() ) {
  6834. if( getCurrentContext().getConfig()->shouldDebugBreak() )
  6835. m_shouldDebugBreak = true;
  6836. if( getCurrentContext().getRunner()->aborting() || (m_assertionInfo.resultDisposition & ResultDisposition::Normal) )
  6837. m_shouldThrow = true;
  6838. }
  6839. }
  6840. void ResultBuilder::react() {
  6841. if( m_shouldThrow )
  6842. throw Catch::TestFailureException();
  6843. }
  6844. bool ResultBuilder::shouldDebugBreak() const { return m_shouldDebugBreak; }
  6845. bool ResultBuilder::allowThrows() const { return getCurrentContext().getConfig()->allowThrows(); }
  6846. AssertionResult ResultBuilder::build() const
  6847. {
  6848. assert( m_data.resultType != ResultWas::Unknown );
  6849. AssertionResultData data = m_data;
  6850. // Flip bool results if testFalse is set
  6851. if( m_exprComponents.testFalse ) {
  6852. if( data.resultType == ResultWas::Ok )
  6853. data.resultType = ResultWas::ExpressionFailed;
  6854. else if( data.resultType == ResultWas::ExpressionFailed )
  6855. data.resultType = ResultWas::Ok;
  6856. }
  6857. data.message = m_stream.oss.str();
  6858. data.reconstructedExpression = reconstructExpression();
  6859. if( m_exprComponents.testFalse ) {
  6860. if( m_exprComponents.op == "" )
  6861. data.reconstructedExpression = "!" + data.reconstructedExpression;
  6862. else
  6863. data.reconstructedExpression = "!(" + data.reconstructedExpression + ")";
  6864. }
  6865. return AssertionResult( m_assertionInfo, data );
  6866. }
  6867. std::string ResultBuilder::reconstructExpression() const {
  6868. if( m_exprComponents.op == "" )
  6869. return m_exprComponents.lhs.empty() ? m_assertionInfo.capturedExpression : m_exprComponents.op + m_exprComponents.lhs;
  6870. else if( m_exprComponents.op == "matches" )
  6871. return m_exprComponents.lhs + " " + m_exprComponents.rhs;
  6872. else if( m_exprComponents.op != "!" ) {
  6873. if( m_exprComponents.lhs.size() + m_exprComponents.rhs.size() < 40 &&
  6874. m_exprComponents.lhs.find("\n") == std::string::npos &&
  6875. m_exprComponents.rhs.find("\n") == std::string::npos )
  6876. return m_exprComponents.lhs + " " + m_exprComponents.op + " " + m_exprComponents.rhs;
  6877. else
  6878. return m_exprComponents.lhs + "\n" + m_exprComponents.op + "\n" + m_exprComponents.rhs;
  6879. }
  6880. else
  6881. 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}";
  6882. }
  6883. } // end namespace Catch
  6884. // #included from: catch_tag_alias_registry.hpp
  6885. #define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED
  6886. // #included from: catch_tag_alias_registry.h
  6887. #define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_H_INCLUDED
  6888. #include <map>
  6889. namespace Catch {
  6890. class TagAliasRegistry : public ITagAliasRegistry {
  6891. public:
  6892. virtual ~TagAliasRegistry();
  6893. virtual Option<TagAlias> find( std::string const& alias ) const;
  6894. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const;
  6895. void add( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  6896. static TagAliasRegistry& get();
  6897. private:
  6898. std::map<std::string, TagAlias> m_registry;
  6899. };
  6900. } // end namespace Catch
  6901. #include <map>
  6902. #include <iostream>
  6903. namespace Catch {
  6904. TagAliasRegistry::~TagAliasRegistry() {}
  6905. Option<TagAlias> TagAliasRegistry::find( std::string const& alias ) const {
  6906. std::map<std::string, TagAlias>::const_iterator it = m_registry.find( alias );
  6907. if( it != m_registry.end() )
  6908. return it->second;
  6909. else
  6910. return Option<TagAlias>();
  6911. }
  6912. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  6913. std::string expandedTestSpec = unexpandedTestSpec;
  6914. for( std::map<std::string, TagAlias>::const_iterator it = m_registry.begin(), itEnd = m_registry.end();
  6915. it != itEnd;
  6916. ++it ) {
  6917. std::size_t pos = expandedTestSpec.find( it->first );
  6918. if( pos != std::string::npos ) {
  6919. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  6920. it->second.tag +
  6921. expandedTestSpec.substr( pos + it->first.size() );
  6922. }
  6923. }
  6924. return expandedTestSpec;
  6925. }
  6926. void TagAliasRegistry::add( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) {
  6927. if( !startsWith( alias, "[@" ) || !endsWith( alias, "]" ) ) {
  6928. std::ostringstream oss;
  6929. oss << "error: tag alias, \"" << alias << "\" is not of the form [@alias name].\n" << lineInfo;
  6930. throw std::domain_error( oss.str().c_str() );
  6931. }
  6932. if( !m_registry.insert( std::make_pair( alias, TagAlias( tag, lineInfo ) ) ).second ) {
  6933. std::ostringstream oss;
  6934. oss << "error: tag alias, \"" << alias << "\" already registered.\n"
  6935. << "\tFirst seen at " << find(alias)->lineInfo << "\n"
  6936. << "\tRedefined at " << lineInfo;
  6937. throw std::domain_error( oss.str().c_str() );
  6938. }
  6939. }
  6940. TagAliasRegistry& TagAliasRegistry::get() {
  6941. static TagAliasRegistry instance;
  6942. return instance;
  6943. }
  6944. ITagAliasRegistry::~ITagAliasRegistry() {}
  6945. ITagAliasRegistry const& ITagAliasRegistry::get() { return TagAliasRegistry::get(); }
  6946. RegistrarForTagAliases::RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) {
  6947. try {
  6948. TagAliasRegistry::get().add( alias, tag, lineInfo );
  6949. }
  6950. catch( std::exception& ex ) {
  6951. Colour colourGuard( Colour::Red );
  6952. Catch::cerr() << ex.what() << std::endl;
  6953. exit(1);
  6954. }
  6955. }
  6956. } // end namespace Catch
  6957. // #included from: ../reporters/catch_reporter_multi.hpp
  6958. #define TWOBLUECUBES_CATCH_REPORTER_MULTI_HPP_INCLUDED
  6959. namespace Catch {
  6960. class MultipleReporters : public SharedImpl<IStreamingReporter> {
  6961. typedef std::vector<Ptr<IStreamingReporter> > Reporters;
  6962. Reporters m_reporters;
  6963. public:
  6964. void add( Ptr<IStreamingReporter> const& reporter ) {
  6965. m_reporters.push_back( reporter );
  6966. }
  6967. public: // IStreamingReporter
  6968. virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE {
  6969. return m_reporters[0]->getPreferences();
  6970. }
  6971. virtual void noMatchingTestCases( std::string const& spec ) CATCH_OVERRIDE {
  6972. for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
  6973. it != itEnd;
  6974. ++it )
  6975. (*it)->noMatchingTestCases( spec );
  6976. }
  6977. virtual void testRunStarting( TestRunInfo const& testRunInfo ) CATCH_OVERRIDE {
  6978. for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
  6979. it != itEnd;
  6980. ++it )
  6981. (*it)->testRunStarting( testRunInfo );
  6982. }
  6983. virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE {
  6984. for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
  6985. it != itEnd;
  6986. ++it )
  6987. (*it)->testGroupStarting( groupInfo );
  6988. }
  6989. virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE {
  6990. for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
  6991. it != itEnd;
  6992. ++it )
  6993. (*it)->testCaseStarting( testInfo );
  6994. }
  6995. virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE {
  6996. for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
  6997. it != itEnd;
  6998. ++it )
  6999. (*it)->sectionStarting( sectionInfo );
  7000. }
  7001. virtual void assertionStarting( AssertionInfo const& assertionInfo ) CATCH_OVERRIDE {
  7002. for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
  7003. it != itEnd;
  7004. ++it )
  7005. (*it)->assertionStarting( assertionInfo );
  7006. }
  7007. // The return value indicates if the messages buffer should be cleared:
  7008. virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE {
  7009. bool clearBuffer = false;
  7010. for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
  7011. it != itEnd;
  7012. ++it )
  7013. clearBuffer |= (*it)->assertionEnded( assertionStats );
  7014. return clearBuffer;
  7015. }
  7016. virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE {
  7017. for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
  7018. it != itEnd;
  7019. ++it )
  7020. (*it)->sectionEnded( sectionStats );
  7021. }
  7022. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE {
  7023. for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
  7024. it != itEnd;
  7025. ++it )
  7026. (*it)->testCaseEnded( testCaseStats );
  7027. }
  7028. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE {
  7029. for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
  7030. it != itEnd;
  7031. ++it )
  7032. (*it)->testGroupEnded( testGroupStats );
  7033. }
  7034. virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE {
  7035. for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
  7036. it != itEnd;
  7037. ++it )
  7038. (*it)->testRunEnded( testRunStats );
  7039. }
  7040. virtual void skipTest( TestCaseInfo const& testInfo ) CATCH_OVERRIDE {
  7041. for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end();
  7042. it != itEnd;
  7043. ++it )
  7044. (*it)->skipTest( testInfo );
  7045. }
  7046. };
  7047. Ptr<IStreamingReporter> addReporter( Ptr<IStreamingReporter> const& existingReporter, Ptr<IStreamingReporter> const& additionalReporter ) {
  7048. Ptr<IStreamingReporter> resultingReporter;
  7049. if( existingReporter ) {
  7050. MultipleReporters* multi = dynamic_cast<MultipleReporters*>( existingReporter.get() );
  7051. if( !multi ) {
  7052. multi = new MultipleReporters;
  7053. resultingReporter = Ptr<IStreamingReporter>( multi );
  7054. if( existingReporter )
  7055. multi->add( existingReporter );
  7056. }
  7057. else
  7058. resultingReporter = existingReporter;
  7059. multi->add( additionalReporter );
  7060. }
  7061. else
  7062. resultingReporter = additionalReporter;
  7063. return resultingReporter;
  7064. }
  7065. } // end namespace Catch
  7066. // #included from: ../reporters/catch_reporter_xml.hpp
  7067. #define TWOBLUECUBES_CATCH_REPORTER_XML_HPP_INCLUDED
  7068. // #included from: catch_reporter_bases.hpp
  7069. #define TWOBLUECUBES_CATCH_REPORTER_BASES_HPP_INCLUDED
  7070. #include <cstring>
  7071. namespace Catch {
  7072. struct StreamingReporterBase : SharedImpl<IStreamingReporter> {
  7073. StreamingReporterBase( ReporterConfig const& _config )
  7074. : m_config( _config.fullConfig() ),
  7075. stream( _config.stream() )
  7076. {
  7077. m_reporterPrefs.shouldRedirectStdOut = false;
  7078. }
  7079. virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE {
  7080. return m_reporterPrefs;
  7081. }
  7082. virtual ~StreamingReporterBase() CATCH_OVERRIDE;
  7083. virtual void noMatchingTestCases( std::string const& ) CATCH_OVERRIDE {}
  7084. virtual void testRunStarting( TestRunInfo const& _testRunInfo ) CATCH_OVERRIDE {
  7085. currentTestRunInfo = _testRunInfo;
  7086. }
  7087. virtual void testGroupStarting( GroupInfo const& _groupInfo ) CATCH_OVERRIDE {
  7088. currentGroupInfo = _groupInfo;
  7089. }
  7090. virtual void testCaseStarting( TestCaseInfo const& _testInfo ) CATCH_OVERRIDE {
  7091. currentTestCaseInfo = _testInfo;
  7092. }
  7093. virtual void sectionStarting( SectionInfo const& _sectionInfo ) CATCH_OVERRIDE {
  7094. m_sectionStack.push_back( _sectionInfo );
  7095. }
  7096. virtual void sectionEnded( SectionStats const& /* _sectionStats */ ) CATCH_OVERRIDE {
  7097. m_sectionStack.pop_back();
  7098. }
  7099. virtual void testCaseEnded( TestCaseStats const& /* _testCaseStats */ ) CATCH_OVERRIDE {
  7100. currentTestCaseInfo.reset();
  7101. }
  7102. virtual void testGroupEnded( TestGroupStats const& /* _testGroupStats */ ) CATCH_OVERRIDE {
  7103. currentGroupInfo.reset();
  7104. }
  7105. virtual void testRunEnded( TestRunStats const& /* _testRunStats */ ) CATCH_OVERRIDE {
  7106. currentTestCaseInfo.reset();
  7107. currentGroupInfo.reset();
  7108. currentTestRunInfo.reset();
  7109. }
  7110. virtual void skipTest( TestCaseInfo const& ) CATCH_OVERRIDE {
  7111. // Don't do anything with this by default.
  7112. // It can optionally be overridden in the derived class.
  7113. }
  7114. Ptr<IConfig const> m_config;
  7115. std::ostream& stream;
  7116. LazyStat<TestRunInfo> currentTestRunInfo;
  7117. LazyStat<GroupInfo> currentGroupInfo;
  7118. LazyStat<TestCaseInfo> currentTestCaseInfo;
  7119. std::vector<SectionInfo> m_sectionStack;
  7120. ReporterPreferences m_reporterPrefs;
  7121. };
  7122. struct CumulativeReporterBase : SharedImpl<IStreamingReporter> {
  7123. template<typename T, typename ChildNodeT>
  7124. struct Node : SharedImpl<> {
  7125. explicit Node( T const& _value ) : value( _value ) {}
  7126. virtual ~Node() {}
  7127. typedef std::vector<Ptr<ChildNodeT> > ChildNodes;
  7128. T value;
  7129. ChildNodes children;
  7130. };
  7131. struct SectionNode : SharedImpl<> {
  7132. explicit SectionNode( SectionStats const& _stats ) : stats( _stats ) {}
  7133. virtual ~SectionNode();
  7134. bool operator == ( SectionNode const& other ) const {
  7135. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  7136. }
  7137. bool operator == ( Ptr<SectionNode> const& other ) const {
  7138. return operator==( *other );
  7139. }
  7140. SectionStats stats;
  7141. typedef std::vector<Ptr<SectionNode> > ChildSections;
  7142. typedef std::vector<AssertionStats> Assertions;
  7143. ChildSections childSections;
  7144. Assertions assertions;
  7145. std::string stdOut;
  7146. std::string stdErr;
  7147. };
  7148. struct BySectionInfo {
  7149. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  7150. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  7151. bool operator() ( Ptr<SectionNode> const& node ) const {
  7152. return node->stats.sectionInfo.lineInfo == m_other.lineInfo;
  7153. }
  7154. private:
  7155. void operator=( BySectionInfo const& );
  7156. SectionInfo const& m_other;
  7157. };
  7158. typedef Node<TestCaseStats, SectionNode> TestCaseNode;
  7159. typedef Node<TestGroupStats, TestCaseNode> TestGroupNode;
  7160. typedef Node<TestRunStats, TestGroupNode> TestRunNode;
  7161. CumulativeReporterBase( ReporterConfig const& _config )
  7162. : m_config( _config.fullConfig() ),
  7163. stream( _config.stream() )
  7164. {
  7165. m_reporterPrefs.shouldRedirectStdOut = false;
  7166. }
  7167. ~CumulativeReporterBase();
  7168. virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE {
  7169. return m_reporterPrefs;
  7170. }
  7171. virtual void testRunStarting( TestRunInfo const& ) CATCH_OVERRIDE {}
  7172. virtual void testGroupStarting( GroupInfo const& ) CATCH_OVERRIDE {}
  7173. virtual void testCaseStarting( TestCaseInfo const& ) CATCH_OVERRIDE {}
  7174. virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE {
  7175. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  7176. Ptr<SectionNode> node;
  7177. if( m_sectionStack.empty() ) {
  7178. if( !m_rootSection )
  7179. m_rootSection = new SectionNode( incompleteStats );
  7180. node = m_rootSection;
  7181. }
  7182. else {
  7183. SectionNode& parentNode = *m_sectionStack.back();
  7184. SectionNode::ChildSections::const_iterator it =
  7185. std::find_if( parentNode.childSections.begin(),
  7186. parentNode.childSections.end(),
  7187. BySectionInfo( sectionInfo ) );
  7188. if( it == parentNode.childSections.end() ) {
  7189. node = new SectionNode( incompleteStats );
  7190. parentNode.childSections.push_back( node );
  7191. }
  7192. else
  7193. node = *it;
  7194. }
  7195. m_sectionStack.push_back( node );
  7196. m_deepestSection = node;
  7197. }
  7198. virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {}
  7199. virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE {
  7200. assert( !m_sectionStack.empty() );
  7201. SectionNode& sectionNode = *m_sectionStack.back();
  7202. sectionNode.assertions.push_back( assertionStats );
  7203. return true;
  7204. }
  7205. virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE {
  7206. assert( !m_sectionStack.empty() );
  7207. SectionNode& node = *m_sectionStack.back();
  7208. node.stats = sectionStats;
  7209. m_sectionStack.pop_back();
  7210. }
  7211. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE {
  7212. Ptr<TestCaseNode> node = new TestCaseNode( testCaseStats );
  7213. assert( m_sectionStack.size() == 0 );
  7214. node->children.push_back( m_rootSection );
  7215. m_testCases.push_back( node );
  7216. m_rootSection.reset();
  7217. assert( m_deepestSection );
  7218. m_deepestSection->stdOut = testCaseStats.stdOut;
  7219. m_deepestSection->stdErr = testCaseStats.stdErr;
  7220. }
  7221. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE {
  7222. Ptr<TestGroupNode> node = new TestGroupNode( testGroupStats );
  7223. node->children.swap( m_testCases );
  7224. m_testGroups.push_back( node );
  7225. }
  7226. virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE {
  7227. Ptr<TestRunNode> node = new TestRunNode( testRunStats );
  7228. node->children.swap( m_testGroups );
  7229. m_testRuns.push_back( node );
  7230. testRunEndedCumulative();
  7231. }
  7232. virtual void testRunEndedCumulative() = 0;
  7233. virtual void skipTest( TestCaseInfo const& ) CATCH_OVERRIDE {}
  7234. Ptr<IConfig const> m_config;
  7235. std::ostream& stream;
  7236. std::vector<AssertionStats> m_assertions;
  7237. std::vector<std::vector<Ptr<SectionNode> > > m_sections;
  7238. std::vector<Ptr<TestCaseNode> > m_testCases;
  7239. std::vector<Ptr<TestGroupNode> > m_testGroups;
  7240. std::vector<Ptr<TestRunNode> > m_testRuns;
  7241. Ptr<SectionNode> m_rootSection;
  7242. Ptr<SectionNode> m_deepestSection;
  7243. std::vector<Ptr<SectionNode> > m_sectionStack;
  7244. ReporterPreferences m_reporterPrefs;
  7245. };
  7246. template<char C>
  7247. char const* getLineOfChars() {
  7248. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  7249. if( !*line ) {
  7250. memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  7251. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  7252. }
  7253. return line;
  7254. }
  7255. struct TestEventListenerBase : StreamingReporterBase {
  7256. TestEventListenerBase( ReporterConfig const& _config )
  7257. : StreamingReporterBase( _config )
  7258. {}
  7259. virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {}
  7260. virtual bool assertionEnded( AssertionStats const& ) CATCH_OVERRIDE {
  7261. return false;
  7262. }
  7263. };
  7264. } // end namespace Catch
  7265. // #included from: ../internal/catch_reporter_registrars.hpp
  7266. #define TWOBLUECUBES_CATCH_REPORTER_REGISTRARS_HPP_INCLUDED
  7267. namespace Catch {
  7268. template<typename T>
  7269. class LegacyReporterRegistrar {
  7270. class ReporterFactory : public IReporterFactory {
  7271. virtual IStreamingReporter* create( ReporterConfig const& config ) const {
  7272. return new LegacyReporterAdapter( new T( config ) );
  7273. }
  7274. virtual std::string getDescription() const {
  7275. return T::getDescription();
  7276. }
  7277. };
  7278. public:
  7279. LegacyReporterRegistrar( std::string const& name ) {
  7280. getMutableRegistryHub().registerReporter( name, new ReporterFactory() );
  7281. }
  7282. };
  7283. template<typename T>
  7284. class ReporterRegistrar {
  7285. class ReporterFactory : public SharedImpl<IReporterFactory> {
  7286. // *** Please Note ***:
  7287. // - If you end up here looking at a compiler error because it's trying to register
  7288. // your custom reporter class be aware that the native reporter interface has changed
  7289. // to IStreamingReporter. The "legacy" interface, IReporter, is still supported via
  7290. // an adapter. Just use REGISTER_LEGACY_REPORTER to take advantage of the adapter.
  7291. // However please consider updating to the new interface as the old one is now
  7292. // deprecated and will probably be removed quite soon!
  7293. // Please contact me via github if you have any questions at all about this.
  7294. // In fact, ideally, please contact me anyway to let me know you've hit this - as I have
  7295. // no idea who is actually using custom reporters at all (possibly no-one!).
  7296. // The new interface is designed to minimise exposure to interface changes in the future.
  7297. virtual IStreamingReporter* create( ReporterConfig const& config ) const {
  7298. return new T( config );
  7299. }
  7300. virtual std::string getDescription() const {
  7301. return T::getDescription();
  7302. }
  7303. };
  7304. public:
  7305. ReporterRegistrar( std::string const& name ) {
  7306. getMutableRegistryHub().registerReporter( name, new ReporterFactory() );
  7307. }
  7308. };
  7309. template<typename T>
  7310. class ListenerRegistrar {
  7311. class ListenerFactory : public SharedImpl<IReporterFactory> {
  7312. virtual IStreamingReporter* create( ReporterConfig const& config ) const {
  7313. return new T( config );
  7314. }
  7315. virtual std::string getDescription() const {
  7316. return "";
  7317. }
  7318. };
  7319. public:
  7320. ListenerRegistrar() {
  7321. getMutableRegistryHub().registerListener( new ListenerFactory() );
  7322. }
  7323. };
  7324. }
  7325. #define INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) \
  7326. namespace{ Catch::LegacyReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); }
  7327. #define INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) \
  7328. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); }
  7329. #define INTERNAL_CATCH_REGISTER_LISTENER( listenerType ) \
  7330. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; }
  7331. // #included from: ../internal/catch_xmlwriter.hpp
  7332. #define TWOBLUECUBES_CATCH_XMLWRITER_HPP_INCLUDED
  7333. #include <sstream>
  7334. #include <string>
  7335. #include <vector>
  7336. #include <iomanip>
  7337. namespace Catch {
  7338. class XmlEncode {
  7339. public:
  7340. enum ForWhat { ForTextNodes, ForAttributes };
  7341. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes )
  7342. : m_str( str ),
  7343. m_forWhat( forWhat )
  7344. {}
  7345. void encodeTo( std::ostream& os ) const {
  7346. // Apostrophe escaping not necessary if we always use " to write attributes
  7347. // (see: http://www.w3.org/TR/xml/#syntax)
  7348. for( std::size_t i = 0; i < m_str.size(); ++ i ) {
  7349. char c = m_str[i];
  7350. switch( c ) {
  7351. case '<': os << "&lt;"; break;
  7352. case '&': os << "&amp;"; break;
  7353. case '>':
  7354. // See: http://www.w3.org/TR/xml/#syntax
  7355. if( i > 2 && m_str[i-1] == ']' && m_str[i-2] == ']' )
  7356. os << "&gt;";
  7357. else
  7358. os << c;
  7359. break;
  7360. case '\"':
  7361. if( m_forWhat == ForAttributes )
  7362. os << "&quot;";
  7363. else
  7364. os << c;
  7365. break;
  7366. default:
  7367. // Escape control chars - based on contribution by @espenalb in PR #465
  7368. if ( ( c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' )
  7369. os << "&#x" << std::uppercase << std::hex << static_cast<int>( c );
  7370. else
  7371. os << c;
  7372. }
  7373. }
  7374. }
  7375. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  7376. xmlEncode.encodeTo( os );
  7377. return os;
  7378. }
  7379. private:
  7380. std::string m_str;
  7381. ForWhat m_forWhat;
  7382. };
  7383. class XmlWriter {
  7384. public:
  7385. class ScopedElement {
  7386. public:
  7387. ScopedElement( XmlWriter* writer )
  7388. : m_writer( writer )
  7389. {}
  7390. ScopedElement( ScopedElement const& other )
  7391. : m_writer( other.m_writer ){
  7392. other.m_writer = CATCH_NULL;
  7393. }
  7394. ~ScopedElement() {
  7395. if( m_writer )
  7396. m_writer->endElement();
  7397. }
  7398. ScopedElement& writeText( std::string const& text, bool indent = true ) {
  7399. m_writer->writeText( text, indent );
  7400. return *this;
  7401. }
  7402. template<typename T>
  7403. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  7404. m_writer->writeAttribute( name, attribute );
  7405. return *this;
  7406. }
  7407. private:
  7408. mutable XmlWriter* m_writer;
  7409. };
  7410. XmlWriter()
  7411. : m_tagIsOpen( false ),
  7412. m_needsNewline( false ),
  7413. m_os( &Catch::cout() )
  7414. {}
  7415. XmlWriter( std::ostream& os )
  7416. : m_tagIsOpen( false ),
  7417. m_needsNewline( false ),
  7418. m_os( &os )
  7419. {}
  7420. ~XmlWriter() {
  7421. while( !m_tags.empty() )
  7422. endElement();
  7423. }
  7424. XmlWriter& startElement( std::string const& name ) {
  7425. ensureTagClosed();
  7426. newlineIfNecessary();
  7427. stream() << m_indent << "<" << name;
  7428. m_tags.push_back( name );
  7429. m_indent += " ";
  7430. m_tagIsOpen = true;
  7431. return *this;
  7432. }
  7433. ScopedElement scopedElement( std::string const& name ) {
  7434. ScopedElement scoped( this );
  7435. startElement( name );
  7436. return scoped;
  7437. }
  7438. XmlWriter& endElement() {
  7439. newlineIfNecessary();
  7440. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  7441. if( m_tagIsOpen ) {
  7442. stream() << "/>\n";
  7443. m_tagIsOpen = false;
  7444. }
  7445. else {
  7446. stream() << m_indent << "</" << m_tags.back() << ">\n";
  7447. }
  7448. m_tags.pop_back();
  7449. return *this;
  7450. }
  7451. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ) {
  7452. if( !name.empty() && !attribute.empty() )
  7453. stream() << " " << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << "\"";
  7454. return *this;
  7455. }
  7456. XmlWriter& writeAttribute( std::string const& name, bool attribute ) {
  7457. stream() << " " << name << "=\"" << ( attribute ? "true" : "false" ) << "\"";
  7458. return *this;
  7459. }
  7460. template<typename T>
  7461. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  7462. std::ostringstream oss;
  7463. oss << attribute;
  7464. return writeAttribute( name, oss.str() );
  7465. }
  7466. XmlWriter& writeText( std::string const& text, bool indent = true ) {
  7467. if( !text.empty() ){
  7468. bool tagWasOpen = m_tagIsOpen;
  7469. ensureTagClosed();
  7470. if( tagWasOpen && indent )
  7471. stream() << m_indent;
  7472. stream() << XmlEncode( text );
  7473. m_needsNewline = true;
  7474. }
  7475. return *this;
  7476. }
  7477. XmlWriter& writeComment( std::string const& text ) {
  7478. ensureTagClosed();
  7479. stream() << m_indent << "<!--" << text << "-->";
  7480. m_needsNewline = true;
  7481. return *this;
  7482. }
  7483. XmlWriter& writeBlankLine() {
  7484. ensureTagClosed();
  7485. stream() << "\n";
  7486. return *this;
  7487. }
  7488. void setStream( std::ostream& os ) {
  7489. m_os = &os;
  7490. }
  7491. private:
  7492. XmlWriter( XmlWriter const& );
  7493. void operator=( XmlWriter const& );
  7494. std::ostream& stream() {
  7495. return *m_os;
  7496. }
  7497. void ensureTagClosed() {
  7498. if( m_tagIsOpen ) {
  7499. stream() << ">\n";
  7500. m_tagIsOpen = false;
  7501. }
  7502. }
  7503. void newlineIfNecessary() {
  7504. if( m_needsNewline ) {
  7505. stream() << "\n";
  7506. m_needsNewline = false;
  7507. }
  7508. }
  7509. bool m_tagIsOpen;
  7510. bool m_needsNewline;
  7511. std::vector<std::string> m_tags;
  7512. std::string m_indent;
  7513. std::ostream* m_os;
  7514. };
  7515. }
  7516. // #included from: catch_reenable_warnings.h
  7517. #define TWOBLUECUBES_CATCH_REENABLE_WARNINGS_H_INCLUDED
  7518. #ifdef __clang__
  7519. # ifdef __ICC // icpc defines the __clang__ macro
  7520. # pragma warning(pop)
  7521. # else
  7522. # pragma clang diagnostic pop
  7523. # endif
  7524. #elif defined __GNUC__
  7525. # pragma GCC diagnostic pop
  7526. #endif
  7527. namespace Catch {
  7528. class XmlReporter : public StreamingReporterBase {
  7529. public:
  7530. XmlReporter( ReporterConfig const& _config )
  7531. : StreamingReporterBase( _config ),
  7532. m_sectionDepth( 0 )
  7533. {
  7534. m_reporterPrefs.shouldRedirectStdOut = true;
  7535. }
  7536. virtual ~XmlReporter() CATCH_OVERRIDE;
  7537. static std::string getDescription() {
  7538. return "Reports test results as an XML document";
  7539. }
  7540. public: // StreamingReporterBase
  7541. virtual void noMatchingTestCases( std::string const& s ) CATCH_OVERRIDE {
  7542. StreamingReporterBase::noMatchingTestCases( s );
  7543. }
  7544. virtual void testRunStarting( TestRunInfo const& testInfo ) CATCH_OVERRIDE {
  7545. StreamingReporterBase::testRunStarting( testInfo );
  7546. m_xml.setStream( stream );
  7547. m_xml.startElement( "Catch" );
  7548. if( !m_config->name().empty() )
  7549. m_xml.writeAttribute( "name", m_config->name() );
  7550. }
  7551. virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE {
  7552. StreamingReporterBase::testGroupStarting( groupInfo );
  7553. m_xml.startElement( "Group" )
  7554. .writeAttribute( "name", groupInfo.name );
  7555. }
  7556. virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE {
  7557. StreamingReporterBase::testCaseStarting(testInfo);
  7558. m_xml.startElement( "TestCase" ).writeAttribute( "name", trim( testInfo.name ) );
  7559. if ( m_config->showDurations() == ShowDurations::Always )
  7560. m_testCaseTimer.start();
  7561. }
  7562. virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE {
  7563. StreamingReporterBase::sectionStarting( sectionInfo );
  7564. if( m_sectionDepth++ > 0 ) {
  7565. m_xml.startElement( "Section" )
  7566. .writeAttribute( "name", trim( sectionInfo.name ) )
  7567. .writeAttribute( "description", sectionInfo.description );
  7568. }
  7569. }
  7570. virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE { }
  7571. virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE {
  7572. const AssertionResult& assertionResult = assertionStats.assertionResult;
  7573. // Print any info messages in <Info> tags.
  7574. if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) {
  7575. for( std::vector<MessageInfo>::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end();
  7576. it != itEnd;
  7577. ++it ) {
  7578. if( it->type == ResultWas::Info ) {
  7579. m_xml.scopedElement( "Info" )
  7580. .writeText( it->message );
  7581. } else if ( it->type == ResultWas::Warning ) {
  7582. m_xml.scopedElement( "Warning" )
  7583. .writeText( it->message );
  7584. }
  7585. }
  7586. }
  7587. // Drop out if result was successful but we're not printing them.
  7588. if( !m_config->includeSuccessfulResults() && isOk(assertionResult.getResultType()) )
  7589. return true;
  7590. // Print the expression if there is one.
  7591. if( assertionResult.hasExpression() ) {
  7592. m_xml.startElement( "Expression" )
  7593. .writeAttribute( "success", assertionResult.succeeded() )
  7594. .writeAttribute( "type", assertionResult.getTestMacroName() )
  7595. .writeAttribute( "filename", assertionResult.getSourceInfo().file )
  7596. .writeAttribute( "line", assertionResult.getSourceInfo().line );
  7597. m_xml.scopedElement( "Original" )
  7598. .writeText( assertionResult.getExpression() );
  7599. m_xml.scopedElement( "Expanded" )
  7600. .writeText( assertionResult.getExpandedExpression() );
  7601. }
  7602. // And... Print a result applicable to each result type.
  7603. switch( assertionResult.getResultType() ) {
  7604. case ResultWas::ThrewException:
  7605. m_xml.scopedElement( "Exception" )
  7606. .writeAttribute( "filename", assertionResult.getSourceInfo().file )
  7607. .writeAttribute( "line", assertionResult.getSourceInfo().line )
  7608. .writeText( assertionResult.getMessage() );
  7609. break;
  7610. case ResultWas::FatalErrorCondition:
  7611. m_xml.scopedElement( "Fatal Error Condition" )
  7612. .writeAttribute( "filename", assertionResult.getSourceInfo().file )
  7613. .writeAttribute( "line", assertionResult.getSourceInfo().line )
  7614. .writeText( assertionResult.getMessage() );
  7615. break;
  7616. case ResultWas::Info:
  7617. m_xml.scopedElement( "Info" )
  7618. .writeText( assertionResult.getMessage() );
  7619. break;
  7620. case ResultWas::Warning:
  7621. // Warning will already have been written
  7622. break;
  7623. case ResultWas::ExplicitFailure:
  7624. m_xml.scopedElement( "Failure" )
  7625. .writeText( assertionResult.getMessage() );
  7626. break;
  7627. default:
  7628. break;
  7629. }
  7630. if( assertionResult.hasExpression() )
  7631. m_xml.endElement();
  7632. return true;
  7633. }
  7634. virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE {
  7635. StreamingReporterBase::sectionEnded( sectionStats );
  7636. if( --m_sectionDepth > 0 ) {
  7637. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  7638. e.writeAttribute( "successes", sectionStats.assertions.passed );
  7639. e.writeAttribute( "failures", sectionStats.assertions.failed );
  7640. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  7641. if ( m_config->showDurations() == ShowDurations::Always )
  7642. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  7643. m_xml.endElement();
  7644. }
  7645. }
  7646. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE {
  7647. StreamingReporterBase::testCaseEnded( testCaseStats );
  7648. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  7649. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  7650. if ( m_config->showDurations() == ShowDurations::Always )
  7651. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  7652. m_xml.endElement();
  7653. }
  7654. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE {
  7655. StreamingReporterBase::testGroupEnded( testGroupStats );
  7656. // TODO: Check testGroupStats.aborting and act accordingly.
  7657. m_xml.scopedElement( "OverallResults" )
  7658. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  7659. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  7660. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  7661. m_xml.endElement();
  7662. }
  7663. virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE {
  7664. StreamingReporterBase::testRunEnded( testRunStats );
  7665. m_xml.scopedElement( "OverallResults" )
  7666. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  7667. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  7668. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  7669. m_xml.endElement();
  7670. }
  7671. private:
  7672. Timer m_testCaseTimer;
  7673. XmlWriter m_xml;
  7674. int m_sectionDepth;
  7675. };
  7676. INTERNAL_CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  7677. } // end namespace Catch
  7678. // #included from: ../reporters/catch_reporter_junit.hpp
  7679. #define TWOBLUECUBES_CATCH_REPORTER_JUNIT_HPP_INCLUDED
  7680. #include <assert.h>
  7681. namespace Catch {
  7682. class JunitReporter : public CumulativeReporterBase {
  7683. public:
  7684. JunitReporter( ReporterConfig const& _config )
  7685. : CumulativeReporterBase( _config ),
  7686. xml( _config.stream() )
  7687. {
  7688. m_reporterPrefs.shouldRedirectStdOut = true;
  7689. }
  7690. virtual ~JunitReporter() CATCH_OVERRIDE;
  7691. static std::string getDescription() {
  7692. return "Reports test results in an XML format that looks like Ant's junitreport target";
  7693. }
  7694. virtual void noMatchingTestCases( std::string const& /*spec*/ ) CATCH_OVERRIDE {}
  7695. virtual void testRunStarting( TestRunInfo const& runInfo ) CATCH_OVERRIDE {
  7696. CumulativeReporterBase::testRunStarting( runInfo );
  7697. xml.startElement( "testsuites" );
  7698. }
  7699. virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE {
  7700. suiteTimer.start();
  7701. stdOutForSuite.str("");
  7702. stdErrForSuite.str("");
  7703. unexpectedExceptions = 0;
  7704. CumulativeReporterBase::testGroupStarting( groupInfo );
  7705. }
  7706. virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE {
  7707. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException )
  7708. unexpectedExceptions++;
  7709. return CumulativeReporterBase::assertionEnded( assertionStats );
  7710. }
  7711. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE {
  7712. stdOutForSuite << testCaseStats.stdOut;
  7713. stdErrForSuite << testCaseStats.stdErr;
  7714. CumulativeReporterBase::testCaseEnded( testCaseStats );
  7715. }
  7716. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE {
  7717. double suiteTime = suiteTimer.getElapsedSeconds();
  7718. CumulativeReporterBase::testGroupEnded( testGroupStats );
  7719. writeGroup( *m_testGroups.back(), suiteTime );
  7720. }
  7721. virtual void testRunEndedCumulative() CATCH_OVERRIDE {
  7722. xml.endElement();
  7723. }
  7724. void writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  7725. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  7726. TestGroupStats const& stats = groupNode.value;
  7727. xml.writeAttribute( "name", stats.groupInfo.name );
  7728. xml.writeAttribute( "errors", unexpectedExceptions );
  7729. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  7730. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  7731. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  7732. if( m_config->showDurations() == ShowDurations::Never )
  7733. xml.writeAttribute( "time", "" );
  7734. else
  7735. xml.writeAttribute( "time", suiteTime );
  7736. xml.writeAttribute( "timestamp", "tbd" ); // !TBD
  7737. // Write test cases
  7738. for( TestGroupNode::ChildNodes::const_iterator
  7739. it = groupNode.children.begin(), itEnd = groupNode.children.end();
  7740. it != itEnd;
  7741. ++it )
  7742. writeTestCase( **it );
  7743. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite.str() ), false );
  7744. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite.str() ), false );
  7745. }
  7746. void writeTestCase( TestCaseNode const& testCaseNode ) {
  7747. TestCaseStats const& stats = testCaseNode.value;
  7748. // All test cases have exactly one section - which represents the
  7749. // test case itself. That section may have 0-n nested sections
  7750. assert( testCaseNode.children.size() == 1 );
  7751. SectionNode const& rootSection = *testCaseNode.children.front();
  7752. std::string className = stats.testInfo.className;
  7753. if( className.empty() ) {
  7754. if( rootSection.childSections.empty() )
  7755. className = "global";
  7756. }
  7757. writeSection( className, "", rootSection );
  7758. }
  7759. void writeSection( std::string const& className,
  7760. std::string const& rootName,
  7761. SectionNode const& sectionNode ) {
  7762. std::string name = trim( sectionNode.stats.sectionInfo.name );
  7763. if( !rootName.empty() )
  7764. name = rootName + "/" + name;
  7765. if( !sectionNode.assertions.empty() ||
  7766. !sectionNode.stdOut.empty() ||
  7767. !sectionNode.stdErr.empty() ) {
  7768. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  7769. if( className.empty() ) {
  7770. xml.writeAttribute( "classname", name );
  7771. xml.writeAttribute( "name", "root" );
  7772. }
  7773. else {
  7774. xml.writeAttribute( "classname", className );
  7775. xml.writeAttribute( "name", name );
  7776. }
  7777. xml.writeAttribute( "time", Catch::toString( sectionNode.stats.durationInSeconds ) );
  7778. writeAssertions( sectionNode );
  7779. if( !sectionNode.stdOut.empty() )
  7780. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  7781. if( !sectionNode.stdErr.empty() )
  7782. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  7783. }
  7784. for( SectionNode::ChildSections::const_iterator
  7785. it = sectionNode.childSections.begin(),
  7786. itEnd = sectionNode.childSections.end();
  7787. it != itEnd;
  7788. ++it )
  7789. if( className.empty() )
  7790. writeSection( name, "", **it );
  7791. else
  7792. writeSection( className, name, **it );
  7793. }
  7794. void writeAssertions( SectionNode const& sectionNode ) {
  7795. for( SectionNode::Assertions::const_iterator
  7796. it = sectionNode.assertions.begin(), itEnd = sectionNode.assertions.end();
  7797. it != itEnd;
  7798. ++it )
  7799. writeAssertion( *it );
  7800. }
  7801. void writeAssertion( AssertionStats const& stats ) {
  7802. AssertionResult const& result = stats.assertionResult;
  7803. if( !result.isOk() ) {
  7804. std::string elementName;
  7805. switch( result.getResultType() ) {
  7806. case ResultWas::ThrewException:
  7807. case ResultWas::FatalErrorCondition:
  7808. elementName = "error";
  7809. break;
  7810. case ResultWas::ExplicitFailure:
  7811. elementName = "failure";
  7812. break;
  7813. case ResultWas::ExpressionFailed:
  7814. elementName = "failure";
  7815. break;
  7816. case ResultWas::DidntThrowException:
  7817. elementName = "failure";
  7818. break;
  7819. // We should never see these here:
  7820. case ResultWas::Info:
  7821. case ResultWas::Warning:
  7822. case ResultWas::Ok:
  7823. case ResultWas::Unknown:
  7824. case ResultWas::FailureBit:
  7825. case ResultWas::Exception:
  7826. elementName = "internalError";
  7827. break;
  7828. }
  7829. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  7830. xml.writeAttribute( "message", result.getExpandedExpression() );
  7831. xml.writeAttribute( "type", result.getTestMacroName() );
  7832. std::ostringstream oss;
  7833. if( !result.getMessage().empty() )
  7834. oss << result.getMessage() << "\n";
  7835. for( std::vector<MessageInfo>::const_iterator
  7836. it = stats.infoMessages.begin(),
  7837. itEnd = stats.infoMessages.end();
  7838. it != itEnd;
  7839. ++it )
  7840. if( it->type == ResultWas::Info )
  7841. oss << it->message << "\n";
  7842. oss << "at " << result.getSourceInfo();
  7843. xml.writeText( oss.str(), false );
  7844. }
  7845. }
  7846. XmlWriter xml;
  7847. Timer suiteTimer;
  7848. std::ostringstream stdOutForSuite;
  7849. std::ostringstream stdErrForSuite;
  7850. unsigned int unexpectedExceptions;
  7851. };
  7852. INTERNAL_CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  7853. } // end namespace Catch
  7854. // #included from: ../reporters/catch_reporter_console.hpp
  7855. #define TWOBLUECUBES_CATCH_REPORTER_CONSOLE_HPP_INCLUDED
  7856. namespace Catch {
  7857. struct ConsoleReporter : StreamingReporterBase {
  7858. ConsoleReporter( ReporterConfig const& _config )
  7859. : StreamingReporterBase( _config ),
  7860. m_headerPrinted( false )
  7861. {}
  7862. virtual ~ConsoleReporter() CATCH_OVERRIDE;
  7863. static std::string getDescription() {
  7864. return "Reports test results as plain lines of text";
  7865. }
  7866. virtual void noMatchingTestCases( std::string const& spec ) CATCH_OVERRIDE {
  7867. stream << "No test cases matched '" << spec << "'" << std::endl;
  7868. }
  7869. virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {
  7870. }
  7871. virtual bool assertionEnded( AssertionStats const& _assertionStats ) CATCH_OVERRIDE {
  7872. AssertionResult const& result = _assertionStats.assertionResult;
  7873. bool printInfoMessages = true;
  7874. // Drop out if result was successful and we're not printing those
  7875. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  7876. if( result.getResultType() != ResultWas::Warning )
  7877. return false;
  7878. printInfoMessages = false;
  7879. }
  7880. lazyPrint();
  7881. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  7882. printer.print();
  7883. stream << std::endl;
  7884. return true;
  7885. }
  7886. virtual void sectionStarting( SectionInfo const& _sectionInfo ) CATCH_OVERRIDE {
  7887. m_headerPrinted = false;
  7888. StreamingReporterBase::sectionStarting( _sectionInfo );
  7889. }
  7890. virtual void sectionEnded( SectionStats const& _sectionStats ) CATCH_OVERRIDE {
  7891. if( _sectionStats.missingAssertions ) {
  7892. lazyPrint();
  7893. Colour colour( Colour::ResultError );
  7894. if( m_sectionStack.size() > 1 )
  7895. stream << "\nNo assertions in section";
  7896. else
  7897. stream << "\nNo assertions in test case";
  7898. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  7899. }
  7900. if( m_headerPrinted ) {
  7901. if( m_config->showDurations() == ShowDurations::Always )
  7902. stream << "Completed in " << _sectionStats.durationInSeconds << "s" << std::endl;
  7903. m_headerPrinted = false;
  7904. }
  7905. else {
  7906. if( m_config->showDurations() == ShowDurations::Always )
  7907. stream << _sectionStats.sectionInfo.name << " completed in " << _sectionStats.durationInSeconds << "s" << std::endl;
  7908. }
  7909. StreamingReporterBase::sectionEnded( _sectionStats );
  7910. }
  7911. virtual void testCaseEnded( TestCaseStats const& _testCaseStats ) CATCH_OVERRIDE {
  7912. StreamingReporterBase::testCaseEnded( _testCaseStats );
  7913. m_headerPrinted = false;
  7914. }
  7915. virtual void testGroupEnded( TestGroupStats const& _testGroupStats ) CATCH_OVERRIDE {
  7916. if( currentGroupInfo.used ) {
  7917. printSummaryDivider();
  7918. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  7919. printTotals( _testGroupStats.totals );
  7920. stream << "\n" << std::endl;
  7921. }
  7922. StreamingReporterBase::testGroupEnded( _testGroupStats );
  7923. }
  7924. virtual void testRunEnded( TestRunStats const& _testRunStats ) CATCH_OVERRIDE {
  7925. printTotalsDivider( _testRunStats.totals );
  7926. printTotals( _testRunStats.totals );
  7927. stream << std::endl;
  7928. StreamingReporterBase::testRunEnded( _testRunStats );
  7929. }
  7930. private:
  7931. class AssertionPrinter {
  7932. void operator= ( AssertionPrinter const& );
  7933. public:
  7934. AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages )
  7935. : stream( _stream ),
  7936. stats( _stats ),
  7937. result( _stats.assertionResult ),
  7938. colour( Colour::None ),
  7939. message( result.getMessage() ),
  7940. messages( _stats.infoMessages ),
  7941. printInfoMessages( _printInfoMessages )
  7942. {
  7943. switch( result.getResultType() ) {
  7944. case ResultWas::Ok:
  7945. colour = Colour::Success;
  7946. passOrFail = "PASSED";
  7947. //if( result.hasMessage() )
  7948. if( _stats.infoMessages.size() == 1 )
  7949. messageLabel = "with message";
  7950. if( _stats.infoMessages.size() > 1 )
  7951. messageLabel = "with messages";
  7952. break;
  7953. case ResultWas::ExpressionFailed:
  7954. if( result.isOk() ) {
  7955. colour = Colour::Success;
  7956. passOrFail = "FAILED - but was ok";
  7957. }
  7958. else {
  7959. colour = Colour::Error;
  7960. passOrFail = "FAILED";
  7961. }
  7962. if( _stats.infoMessages.size() == 1 )
  7963. messageLabel = "with message";
  7964. if( _stats.infoMessages.size() > 1 )
  7965. messageLabel = "with messages";
  7966. break;
  7967. case ResultWas::ThrewException:
  7968. colour = Colour::Error;
  7969. passOrFail = "FAILED";
  7970. messageLabel = "due to unexpected exception with message";
  7971. break;
  7972. case ResultWas::FatalErrorCondition:
  7973. colour = Colour::Error;
  7974. passOrFail = "FAILED";
  7975. messageLabel = "due to a fatal error condition";
  7976. break;
  7977. case ResultWas::DidntThrowException:
  7978. colour = Colour::Error;
  7979. passOrFail = "FAILED";
  7980. messageLabel = "because no exception was thrown where one was expected";
  7981. break;
  7982. case ResultWas::Info:
  7983. messageLabel = "info";
  7984. break;
  7985. case ResultWas::Warning:
  7986. messageLabel = "warning";
  7987. break;
  7988. case ResultWas::ExplicitFailure:
  7989. passOrFail = "FAILED";
  7990. colour = Colour::Error;
  7991. if( _stats.infoMessages.size() == 1 )
  7992. messageLabel = "explicitly with message";
  7993. if( _stats.infoMessages.size() > 1 )
  7994. messageLabel = "explicitly with messages";
  7995. break;
  7996. // These cases are here to prevent compiler warnings
  7997. case ResultWas::Unknown:
  7998. case ResultWas::FailureBit:
  7999. case ResultWas::Exception:
  8000. passOrFail = "** internal error **";
  8001. colour = Colour::Error;
  8002. break;
  8003. }
  8004. }
  8005. void print() const {
  8006. printSourceInfo();
  8007. if( stats.totals.assertions.total() > 0 ) {
  8008. if( result.isOk() )
  8009. stream << "\n";
  8010. printResultType();
  8011. printOriginalExpression();
  8012. printReconstructedExpression();
  8013. }
  8014. else {
  8015. stream << "\n";
  8016. }
  8017. printMessage();
  8018. }
  8019. private:
  8020. void printResultType() const {
  8021. if( !passOrFail.empty() ) {
  8022. Colour colourGuard( colour );
  8023. stream << passOrFail << ":\n";
  8024. }
  8025. }
  8026. void printOriginalExpression() const {
  8027. if( result.hasExpression() ) {
  8028. Colour colourGuard( Colour::OriginalExpression );
  8029. stream << " ";
  8030. stream << result.getExpressionInMacro();
  8031. stream << "\n";
  8032. }
  8033. }
  8034. void printReconstructedExpression() const {
  8035. if( result.hasExpandedExpression() ) {
  8036. stream << "with expansion:\n";
  8037. Colour colourGuard( Colour::ReconstructedExpression );
  8038. stream << Text( result.getExpandedExpression(), TextAttributes().setIndent(2) ) << "\n";
  8039. }
  8040. }
  8041. void printMessage() const {
  8042. if( !messageLabel.empty() )
  8043. stream << messageLabel << ":" << "\n";
  8044. for( std::vector<MessageInfo>::const_iterator it = messages.begin(), itEnd = messages.end();
  8045. it != itEnd;
  8046. ++it ) {
  8047. // If this assertion is a warning ignore any INFO messages
  8048. if( printInfoMessages || it->type != ResultWas::Info )
  8049. stream << Text( it->message, TextAttributes().setIndent(2) ) << "\n";
  8050. }
  8051. }
  8052. void printSourceInfo() const {
  8053. Colour colourGuard( Colour::FileName );
  8054. stream << result.getSourceInfo() << ": ";
  8055. }
  8056. std::ostream& stream;
  8057. AssertionStats const& stats;
  8058. AssertionResult const& result;
  8059. Colour::Code colour;
  8060. std::string passOrFail;
  8061. std::string messageLabel;
  8062. std::string message;
  8063. std::vector<MessageInfo> messages;
  8064. bool printInfoMessages;
  8065. };
  8066. void lazyPrint() {
  8067. if( !currentTestRunInfo.used )
  8068. lazyPrintRunInfo();
  8069. if( !currentGroupInfo.used )
  8070. lazyPrintGroupInfo();
  8071. if( !m_headerPrinted ) {
  8072. printTestCaseAndSectionHeader();
  8073. m_headerPrinted = true;
  8074. }
  8075. }
  8076. void lazyPrintRunInfo() {
  8077. stream << "\n" << getLineOfChars<'~'>() << "\n";
  8078. Colour colour( Colour::SecondaryText );
  8079. stream << currentTestRunInfo->name
  8080. << " is a Catch v" << libraryVersion << " host application.\n"
  8081. << "Run with -? for options\n\n";
  8082. if( m_config->rngSeed() != 0 )
  8083. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  8084. currentTestRunInfo.used = true;
  8085. }
  8086. void lazyPrintGroupInfo() {
  8087. if( !currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1 ) {
  8088. printClosedHeader( "Group: " + currentGroupInfo->name );
  8089. currentGroupInfo.used = true;
  8090. }
  8091. }
  8092. void printTestCaseAndSectionHeader() {
  8093. assert( !m_sectionStack.empty() );
  8094. printOpenHeader( currentTestCaseInfo->name );
  8095. if( m_sectionStack.size() > 1 ) {
  8096. Colour colourGuard( Colour::Headers );
  8097. std::vector<SectionInfo>::const_iterator
  8098. it = m_sectionStack.begin()+1, // Skip first section (test case)
  8099. itEnd = m_sectionStack.end();
  8100. for( ; it != itEnd; ++it )
  8101. printHeaderString( it->name, 2 );
  8102. }
  8103. SourceLineInfo lineInfo = m_sectionStack.front().lineInfo;
  8104. if( !lineInfo.empty() ){
  8105. stream << getLineOfChars<'-'>() << "\n";
  8106. Colour colourGuard( Colour::FileName );
  8107. stream << lineInfo << "\n";
  8108. }
  8109. stream << getLineOfChars<'.'>() << "\n" << std::endl;
  8110. }
  8111. void printClosedHeader( std::string const& _name ) {
  8112. printOpenHeader( _name );
  8113. stream << getLineOfChars<'.'>() << "\n";
  8114. }
  8115. void printOpenHeader( std::string const& _name ) {
  8116. stream << getLineOfChars<'-'>() << "\n";
  8117. {
  8118. Colour colourGuard( Colour::Headers );
  8119. printHeaderString( _name );
  8120. }
  8121. }
  8122. // if string has a : in first line will set indent to follow it on
  8123. // subsequent lines
  8124. void printHeaderString( std::string const& _string, std::size_t indent = 0 ) {
  8125. std::size_t i = _string.find( ": " );
  8126. if( i != std::string::npos )
  8127. i+=2;
  8128. else
  8129. i = 0;
  8130. stream << Text( _string, TextAttributes()
  8131. .setIndent( indent+i)
  8132. .setInitialIndent( indent ) ) << "\n";
  8133. }
  8134. struct SummaryColumn {
  8135. SummaryColumn( std::string const& _label, Colour::Code _colour )
  8136. : label( _label ),
  8137. colour( _colour )
  8138. {}
  8139. SummaryColumn addRow( std::size_t count ) {
  8140. std::ostringstream oss;
  8141. oss << count;
  8142. std::string row = oss.str();
  8143. for( std::vector<std::string>::iterator it = rows.begin(); it != rows.end(); ++it ) {
  8144. while( it->size() < row.size() )
  8145. *it = " " + *it;
  8146. while( it->size() > row.size() )
  8147. row = " " + row;
  8148. }
  8149. rows.push_back( row );
  8150. return *this;
  8151. }
  8152. std::string label;
  8153. Colour::Code colour;
  8154. std::vector<std::string> rows;
  8155. };
  8156. void printTotals( Totals const& totals ) {
  8157. if( totals.testCases.total() == 0 ) {
  8158. stream << Colour( Colour::Warning ) << "No tests ran\n";
  8159. }
  8160. else if( totals.assertions.total() > 0 && totals.testCases.allPassed() ) {
  8161. stream << Colour( Colour::ResultSuccess ) << "All tests passed";
  8162. stream << " ("
  8163. << pluralise( totals.assertions.passed, "assertion" ) << " in "
  8164. << pluralise( totals.testCases.passed, "test case" ) << ")"
  8165. << "\n";
  8166. }
  8167. else {
  8168. std::vector<SummaryColumn> columns;
  8169. columns.push_back( SummaryColumn( "", Colour::None )
  8170. .addRow( totals.testCases.total() )
  8171. .addRow( totals.assertions.total() ) );
  8172. columns.push_back( SummaryColumn( "passed", Colour::Success )
  8173. .addRow( totals.testCases.passed )
  8174. .addRow( totals.assertions.passed ) );
  8175. columns.push_back( SummaryColumn( "failed", Colour::ResultError )
  8176. .addRow( totals.testCases.failed )
  8177. .addRow( totals.assertions.failed ) );
  8178. columns.push_back( SummaryColumn( "failed as expected", Colour::ResultExpectedFailure )
  8179. .addRow( totals.testCases.failedButOk )
  8180. .addRow( totals.assertions.failedButOk ) );
  8181. printSummaryRow( "test cases", columns, 0 );
  8182. printSummaryRow( "assertions", columns, 1 );
  8183. }
  8184. }
  8185. void printSummaryRow( std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row ) {
  8186. for( std::vector<SummaryColumn>::const_iterator it = cols.begin(); it != cols.end(); ++it ) {
  8187. std::string value = it->rows[row];
  8188. if( it->label.empty() ) {
  8189. stream << label << ": ";
  8190. if( value != "0" )
  8191. stream << value;
  8192. else
  8193. stream << Colour( Colour::Warning ) << "- none -";
  8194. }
  8195. else if( value != "0" ) {
  8196. stream << Colour( Colour::LightGrey ) << " | ";
  8197. stream << Colour( it->colour )
  8198. << value << " " << it->label;
  8199. }
  8200. }
  8201. stream << "\n";
  8202. }
  8203. static std::size_t makeRatio( std::size_t number, std::size_t total ) {
  8204. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number/ total : 0;
  8205. return ( ratio == 0 && number > 0 ) ? 1 : ratio;
  8206. }
  8207. static std::size_t& findMax( std::size_t& i, std::size_t& j, std::size_t& k ) {
  8208. if( i > j && i > k )
  8209. return i;
  8210. else if( j > k )
  8211. return j;
  8212. else
  8213. return k;
  8214. }
  8215. void printTotalsDivider( Totals const& totals ) {
  8216. if( totals.testCases.total() > 0 ) {
  8217. std::size_t failedRatio = makeRatio( totals.testCases.failed, totals.testCases.total() );
  8218. std::size_t failedButOkRatio = makeRatio( totals.testCases.failedButOk, totals.testCases.total() );
  8219. std::size_t passedRatio = makeRatio( totals.testCases.passed, totals.testCases.total() );
  8220. while( failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH-1 )
  8221. findMax( failedRatio, failedButOkRatio, passedRatio )++;
  8222. while( failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH-1 )
  8223. findMax( failedRatio, failedButOkRatio, passedRatio )--;
  8224. stream << Colour( Colour::Error ) << std::string( failedRatio, '=' );
  8225. stream << Colour( Colour::ResultExpectedFailure ) << std::string( failedButOkRatio, '=' );
  8226. if( totals.testCases.allPassed() )
  8227. stream << Colour( Colour::ResultSuccess ) << std::string( passedRatio, '=' );
  8228. else
  8229. stream << Colour( Colour::Success ) << std::string( passedRatio, '=' );
  8230. }
  8231. else {
  8232. stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH-1, '=' );
  8233. }
  8234. stream << "\n";
  8235. }
  8236. void printSummaryDivider() {
  8237. stream << getLineOfChars<'-'>() << "\n";
  8238. }
  8239. private:
  8240. bool m_headerPrinted;
  8241. };
  8242. INTERNAL_CATCH_REGISTER_REPORTER( "console", ConsoleReporter )
  8243. } // end namespace Catch
  8244. // #included from: ../reporters/catch_reporter_compact.hpp
  8245. #define TWOBLUECUBES_CATCH_REPORTER_COMPACT_HPP_INCLUDED
  8246. namespace Catch {
  8247. struct CompactReporter : StreamingReporterBase {
  8248. CompactReporter( ReporterConfig const& _config )
  8249. : StreamingReporterBase( _config )
  8250. {}
  8251. virtual ~CompactReporter();
  8252. static std::string getDescription() {
  8253. return "Reports test results on a single line, suitable for IDEs";
  8254. }
  8255. virtual ReporterPreferences getPreferences() const {
  8256. ReporterPreferences prefs;
  8257. prefs.shouldRedirectStdOut = false;
  8258. return prefs;
  8259. }
  8260. virtual void noMatchingTestCases( std::string const& spec ) {
  8261. stream << "No test cases matched '" << spec << "'" << std::endl;
  8262. }
  8263. virtual void assertionStarting( AssertionInfo const& ) {
  8264. }
  8265. virtual bool assertionEnded( AssertionStats const& _assertionStats ) {
  8266. AssertionResult const& result = _assertionStats.assertionResult;
  8267. bool printInfoMessages = true;
  8268. // Drop out if result was successful and we're not printing those
  8269. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  8270. if( result.getResultType() != ResultWas::Warning )
  8271. return false;
  8272. printInfoMessages = false;
  8273. }
  8274. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  8275. printer.print();
  8276. stream << std::endl;
  8277. return true;
  8278. }
  8279. virtual void testRunEnded( TestRunStats const& _testRunStats ) {
  8280. printTotals( _testRunStats.totals );
  8281. stream << "\n" << std::endl;
  8282. StreamingReporterBase::testRunEnded( _testRunStats );
  8283. }
  8284. private:
  8285. class AssertionPrinter {
  8286. void operator= ( AssertionPrinter const& );
  8287. public:
  8288. AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages )
  8289. : stream( _stream )
  8290. , stats( _stats )
  8291. , result( _stats.assertionResult )
  8292. , messages( _stats.infoMessages )
  8293. , itMessage( _stats.infoMessages.begin() )
  8294. , printInfoMessages( _printInfoMessages )
  8295. {}
  8296. void print() {
  8297. printSourceInfo();
  8298. itMessage = messages.begin();
  8299. switch( result.getResultType() ) {
  8300. case ResultWas::Ok:
  8301. printResultType( Colour::ResultSuccess, passedString() );
  8302. printOriginalExpression();
  8303. printReconstructedExpression();
  8304. if ( ! result.hasExpression() )
  8305. printRemainingMessages( Colour::None );
  8306. else
  8307. printRemainingMessages();
  8308. break;
  8309. case ResultWas::ExpressionFailed:
  8310. if( result.isOk() )
  8311. printResultType( Colour::ResultSuccess, failedString() + std::string( " - but was ok" ) );
  8312. else
  8313. printResultType( Colour::Error, failedString() );
  8314. printOriginalExpression();
  8315. printReconstructedExpression();
  8316. printRemainingMessages();
  8317. break;
  8318. case ResultWas::ThrewException:
  8319. printResultType( Colour::Error, failedString() );
  8320. printIssue( "unexpected exception with message:" );
  8321. printMessage();
  8322. printExpressionWas();
  8323. printRemainingMessages();
  8324. break;
  8325. case ResultWas::FatalErrorCondition:
  8326. printResultType( Colour::Error, failedString() );
  8327. printIssue( "fatal error condition with message:" );
  8328. printMessage();
  8329. printExpressionWas();
  8330. printRemainingMessages();
  8331. break;
  8332. case ResultWas::DidntThrowException:
  8333. printResultType( Colour::Error, failedString() );
  8334. printIssue( "expected exception, got none" );
  8335. printExpressionWas();
  8336. printRemainingMessages();
  8337. break;
  8338. case ResultWas::Info:
  8339. printResultType( Colour::None, "info" );
  8340. printMessage();
  8341. printRemainingMessages();
  8342. break;
  8343. case ResultWas::Warning:
  8344. printResultType( Colour::None, "warning" );
  8345. printMessage();
  8346. printRemainingMessages();
  8347. break;
  8348. case ResultWas::ExplicitFailure:
  8349. printResultType( Colour::Error, failedString() );
  8350. printIssue( "explicitly" );
  8351. printRemainingMessages( Colour::None );
  8352. break;
  8353. // These cases are here to prevent compiler warnings
  8354. case ResultWas::Unknown:
  8355. case ResultWas::FailureBit:
  8356. case ResultWas::Exception:
  8357. printResultType( Colour::Error, "** internal error **" );
  8358. break;
  8359. }
  8360. }
  8361. private:
  8362. // Colour::LightGrey
  8363. static Colour::Code dimColour() { return Colour::FileName; }
  8364. #ifdef CATCH_PLATFORM_MAC
  8365. static const char* failedString() { return "FAILED"; }
  8366. static const char* passedString() { return "PASSED"; }
  8367. #else
  8368. static const char* failedString() { return "failed"; }
  8369. static const char* passedString() { return "passed"; }
  8370. #endif
  8371. void printSourceInfo() const {
  8372. Colour colourGuard( Colour::FileName );
  8373. stream << result.getSourceInfo() << ":";
  8374. }
  8375. void printResultType( Colour::Code colour, std::string passOrFail ) const {
  8376. if( !passOrFail.empty() ) {
  8377. {
  8378. Colour colourGuard( colour );
  8379. stream << " " << passOrFail;
  8380. }
  8381. stream << ":";
  8382. }
  8383. }
  8384. void printIssue( std::string issue ) const {
  8385. stream << " " << issue;
  8386. }
  8387. void printExpressionWas() {
  8388. if( result.hasExpression() ) {
  8389. stream << ";";
  8390. {
  8391. Colour colour( dimColour() );
  8392. stream << " expression was:";
  8393. }
  8394. printOriginalExpression();
  8395. }
  8396. }
  8397. void printOriginalExpression() const {
  8398. if( result.hasExpression() ) {
  8399. stream << " " << result.getExpression();
  8400. }
  8401. }
  8402. void printReconstructedExpression() const {
  8403. if( result.hasExpandedExpression() ) {
  8404. {
  8405. Colour colour( dimColour() );
  8406. stream << " for: ";
  8407. }
  8408. stream << result.getExpandedExpression();
  8409. }
  8410. }
  8411. void printMessage() {
  8412. if ( itMessage != messages.end() ) {
  8413. stream << " '" << itMessage->message << "'";
  8414. ++itMessage;
  8415. }
  8416. }
  8417. void printRemainingMessages( Colour::Code colour = dimColour() ) {
  8418. if ( itMessage == messages.end() )
  8419. return;
  8420. // using messages.end() directly yields compilation error:
  8421. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  8422. const std::size_t N = static_cast<std::size_t>( std::distance( itMessage, itEnd ) );
  8423. {
  8424. Colour colourGuard( colour );
  8425. stream << " with " << pluralise( N, "message" ) << ":";
  8426. }
  8427. for(; itMessage != itEnd; ) {
  8428. // If this assertion is a warning ignore any INFO messages
  8429. if( printInfoMessages || itMessage->type != ResultWas::Info ) {
  8430. stream << " '" << itMessage->message << "'";
  8431. if ( ++itMessage != itEnd ) {
  8432. Colour colourGuard( dimColour() );
  8433. stream << " and";
  8434. }
  8435. }
  8436. }
  8437. }
  8438. private:
  8439. std::ostream& stream;
  8440. AssertionStats const& stats;
  8441. AssertionResult const& result;
  8442. std::vector<MessageInfo> messages;
  8443. std::vector<MessageInfo>::const_iterator itMessage;
  8444. bool printInfoMessages;
  8445. };
  8446. // Colour, message variants:
  8447. // - white: No tests ran.
  8448. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  8449. // - white: Passed [both/all] N test cases (no assertions).
  8450. // - red: Failed N tests cases, failed M assertions.
  8451. // - green: Passed [both/all] N tests cases with M assertions.
  8452. std::string bothOrAll( std::size_t count ) const {
  8453. return count == 1 ? "" : count == 2 ? "both " : "all " ;
  8454. }
  8455. void printTotals( const Totals& totals ) const {
  8456. if( totals.testCases.total() == 0 ) {
  8457. stream << "No tests ran.";
  8458. }
  8459. else if( totals.testCases.failed == totals.testCases.total() ) {
  8460. Colour colour( Colour::ResultError );
  8461. const std::string qualify_assertions_failed =
  8462. totals.assertions.failed == totals.assertions.total() ?
  8463. bothOrAll( totals.assertions.failed ) : "";
  8464. stream <<
  8465. "Failed " << bothOrAll( totals.testCases.failed )
  8466. << pluralise( totals.testCases.failed, "test case" ) << ", "
  8467. "failed " << qualify_assertions_failed <<
  8468. pluralise( totals.assertions.failed, "assertion" ) << ".";
  8469. }
  8470. else if( totals.assertions.total() == 0 ) {
  8471. stream <<
  8472. "Passed " << bothOrAll( totals.testCases.total() )
  8473. << pluralise( totals.testCases.total(), "test case" )
  8474. << " (no assertions).";
  8475. }
  8476. else if( totals.assertions.failed ) {
  8477. Colour colour( Colour::ResultError );
  8478. stream <<
  8479. "Failed " << pluralise( totals.testCases.failed, "test case" ) << ", "
  8480. "failed " << pluralise( totals.assertions.failed, "assertion" ) << ".";
  8481. }
  8482. else {
  8483. Colour colour( Colour::ResultSuccess );
  8484. stream <<
  8485. "Passed " << bothOrAll( totals.testCases.passed )
  8486. << pluralise( totals.testCases.passed, "test case" ) <<
  8487. " with " << pluralise( totals.assertions.passed, "assertion" ) << ".";
  8488. }
  8489. }
  8490. };
  8491. INTERNAL_CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  8492. } // end namespace Catch
  8493. namespace Catch {
  8494. // These are all here to avoid warnings about not having any out of line
  8495. // virtual methods
  8496. NonCopyable::~NonCopyable() {}
  8497. IShared::~IShared() {}
  8498. IStream::~IStream() CATCH_NOEXCEPT {}
  8499. FileStream::~FileStream() CATCH_NOEXCEPT {}
  8500. CoutStream::~CoutStream() CATCH_NOEXCEPT {}
  8501. DebugOutStream::~DebugOutStream() CATCH_NOEXCEPT {}
  8502. StreamBufBase::~StreamBufBase() CATCH_NOEXCEPT {}
  8503. IContext::~IContext() {}
  8504. IResultCapture::~IResultCapture() {}
  8505. ITestCase::~ITestCase() {}
  8506. ITestCaseRegistry::~ITestCaseRegistry() {}
  8507. IRegistryHub::~IRegistryHub() {}
  8508. IMutableRegistryHub::~IMutableRegistryHub() {}
  8509. IExceptionTranslator::~IExceptionTranslator() {}
  8510. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() {}
  8511. IReporter::~IReporter() {}
  8512. IReporterFactory::~IReporterFactory() {}
  8513. IReporterRegistry::~IReporterRegistry() {}
  8514. IStreamingReporter::~IStreamingReporter() {}
  8515. AssertionStats::~AssertionStats() {}
  8516. SectionStats::~SectionStats() {}
  8517. TestCaseStats::~TestCaseStats() {}
  8518. TestGroupStats::~TestGroupStats() {}
  8519. TestRunStats::~TestRunStats() {}
  8520. CumulativeReporterBase::SectionNode::~SectionNode() {}
  8521. CumulativeReporterBase::~CumulativeReporterBase() {}
  8522. StreamingReporterBase::~StreamingReporterBase() {}
  8523. ConsoleReporter::~ConsoleReporter() {}
  8524. CompactReporter::~CompactReporter() {}
  8525. IRunner::~IRunner() {}
  8526. IMutableContext::~IMutableContext() {}
  8527. IConfig::~IConfig() {}
  8528. XmlReporter::~XmlReporter() {}
  8529. JunitReporter::~JunitReporter() {}
  8530. TestRegistry::~TestRegistry() {}
  8531. FreeFunctionTestCase::~FreeFunctionTestCase() {}
  8532. IGeneratorInfo::~IGeneratorInfo() {}
  8533. IGeneratorsForTest::~IGeneratorsForTest() {}
  8534. WildcardPattern::~WildcardPattern() {}
  8535. TestSpec::Pattern::~Pattern() {}
  8536. TestSpec::NamePattern::~NamePattern() {}
  8537. TestSpec::TagPattern::~TagPattern() {}
  8538. TestSpec::ExcludedPattern::~ExcludedPattern() {}
  8539. Matchers::Impl::StdString::Equals::~Equals() {}
  8540. Matchers::Impl::StdString::Contains::~Contains() {}
  8541. Matchers::Impl::StdString::StartsWith::~StartsWith() {}
  8542. Matchers::Impl::StdString::EndsWith::~EndsWith() {}
  8543. void Config::dummy() {}
  8544. namespace TestCaseTracking {
  8545. ITracker::~ITracker() {}
  8546. TrackerBase::~TrackerBase() {}
  8547. SectionTracker::~SectionTracker() {}
  8548. IndexTracker::~IndexTracker() {}
  8549. }
  8550. }
  8551. #ifdef __clang__
  8552. #pragma clang diagnostic pop
  8553. #endif
  8554. #endif
  8555. #ifdef CATCH_CONFIG_MAIN
  8556. // #included from: internal/catch_default_main.hpp
  8557. #define TWOBLUECUBES_CATCH_DEFAULT_MAIN_HPP_INCLUDED
  8558. #ifndef __OBJC__
  8559. // Standard C/C++ main entry point
  8560. int main (int argc, char * argv[]) {
  8561. return Catch::Session().run( argc, argv );
  8562. }
  8563. #else // __OBJC__
  8564. // Objective-C entry point
  8565. int main (int argc, char * const argv[]) {
  8566. #if !CATCH_ARC_ENABLED
  8567. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  8568. #endif
  8569. Catch::registerTestMethods();
  8570. int result = Catch::Session().run( argc, (char* const*)argv );
  8571. #if !CATCH_ARC_ENABLED
  8572. [pool drain];
  8573. #endif
  8574. return result;
  8575. }
  8576. #endif // __OBJC__
  8577. #endif
  8578. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  8579. # undef CLARA_CONFIG_MAIN
  8580. #endif
  8581. //////
  8582. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  8583. #ifdef CATCH_CONFIG_PREFIX_ALL
  8584. #define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE" )
  8585. #define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "CATCH_REQUIRE_FALSE" )
  8586. #define CATCH_REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, "", "CATCH_REQUIRE_THROWS" )
  8587. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THROWS_AS" )
  8588. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, matcher, "CATCH_REQUIRE_THROWS_WITH" )
  8589. #define CATCH_REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_NOTHROW" )
  8590. #define CATCH_CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK" )
  8591. #define CATCH_CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CATCH_CHECK_FALSE" )
  8592. #define CATCH_CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_IF" )
  8593. #define CATCH_CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECKED_ELSE" )
  8594. #define CATCH_CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CATCH_CHECK_NOFAIL" )
  8595. #define CATCH_CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS" )
  8596. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THROWS_AS" )
  8597. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, matcher, "CATCH_CHECK_THROWS_WITH" )
  8598. #define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_NOTHROW" )
  8599. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CATCH_CHECK_THAT" )
  8600. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "CATCH_REQUIRE_THAT" )
  8601. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" )
  8602. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "CATCH_WARN", msg )
  8603. #define CATCH_SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "CATCH_INFO" )
  8604. #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" )
  8605. #define CATCH_SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CATCH_CAPTURE" )
  8606. #ifdef CATCH_CONFIG_VARIADIC_MACROS
  8607. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  8608. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  8609. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  8610. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  8611. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  8612. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", __VA_ARGS__ )
  8613. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", __VA_ARGS__ )
  8614. #else
  8615. #define CATCH_TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description )
  8616. #define CATCH_TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description )
  8617. #define CATCH_METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description )
  8618. #define CATCH_REGISTER_TEST_CASE( function, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( function, name, description )
  8619. #define CATCH_SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description )
  8620. #define CATCH_FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "CATCH_FAIL", msg )
  8621. #define CATCH_SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "CATCH_SUCCEED", msg )
  8622. #endif
  8623. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" )
  8624. #define CATCH_REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType )
  8625. #define CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType )
  8626. #define CATCH_GENERATE( expr) INTERNAL_CATCH_GENERATE( expr )
  8627. // "BDD-style" convenience wrappers
  8628. #ifdef CATCH_CONFIG_VARIADIC_MACROS
  8629. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  8630. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  8631. #else
  8632. #define CATCH_SCENARIO( name, tags ) CATCH_TEST_CASE( "Scenario: " name, tags )
  8633. #define CATCH_SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags )
  8634. #endif
  8635. #define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( "Given: ") + desc, "" )
  8636. #define CATCH_WHEN( desc ) CATCH_SECTION( std::string( " When: ") + desc, "" )
  8637. #define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( " And: ") + desc, "" )
  8638. #define CATCH_THEN( desc ) CATCH_SECTION( std::string( " Then: ") + desc, "" )
  8639. #define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( " And: ") + desc, "" )
  8640. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  8641. #else
  8642. #define REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, "REQUIRE" )
  8643. #define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, "REQUIRE_FALSE" )
  8644. #define REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, "", "REQUIRE_THROWS" )
  8645. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, "REQUIRE_THROWS_AS" )
  8646. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, matcher, "REQUIRE_THROWS_WITH" )
  8647. #define REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, "REQUIRE_NOTHROW" )
  8648. #define CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK" )
  8649. #define CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, "CHECK_FALSE" )
  8650. #define CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_IF" )
  8651. #define CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECKED_ELSE" )
  8652. #define CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, "CHECK_NOFAIL" )
  8653. #define CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, "", "CHECK_THROWS" )
  8654. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THROWS_AS" )
  8655. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, matcher, "CHECK_THROWS_WITH" )
  8656. #define CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, "CHECK_NOTHROW" )
  8657. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, "CHECK_THAT" )
  8658. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, "REQUIRE_THAT" )
  8659. #define INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" )
  8660. #define WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, "WARN", msg )
  8661. #define SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, "INFO" )
  8662. #define CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" )
  8663. #define SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg " := " << msg, "CAPTURE" )
  8664. #ifdef CATCH_CONFIG_VARIADIC_MACROS
  8665. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  8666. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  8667. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  8668. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  8669. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  8670. #define FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", __VA_ARGS__ )
  8671. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", __VA_ARGS__ )
  8672. #else
  8673. #define TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description )
  8674. #define TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description )
  8675. #define METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description )
  8676. #define REGISTER_TEST_CASE( method, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( method, name, description )
  8677. #define SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description )
  8678. #define FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, "FAIL", msg )
  8679. #define SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, "SUCCEED", msg )
  8680. #endif
  8681. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( "", "" )
  8682. #define REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType )
  8683. #define REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType )
  8684. #define GENERATE( expr) INTERNAL_CATCH_GENERATE( expr )
  8685. #endif
  8686. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  8687. // "BDD-style" convenience wrappers
  8688. #ifdef CATCH_CONFIG_VARIADIC_MACROS
  8689. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  8690. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  8691. #else
  8692. #define SCENARIO( name, tags ) TEST_CASE( "Scenario: " name, tags )
  8693. #define SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " name, tags )
  8694. #endif
  8695. #define GIVEN( desc ) SECTION( std::string(" Given: ") + desc, "" )
  8696. #define WHEN( desc ) SECTION( std::string(" When: ") + desc, "" )
  8697. #define AND_WHEN( desc ) SECTION( std::string("And when: ") + desc, "" )
  8698. #define THEN( desc ) SECTION( std::string(" Then: ") + desc, "" )
  8699. #define AND_THEN( desc ) SECTION( std::string(" And: ") + desc, "" )
  8700. using Catch::Detail::Approx;
  8701. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED