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.

12735 lines
422KB

  1. /*
  2. * Catch v2.1.0
  3. * Generated: 2018-01-10 13:51:15.378034
  4. * ----------------------------------------------------------
  5. * This file has been merged from multiple headers. Please don't edit it directly
  6. * Copyright (c) 2018 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. // start catch.hpp
  14. #ifdef __clang__
  15. # pragma clang system_header
  16. #elif defined __GNUC__
  17. # pragma GCC system_header
  18. #endif
  19. // start 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 "-Wunused-variable"
  26. # pragma clang diagnostic push
  27. # pragma clang diagnostic ignored "-Wpadded"
  28. # pragma clang diagnostic ignored "-Wswitch-enum"
  29. # pragma clang diagnostic ignored "-Wcovered-switch-default"
  30. # endif
  31. #elif defined __GNUC__
  32. # pragma GCC diagnostic ignored "-Wunused-variable"
  33. # pragma GCC diagnostic ignored "-Wparentheses"
  34. # pragma GCC diagnostic push
  35. # pragma GCC diagnostic ignored "-Wpadded"
  36. #endif
  37. // end catch_suppress_warnings.h
  38. #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
  39. # define CATCH_IMPL
  40. # define CATCH_CONFIG_ALL_PARTS
  41. #endif
  42. // In the impl file, we want to have access to all parts of the headers
  43. // Can also be used to sanely support PCHs
  44. #if defined(CATCH_CONFIG_ALL_PARTS)
  45. # define CATCH_CONFIG_EXTERNAL_INTERFACES
  46. # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
  47. # undef CATCH_CONFIG_DISABLE_MATCHERS
  48. # endif
  49. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  50. #endif
  51. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  52. // start catch_platform.h
  53. #ifdef __APPLE__
  54. # include <TargetConditionals.h>
  55. # if TARGET_OS_OSX == 1
  56. # define CATCH_PLATFORM_MAC
  57. # elif TARGET_OS_IPHONE == 1
  58. # define CATCH_PLATFORM_IPHONE
  59. # endif
  60. #elif defined(linux) || defined(__linux) || defined(__linux__)
  61. # define CATCH_PLATFORM_LINUX
  62. #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
  63. # define CATCH_PLATFORM_WINDOWS
  64. #endif
  65. // end catch_platform.h
  66. #ifdef CATCH_IMPL
  67. # ifndef CLARA_CONFIG_MAIN
  68. # define CLARA_CONFIG_MAIN_NOT_DEFINED
  69. # define CLARA_CONFIG_MAIN
  70. # endif
  71. #endif
  72. // start catch_user_interfaces.h
  73. namespace Catch {
  74. unsigned int rngSeed();
  75. }
  76. // end catch_user_interfaces.h
  77. // start catch_tag_alias_autoregistrar.h
  78. // start catch_common.h
  79. // start catch_compiler_capabilities.h
  80. // Detect a number of compiler features - by compiler
  81. // The following features are defined:
  82. //
  83. // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
  84. // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
  85. // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
  86. // ****************
  87. // Note to maintainers: if new toggles are added please document them
  88. // in configuration.md, too
  89. // ****************
  90. // In general each macro has a _NO_<feature name> form
  91. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  92. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  93. // can be combined, en-mass, with the _NO_ forms later.
  94. #ifdef __cplusplus
  95. # if __cplusplus >= 201402L
  96. # define CATCH_CPP14_OR_GREATER
  97. # endif
  98. #endif
  99. #ifdef __clang__
  100. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  101. _Pragma( "clang diagnostic push" ) \
  102. _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
  103. _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
  104. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  105. _Pragma( "clang diagnostic pop" )
  106. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  107. _Pragma( "clang diagnostic push" ) \
  108. _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
  109. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  110. _Pragma( "clang diagnostic pop" )
  111. #endif // __clang__
  112. ////////////////////////////////////////////////////////////////////////////////
  113. // We know some environments not to support full POSIX signals
  114. #if defined(__CYGWIN__) || defined(__QNX__)
  115. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  116. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  117. # endif
  118. #endif
  119. #ifdef __OS400__
  120. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  121. # define CATCH_CONFIG_COLOUR_NONE
  122. #endif
  123. ////////////////////////////////////////////////////////////////////////////////
  124. // Cygwin
  125. #ifdef __CYGWIN__
  126. // Required for some versions of Cygwin to declare gettimeofday
  127. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  128. # define _BSD_SOURCE
  129. #endif // __CYGWIN__
  130. ////////////////////////////////////////////////////////////////////////////////
  131. // Visual C++
  132. #ifdef _MSC_VER
  133. // Universal Windows platform does not support SEH
  134. // Or console colours (or console at all...)
  135. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  136. # define CATCH_CONFIG_COLOUR_NONE
  137. # else
  138. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  139. # endif
  140. #endif // _MSC_VER
  141. ////////////////////////////////////////////////////////////////////////////////
  142. // Use of __COUNTER__ is suppressed during code analysis in
  143. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  144. // handled by it.
  145. // Otherwise all supported compilers support COUNTER macro,
  146. // but user still might want to turn it off
  147. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  148. #define CATCH_INTERNAL_CONFIG_COUNTER
  149. #endif
  150. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  151. # define CATCH_CONFIG_COUNTER
  152. #endif
  153. #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH)
  154. # define CATCH_CONFIG_WINDOWS_SEH
  155. #endif
  156. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  157. #if !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
  158. # define CATCH_CONFIG_POSIX_SIGNALS
  159. #endif
  160. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  161. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  162. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  163. #endif
  164. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  165. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  166. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  167. #endif
  168. // end catch_compiler_capabilities.h
  169. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  170. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  171. #ifdef CATCH_CONFIG_COUNTER
  172. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  173. #else
  174. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  175. #endif
  176. #include <iosfwd>
  177. #include <string>
  178. #include <cstdint>
  179. namespace Catch {
  180. struct CaseSensitive { enum Choice {
  181. Yes,
  182. No
  183. }; };
  184. class NonCopyable {
  185. NonCopyable( NonCopyable const& ) = delete;
  186. NonCopyable( NonCopyable && ) = delete;
  187. NonCopyable& operator = ( NonCopyable const& ) = delete;
  188. NonCopyable& operator = ( NonCopyable && ) = delete;
  189. protected:
  190. NonCopyable();
  191. virtual ~NonCopyable();
  192. };
  193. struct SourceLineInfo {
  194. SourceLineInfo() = delete;
  195. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  196. : file( _file ),
  197. line( _line )
  198. {}
  199. SourceLineInfo( SourceLineInfo const& other ) = default;
  200. SourceLineInfo( SourceLineInfo && ) = default;
  201. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  202. SourceLineInfo& operator = ( SourceLineInfo && ) = default;
  203. bool empty() const noexcept;
  204. bool operator == ( SourceLineInfo const& other ) const noexcept;
  205. bool operator < ( SourceLineInfo const& other ) const noexcept;
  206. char const* file;
  207. std::size_t line;
  208. };
  209. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  210. // Use this in variadic streaming macros to allow
  211. // >> +StreamEndStop
  212. // as well as
  213. // >> stuff +StreamEndStop
  214. struct StreamEndStop {
  215. std::string operator+() const;
  216. };
  217. template<typename T>
  218. T const& operator + ( T const& value, StreamEndStop ) {
  219. return value;
  220. }
  221. }
  222. #define CATCH_INTERNAL_LINEINFO \
  223. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  224. // end catch_common.h
  225. namespace Catch {
  226. struct RegistrarForTagAliases {
  227. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  228. };
  229. } // end namespace Catch
  230. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  231. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  232. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  233. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  234. // end catch_tag_alias_autoregistrar.h
  235. // start catch_test_registry.h
  236. // start catch_interfaces_testcase.h
  237. #include <vector>
  238. #include <memory>
  239. namespace Catch {
  240. class TestSpec;
  241. struct ITestInvoker {
  242. virtual void invoke () const = 0;
  243. virtual ~ITestInvoker();
  244. };
  245. using ITestCasePtr = std::shared_ptr<ITestInvoker>;
  246. class TestCase;
  247. struct IConfig;
  248. struct ITestCaseRegistry {
  249. virtual ~ITestCaseRegistry();
  250. virtual std::vector<TestCase> const& getAllTests() const = 0;
  251. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  252. };
  253. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  254. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  255. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  256. }
  257. // end catch_interfaces_testcase.h
  258. // start catch_stringref.h
  259. #include <cstddef>
  260. #include <string>
  261. #include <iosfwd>
  262. namespace Catch {
  263. class StringData;
  264. /// A non-owning string class (similar to the forthcoming std::string_view)
  265. /// Note that, because a StringRef may be a substring of another string,
  266. /// it may not be null terminated. c_str() must return a null terminated
  267. /// string, however, and so the StringRef will internally take ownership
  268. /// (taking a copy), if necessary. In theory this ownership is not externally
  269. /// visible - but it does mean (substring) StringRefs should not be shared between
  270. /// threads.
  271. class StringRef {
  272. public:
  273. using size_type = std::size_t;
  274. private:
  275. friend struct StringRefTestAccess;
  276. char const* m_start;
  277. size_type m_size;
  278. char* m_data = nullptr;
  279. void takeOwnership();
  280. static constexpr char const* const s_empty = "";
  281. public: // construction/ assignment
  282. StringRef() noexcept
  283. : StringRef( s_empty, 0 )
  284. {}
  285. StringRef( StringRef const& other ) noexcept
  286. : m_start( other.m_start ),
  287. m_size( other.m_size )
  288. {}
  289. StringRef( StringRef&& other ) noexcept
  290. : m_start( other.m_start ),
  291. m_size( other.m_size ),
  292. m_data( other.m_data )
  293. {
  294. other.m_data = nullptr;
  295. }
  296. StringRef( char const* rawChars ) noexcept;
  297. StringRef( char const* rawChars, size_type size ) noexcept
  298. : m_start( rawChars ),
  299. m_size( size )
  300. {}
  301. StringRef( std::string const& stdString ) noexcept
  302. : m_start( stdString.c_str() ),
  303. m_size( stdString.size() )
  304. {}
  305. ~StringRef() noexcept {
  306. delete[] m_data;
  307. }
  308. auto operator = ( StringRef const &other ) noexcept -> StringRef& {
  309. delete[] m_data;
  310. m_data = nullptr;
  311. m_start = other.m_start;
  312. m_size = other.m_size;
  313. return *this;
  314. }
  315. operator std::string() const;
  316. void swap( StringRef& other ) noexcept;
  317. public: // operators
  318. auto operator == ( StringRef const& other ) const noexcept -> bool;
  319. auto operator != ( StringRef const& other ) const noexcept -> bool;
  320. auto operator[] ( size_type index ) const noexcept -> char;
  321. public: // named queries
  322. auto empty() const noexcept -> bool {
  323. return m_size == 0;
  324. }
  325. auto size() const noexcept -> size_type {
  326. return m_size;
  327. }
  328. auto numberOfCharacters() const noexcept -> size_type;
  329. auto c_str() const -> char const*;
  330. public: // substrings and searches
  331. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  332. private: // ownership queries - may not be consistent between calls
  333. auto isOwned() const noexcept -> bool;
  334. auto isSubstring() const noexcept -> bool;
  335. auto data() const noexcept -> char const*;
  336. };
  337. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  338. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  339. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  340. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  341. inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  342. return StringRef( rawChars, size );
  343. }
  344. } // namespace Catch
  345. // end catch_stringref.h
  346. namespace Catch {
  347. template<typename C>
  348. class TestInvokerAsMethod : public ITestInvoker {
  349. void (C::*m_testAsMethod)();
  350. public:
  351. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  352. void invoke() const override {
  353. C obj;
  354. (obj.*m_testAsMethod)();
  355. }
  356. };
  357. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  358. template<typename C>
  359. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  360. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  361. }
  362. struct NameAndTags {
  363. NameAndTags( StringRef name_ = StringRef(), StringRef tags_ = StringRef() ) noexcept;
  364. StringRef name;
  365. StringRef tags;
  366. };
  367. struct AutoReg : NonCopyable {
  368. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  369. ~AutoReg();
  370. };
  371. } // end namespace Catch
  372. #if defined(CATCH_CONFIG_DISABLE)
  373. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  374. static void TestName()
  375. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  376. namespace{ \
  377. struct TestName : ClassName { \
  378. void test(); \
  379. }; \
  380. } \
  381. void TestName::test()
  382. #endif
  383. ///////////////////////////////////////////////////////////////////////////////
  384. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  385. static void TestName(); \
  386. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  387. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  388. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  389. static void TestName()
  390. #define INTERNAL_CATCH_TESTCASE( ... ) \
  391. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  392. ///////////////////////////////////////////////////////////////////////////////
  393. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  394. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  395. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  396. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  397. ///////////////////////////////////////////////////////////////////////////////
  398. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  399. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  400. namespace{ \
  401. struct TestName : ClassName{ \
  402. void test(); \
  403. }; \
  404. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  405. } \
  406. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  407. void TestName::test()
  408. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  409. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  410. ///////////////////////////////////////////////////////////////////////////////
  411. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  412. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  413. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  414. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  415. // end catch_test_registry.h
  416. // start catch_capture.hpp
  417. // start catch_assertionhandler.h
  418. // start catch_assertioninfo.h
  419. // start catch_result_type.h
  420. namespace Catch {
  421. // ResultWas::OfType enum
  422. struct ResultWas { enum OfType {
  423. Unknown = -1,
  424. Ok = 0,
  425. Info = 1,
  426. Warning = 2,
  427. FailureBit = 0x10,
  428. ExpressionFailed = FailureBit | 1,
  429. ExplicitFailure = FailureBit | 2,
  430. Exception = 0x100 | FailureBit,
  431. ThrewException = Exception | 1,
  432. DidntThrowException = Exception | 2,
  433. FatalErrorCondition = 0x200 | FailureBit
  434. }; };
  435. bool isOk( ResultWas::OfType resultType );
  436. bool isJustInfo( int flags );
  437. // ResultDisposition::Flags enum
  438. struct ResultDisposition { enum Flags {
  439. Normal = 0x01,
  440. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  441. FalseTest = 0x04, // Prefix expression with !
  442. SuppressFail = 0x08 // Failures are reported but do not fail the test
  443. }; };
  444. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  445. bool shouldContinueOnFailure( int flags );
  446. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  447. bool shouldSuppressFailure( int flags );
  448. } // end namespace Catch
  449. // end catch_result_type.h
  450. namespace Catch {
  451. struct AssertionInfo
  452. {
  453. StringRef macroName;
  454. SourceLineInfo lineInfo;
  455. StringRef capturedExpression;
  456. ResultDisposition::Flags resultDisposition;
  457. // We want to delete this constructor but a compiler bug in 4.8 means
  458. // the struct is then treated as non-aggregate
  459. //AssertionInfo() = delete;
  460. };
  461. } // end namespace Catch
  462. // end catch_assertioninfo.h
  463. // start catch_decomposer.h
  464. // start catch_tostring.h
  465. #include <vector>
  466. #include <cstddef>
  467. #include <type_traits>
  468. #include <string>
  469. // start catch_stream.h
  470. #include <iosfwd>
  471. #include <cstddef>
  472. #include <ostream>
  473. namespace Catch {
  474. std::ostream& cout();
  475. std::ostream& cerr();
  476. std::ostream& clog();
  477. class StringRef;
  478. struct IStream {
  479. virtual ~IStream();
  480. virtual std::ostream& stream() const = 0;
  481. };
  482. auto makeStream( StringRef const &filename ) -> IStream const*;
  483. class ReusableStringStream {
  484. std::size_t m_index;
  485. std::ostream* m_oss;
  486. public:
  487. ReusableStringStream();
  488. ~ReusableStringStream();
  489. auto str() const -> std::string;
  490. template<typename T>
  491. auto operator << ( T const& value ) -> ReusableStringStream& {
  492. *m_oss << value;
  493. return *this;
  494. }
  495. auto get() -> std::ostream& { return *m_oss; }
  496. static void cleanup();
  497. };
  498. }
  499. // end catch_stream.h
  500. #ifdef __OBJC__
  501. // start catch_objc_arc.hpp
  502. #import <Foundation/Foundation.h>
  503. #ifdef __has_feature
  504. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  505. #else
  506. #define CATCH_ARC_ENABLED 0
  507. #endif
  508. void arcSafeRelease( NSObject* obj );
  509. id performOptionalSelector( id obj, SEL sel );
  510. #if !CATCH_ARC_ENABLED
  511. inline void arcSafeRelease( NSObject* obj ) {
  512. [obj release];
  513. }
  514. inline id performOptionalSelector( id obj, SEL sel ) {
  515. if( [obj respondsToSelector: sel] )
  516. return [obj performSelector: sel];
  517. return nil;
  518. }
  519. #define CATCH_UNSAFE_UNRETAINED
  520. #define CATCH_ARC_STRONG
  521. #else
  522. inline void arcSafeRelease( NSObject* ){}
  523. inline id performOptionalSelector( id obj, SEL sel ) {
  524. #ifdef __clang__
  525. #pragma clang diagnostic push
  526. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  527. #endif
  528. if( [obj respondsToSelector: sel] )
  529. return [obj performSelector: sel];
  530. #ifdef __clang__
  531. #pragma clang diagnostic pop
  532. #endif
  533. return nil;
  534. }
  535. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  536. #define CATCH_ARC_STRONG __strong
  537. #endif
  538. // end catch_objc_arc.hpp
  539. #endif
  540. #ifdef _MSC_VER
  541. #pragma warning(push)
  542. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  543. #endif
  544. // We need a dummy global operator<< so we can bring it into Catch namespace later
  545. struct Catch_global_namespace_dummy {};
  546. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  547. namespace Catch {
  548. // Bring in operator<< from global namespace into Catch namespace
  549. using ::operator<<;
  550. namespace Detail {
  551. extern const std::string unprintableString;
  552. std::string rawMemoryToString( const void *object, std::size_t size );
  553. template<typename T>
  554. std::string rawMemoryToString( const T& object ) {
  555. return rawMemoryToString( &object, sizeof(object) );
  556. }
  557. template<typename T>
  558. class IsStreamInsertable {
  559. template<typename SS, typename TT>
  560. static auto test(int)
  561. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  562. template<typename, typename>
  563. static auto test(...)->std::false_type;
  564. public:
  565. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  566. };
  567. template<typename E>
  568. std::string convertUnknownEnumToString( E e );
  569. template<typename T>
  570. typename std::enable_if<!std::is_enum<T>::value, std::string>::type convertUnstreamable( T const& ) {
  571. return Detail::unprintableString;
  572. };
  573. template<typename T>
  574. typename std::enable_if<std::is_enum<T>::value, std::string>::type convertUnstreamable( T const& value ) {
  575. return convertUnknownEnumToString( value );
  576. };
  577. } // namespace Detail
  578. // If we decide for C++14, change these to enable_if_ts
  579. template <typename T, typename = void>
  580. struct StringMaker {
  581. template <typename Fake = T>
  582. static
  583. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  584. convert(const Fake& value) {
  585. ReusableStringStream rss;
  586. rss << value;
  587. return rss.str();
  588. }
  589. template <typename Fake = T>
  590. static
  591. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  592. convert( const Fake& value ) {
  593. return Detail::convertUnstreamable( value );
  594. }
  595. };
  596. namespace Detail {
  597. // This function dispatches all stringification requests inside of Catch.
  598. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  599. template <typename T>
  600. std::string stringify(const T& e) {
  601. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  602. }
  603. template<typename E>
  604. std::string convertUnknownEnumToString( E e ) {
  605. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  606. }
  607. } // namespace Detail
  608. // Some predefined specializations
  609. template<>
  610. struct StringMaker<std::string> {
  611. static std::string convert(const std::string& str);
  612. };
  613. template<>
  614. struct StringMaker<std::wstring> {
  615. static std::string convert(const std::wstring& wstr);
  616. };
  617. template<>
  618. struct StringMaker<char const *> {
  619. static std::string convert(char const * str);
  620. };
  621. template<>
  622. struct StringMaker<char *> {
  623. static std::string convert(char * str);
  624. };
  625. template<>
  626. struct StringMaker<wchar_t const *> {
  627. static std::string convert(wchar_t const * str);
  628. };
  629. template<>
  630. struct StringMaker<wchar_t *> {
  631. static std::string convert(wchar_t * str);
  632. };
  633. template<typename T>
  634. struct is_string_array : std::false_type {};
  635. template<std::size_t N>
  636. struct is_string_array<char[N]> : std::true_type {};
  637. template<std::size_t N>
  638. struct is_string_array<signed char[N]> : std::true_type {};
  639. template<std::size_t N>
  640. struct is_string_array<unsigned char[N]> : std::true_type {};
  641. template<int SZ>
  642. struct StringMaker<char[SZ]> {
  643. static std::string convert(const char* str) {
  644. return ::Catch::Detail::stringify(std::string{ str });
  645. }
  646. };
  647. template<int SZ>
  648. struct StringMaker<signed char[SZ]> {
  649. static std::string convert(const char* str) {
  650. return ::Catch::Detail::stringify(std::string{ str });
  651. }
  652. };
  653. template<int SZ>
  654. struct StringMaker<unsigned char[SZ]> {
  655. static std::string convert(const char* str) {
  656. return ::Catch::Detail::stringify(std::string{ str });
  657. }
  658. };
  659. template<>
  660. struct StringMaker<int> {
  661. static std::string convert(int value);
  662. };
  663. template<>
  664. struct StringMaker<long> {
  665. static std::string convert(long value);
  666. };
  667. template<>
  668. struct StringMaker<long long> {
  669. static std::string convert(long long value);
  670. };
  671. template<>
  672. struct StringMaker<unsigned int> {
  673. static std::string convert(unsigned int value);
  674. };
  675. template<>
  676. struct StringMaker<unsigned long> {
  677. static std::string convert(unsigned long value);
  678. };
  679. template<>
  680. struct StringMaker<unsigned long long> {
  681. static std::string convert(unsigned long long value);
  682. };
  683. template<>
  684. struct StringMaker<bool> {
  685. static std::string convert(bool b);
  686. };
  687. template<>
  688. struct StringMaker<char> {
  689. static std::string convert(char c);
  690. };
  691. template<>
  692. struct StringMaker<signed char> {
  693. static std::string convert(signed char c);
  694. };
  695. template<>
  696. struct StringMaker<unsigned char> {
  697. static std::string convert(unsigned char c);
  698. };
  699. template<>
  700. struct StringMaker<std::nullptr_t> {
  701. static std::string convert(std::nullptr_t);
  702. };
  703. template<>
  704. struct StringMaker<float> {
  705. static std::string convert(float value);
  706. };
  707. template<>
  708. struct StringMaker<double> {
  709. static std::string convert(double value);
  710. };
  711. template <typename T>
  712. struct StringMaker<T*> {
  713. template <typename U>
  714. static std::string convert(U* p) {
  715. if (p) {
  716. return ::Catch::Detail::rawMemoryToString(p);
  717. } else {
  718. return "nullptr";
  719. }
  720. }
  721. };
  722. template <typename R, typename C>
  723. struct StringMaker<R C::*> {
  724. static std::string convert(R C::* p) {
  725. if (p) {
  726. return ::Catch::Detail::rawMemoryToString(p);
  727. } else {
  728. return "nullptr";
  729. }
  730. }
  731. };
  732. namespace Detail {
  733. template<typename InputIterator>
  734. std::string rangeToString(InputIterator first, InputIterator last) {
  735. ReusableStringStream rss;
  736. rss << "{ ";
  737. if (first != last) {
  738. rss << ::Catch::Detail::stringify(*first);
  739. for (++first; first != last; ++first)
  740. rss << ", " << ::Catch::Detail::stringify(*first);
  741. }
  742. rss << " }";
  743. return rss.str();
  744. }
  745. }
  746. #ifdef __OBJC__
  747. template<>
  748. struct StringMaker<NSString*> {
  749. static std::string convert(NSString * nsstring) {
  750. if (!nsstring)
  751. return "nil";
  752. return std::string("@") + [nsstring UTF8String];
  753. }
  754. };
  755. template<>
  756. struct StringMaker<NSObject*> {
  757. static std::string convert(NSObject* nsObject) {
  758. return ::Catch::Detail::stringify([nsObject description]);
  759. }
  760. };
  761. namespace Detail {
  762. inline std::string stringify( NSString* nsstring ) {
  763. return StringMaker<NSString*>::convert( nsstring );
  764. }
  765. } // namespace Detail
  766. #endif // __OBJC__
  767. } // namespace Catch
  768. //////////////////////////////////////////////////////
  769. // Separate std-lib types stringification, so it can be selectively enabled
  770. // This means that we do not bring in
  771. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  772. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  773. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  774. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  775. #endif
  776. // Separate std::pair specialization
  777. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  778. #include <utility>
  779. namespace Catch {
  780. template<typename T1, typename T2>
  781. struct StringMaker<std::pair<T1, T2> > {
  782. static std::string convert(const std::pair<T1, T2>& pair) {
  783. ReusableStringStream rss;
  784. rss << "{ "
  785. << ::Catch::Detail::stringify(pair.first)
  786. << ", "
  787. << ::Catch::Detail::stringify(pair.second)
  788. << " }";
  789. return rss.str();
  790. }
  791. };
  792. }
  793. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  794. // Separate std::tuple specialization
  795. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  796. #include <tuple>
  797. namespace Catch {
  798. namespace Detail {
  799. template<
  800. typename Tuple,
  801. std::size_t N = 0,
  802. bool = (N < std::tuple_size<Tuple>::value)
  803. >
  804. struct TupleElementPrinter {
  805. static void print(const Tuple& tuple, std::ostream& os) {
  806. os << (N ? ", " : " ")
  807. << ::Catch::Detail::stringify(std::get<N>(tuple));
  808. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  809. }
  810. };
  811. template<
  812. typename Tuple,
  813. std::size_t N
  814. >
  815. struct TupleElementPrinter<Tuple, N, false> {
  816. static void print(const Tuple&, std::ostream&) {}
  817. };
  818. }
  819. template<typename ...Types>
  820. struct StringMaker<std::tuple<Types...>> {
  821. static std::string convert(const std::tuple<Types...>& tuple) {
  822. ReusableStringStream rss;
  823. rss << '{';
  824. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  825. rss << " }";
  826. return rss.str();
  827. }
  828. };
  829. }
  830. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  831. namespace Catch {
  832. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  833. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  834. using std::begin;
  835. using std::end;
  836. not_this_one begin( ... );
  837. not_this_one end( ... );
  838. template <typename T>
  839. struct is_range {
  840. static const bool value =
  841. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  842. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  843. };
  844. template<typename Range>
  845. std::string rangeToString( Range const& range ) {
  846. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  847. }
  848. // Handle vector<bool> specially
  849. template<typename Allocator>
  850. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  851. ReusableStringStream rss;
  852. rss << "{ ";
  853. bool first = true;
  854. for( bool b : v ) {
  855. if( first )
  856. first = false;
  857. else
  858. rss << ", ";
  859. rss << ::Catch::Detail::stringify( b );
  860. }
  861. rss << " }";
  862. return rss.str();
  863. }
  864. template<typename R>
  865. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !is_string_array<R>::value>::type> {
  866. static std::string convert( R const& range ) {
  867. return rangeToString( range );
  868. }
  869. };
  870. } // namespace Catch
  871. // Separate std::chrono::duration specialization
  872. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  873. #include <ctime>
  874. #include <ratio>
  875. #include <chrono>
  876. namespace Catch {
  877. template <class Ratio>
  878. struct ratio_string {
  879. static std::string symbol();
  880. };
  881. template <class Ratio>
  882. std::string ratio_string<Ratio>::symbol() {
  883. Catch::ReusableStringStream rss;
  884. rss << '[' << Ratio::num << '/'
  885. << Ratio::den << ']';
  886. return rss.str();
  887. }
  888. template <>
  889. struct ratio_string<std::atto> {
  890. static std::string symbol();
  891. };
  892. template <>
  893. struct ratio_string<std::femto> {
  894. static std::string symbol();
  895. };
  896. template <>
  897. struct ratio_string<std::pico> {
  898. static std::string symbol();
  899. };
  900. template <>
  901. struct ratio_string<std::nano> {
  902. static std::string symbol();
  903. };
  904. template <>
  905. struct ratio_string<std::micro> {
  906. static std::string symbol();
  907. };
  908. template <>
  909. struct ratio_string<std::milli> {
  910. static std::string symbol();
  911. };
  912. ////////////
  913. // std::chrono::duration specializations
  914. template<typename Value, typename Ratio>
  915. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  916. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  917. ReusableStringStream rss;
  918. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  919. return rss.str();
  920. }
  921. };
  922. template<typename Value>
  923. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  924. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  925. ReusableStringStream rss;
  926. rss << duration.count() << " s";
  927. return rss.str();
  928. }
  929. };
  930. template<typename Value>
  931. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  932. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  933. ReusableStringStream rss;
  934. rss << duration.count() << " m";
  935. return rss.str();
  936. }
  937. };
  938. template<typename Value>
  939. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  940. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  941. ReusableStringStream rss;
  942. rss << duration.count() << " h";
  943. return rss.str();
  944. }
  945. };
  946. ////////////
  947. // std::chrono::time_point specialization
  948. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  949. template<typename Clock, typename Duration>
  950. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  951. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  952. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  953. }
  954. };
  955. // std::chrono::time_point<system_clock> specialization
  956. template<typename Duration>
  957. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  958. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  959. auto converted = std::chrono::system_clock::to_time_t(time_point);
  960. #ifdef _MSC_VER
  961. std::tm timeInfo = {};
  962. gmtime_s(&timeInfo, &converted);
  963. #else
  964. std::tm* timeInfo = std::gmtime(&converted);
  965. #endif
  966. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  967. char timeStamp[timeStampSize];
  968. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  969. #ifdef _MSC_VER
  970. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  971. #else
  972. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  973. #endif
  974. return std::string(timeStamp);
  975. }
  976. };
  977. }
  978. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  979. #ifdef _MSC_VER
  980. #pragma warning(pop)
  981. #endif
  982. // end catch_tostring.h
  983. #include <iosfwd>
  984. #ifdef _MSC_VER
  985. #pragma warning(push)
  986. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  987. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  988. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  989. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  990. #endif
  991. namespace Catch {
  992. struct ITransientExpression {
  993. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  994. auto getResult() const -> bool { return m_result; }
  995. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  996. ITransientExpression( bool isBinaryExpression, bool result )
  997. : m_isBinaryExpression( isBinaryExpression ),
  998. m_result( result )
  999. {}
  1000. // We don't actually need a virtual destructor, but many static analysers
  1001. // complain if it's not here :-(
  1002. virtual ~ITransientExpression();
  1003. bool m_isBinaryExpression;
  1004. bool m_result;
  1005. };
  1006. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1007. template<typename LhsT, typename RhsT>
  1008. class BinaryExpr : public ITransientExpression {
  1009. LhsT m_lhs;
  1010. StringRef m_op;
  1011. RhsT m_rhs;
  1012. void streamReconstructedExpression( std::ostream &os ) const override {
  1013. formatReconstructedExpression
  1014. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1015. }
  1016. public:
  1017. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1018. : ITransientExpression{ true, comparisonResult },
  1019. m_lhs( lhs ),
  1020. m_op( op ),
  1021. m_rhs( rhs )
  1022. {}
  1023. };
  1024. template<typename LhsT>
  1025. class UnaryExpr : public ITransientExpression {
  1026. LhsT m_lhs;
  1027. void streamReconstructedExpression( std::ostream &os ) const override {
  1028. os << Catch::Detail::stringify( m_lhs );
  1029. }
  1030. public:
  1031. explicit UnaryExpr( LhsT lhs )
  1032. : ITransientExpression{ false, lhs ? true : false },
  1033. m_lhs( lhs )
  1034. {}
  1035. };
  1036. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1037. template<typename LhsT, typename RhsT>
  1038. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return lhs == rhs; };
  1039. template<typename T>
  1040. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1041. template<typename T>
  1042. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1043. template<typename T>
  1044. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1045. template<typename T>
  1046. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1047. template<typename LhsT, typename RhsT>
  1048. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return lhs != rhs; };
  1049. template<typename T>
  1050. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1051. template<typename T>
  1052. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1053. template<typename T>
  1054. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1055. template<typename T>
  1056. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1057. template<typename LhsT>
  1058. class ExprLhs {
  1059. LhsT m_lhs;
  1060. public:
  1061. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1062. template<typename RhsT>
  1063. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1064. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1065. }
  1066. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1067. return { m_lhs == rhs, m_lhs, "==", rhs };
  1068. }
  1069. template<typename RhsT>
  1070. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1071. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1072. }
  1073. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1074. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1075. }
  1076. template<typename RhsT>
  1077. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1078. return { m_lhs > rhs, m_lhs, ">", rhs };
  1079. }
  1080. template<typename RhsT>
  1081. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1082. return { m_lhs < rhs, m_lhs, "<", rhs };
  1083. }
  1084. template<typename RhsT>
  1085. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1086. return { m_lhs >= rhs, m_lhs, ">=", rhs };
  1087. }
  1088. template<typename RhsT>
  1089. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1090. return { m_lhs <= rhs, m_lhs, "<=", rhs };
  1091. }
  1092. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  1093. return UnaryExpr<LhsT>{ m_lhs };
  1094. }
  1095. };
  1096. void handleExpression( ITransientExpression const& expr );
  1097. template<typename T>
  1098. void handleExpression( ExprLhs<T> const& expr ) {
  1099. handleExpression( expr.makeUnaryExpr() );
  1100. }
  1101. struct Decomposer {
  1102. template<typename T>
  1103. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  1104. return ExprLhs<T const&>{ lhs };
  1105. }
  1106. auto operator <=( bool value ) -> ExprLhs<bool> {
  1107. return ExprLhs<bool>{ value };
  1108. }
  1109. };
  1110. } // end namespace Catch
  1111. #ifdef _MSC_VER
  1112. #pragma warning(pop)
  1113. #endif
  1114. // end catch_decomposer.h
  1115. // start catch_interfaces_capture.h
  1116. #include <string>
  1117. namespace Catch {
  1118. class AssertionResult;
  1119. struct AssertionInfo;
  1120. struct SectionInfo;
  1121. struct SectionEndInfo;
  1122. struct MessageInfo;
  1123. struct Counts;
  1124. struct BenchmarkInfo;
  1125. struct BenchmarkStats;
  1126. struct AssertionReaction;
  1127. struct ITransientExpression;
  1128. struct IResultCapture {
  1129. virtual ~IResultCapture();
  1130. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  1131. Counts& assertions ) = 0;
  1132. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  1133. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  1134. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  1135. virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;
  1136. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  1137. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  1138. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  1139. virtual void handleExpr
  1140. ( AssertionInfo const& info,
  1141. ITransientExpression const& expr,
  1142. AssertionReaction& reaction ) = 0;
  1143. virtual void handleMessage
  1144. ( AssertionInfo const& info,
  1145. ResultWas::OfType resultType,
  1146. StringRef const& message,
  1147. AssertionReaction& reaction ) = 0;
  1148. virtual void handleUnexpectedExceptionNotThrown
  1149. ( AssertionInfo const& info,
  1150. AssertionReaction& reaction ) = 0;
  1151. virtual void handleUnexpectedInflightException
  1152. ( AssertionInfo const& info,
  1153. std::string const& message,
  1154. AssertionReaction& reaction ) = 0;
  1155. virtual void handleIncomplete
  1156. ( AssertionInfo const& info ) = 0;
  1157. virtual void handleNonExpr
  1158. ( AssertionInfo const &info,
  1159. ResultWas::OfType resultType,
  1160. AssertionReaction &reaction ) = 0;
  1161. virtual bool lastAssertionPassed() = 0;
  1162. virtual void assertionPassed() = 0;
  1163. // Deprecated, do not use:
  1164. virtual std::string getCurrentTestName() const = 0;
  1165. virtual const AssertionResult* getLastResult() const = 0;
  1166. virtual void exceptionEarlyReported() = 0;
  1167. };
  1168. IResultCapture& getResultCapture();
  1169. }
  1170. // end catch_interfaces_capture.h
  1171. namespace Catch {
  1172. struct TestFailureException{};
  1173. struct AssertionResultData;
  1174. struct IResultCapture;
  1175. class RunContext;
  1176. class LazyExpression {
  1177. friend class AssertionHandler;
  1178. friend struct AssertionStats;
  1179. friend class RunContext;
  1180. ITransientExpression const* m_transientExpression = nullptr;
  1181. bool m_isNegated;
  1182. public:
  1183. LazyExpression( bool isNegated );
  1184. LazyExpression( LazyExpression const& other );
  1185. LazyExpression& operator = ( LazyExpression const& ) = delete;
  1186. explicit operator bool() const;
  1187. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  1188. };
  1189. struct AssertionReaction {
  1190. bool shouldDebugBreak = false;
  1191. bool shouldThrow = false;
  1192. };
  1193. class AssertionHandler {
  1194. AssertionInfo m_assertionInfo;
  1195. AssertionReaction m_reaction;
  1196. bool m_completed = false;
  1197. IResultCapture& m_resultCapture;
  1198. public:
  1199. AssertionHandler
  1200. ( StringRef macroName,
  1201. SourceLineInfo const& lineInfo,
  1202. StringRef capturedExpression,
  1203. ResultDisposition::Flags resultDisposition );
  1204. ~AssertionHandler() {
  1205. if ( !m_completed ) {
  1206. m_resultCapture.handleIncomplete( m_assertionInfo );
  1207. }
  1208. }
  1209. template<typename T>
  1210. void handleExpr( ExprLhs<T> const& expr ) {
  1211. handleExpr( expr.makeUnaryExpr() );
  1212. }
  1213. void handleExpr( ITransientExpression const& expr );
  1214. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  1215. void handleExceptionThrownAsExpected();
  1216. void handleUnexpectedExceptionNotThrown();
  1217. void handleExceptionNotThrownAsExpected();
  1218. void handleThrowingCallSkipped();
  1219. void handleUnexpectedInflightException();
  1220. void complete();
  1221. void setCompleted();
  1222. // query
  1223. auto allowThrows() const -> bool;
  1224. };
  1225. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString );
  1226. } // namespace Catch
  1227. // end catch_assertionhandler.h
  1228. // start catch_message.h
  1229. #include <string>
  1230. namespace Catch {
  1231. struct MessageInfo {
  1232. MessageInfo( std::string const& _macroName,
  1233. SourceLineInfo const& _lineInfo,
  1234. ResultWas::OfType _type );
  1235. std::string macroName;
  1236. std::string message;
  1237. SourceLineInfo lineInfo;
  1238. ResultWas::OfType type;
  1239. unsigned int sequence;
  1240. bool operator == ( MessageInfo const& other ) const;
  1241. bool operator < ( MessageInfo const& other ) const;
  1242. private:
  1243. static unsigned int globalCount;
  1244. };
  1245. struct MessageStream {
  1246. template<typename T>
  1247. MessageStream& operator << ( T const& value ) {
  1248. m_stream << value;
  1249. return *this;
  1250. }
  1251. ReusableStringStream m_stream;
  1252. };
  1253. struct MessageBuilder : MessageStream {
  1254. MessageBuilder( std::string const& macroName,
  1255. SourceLineInfo const& lineInfo,
  1256. ResultWas::OfType type );
  1257. template<typename T>
  1258. MessageBuilder& operator << ( T const& value ) {
  1259. m_stream << value;
  1260. return *this;
  1261. }
  1262. MessageInfo m_info;
  1263. };
  1264. class ScopedMessage {
  1265. public:
  1266. explicit ScopedMessage( MessageBuilder const& builder );
  1267. ~ScopedMessage();
  1268. MessageInfo m_info;
  1269. };
  1270. } // end namespace Catch
  1271. // end catch_message.h
  1272. #if !defined(CATCH_CONFIG_DISABLE)
  1273. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  1274. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  1275. #else
  1276. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  1277. #endif
  1278. #if defined(CATCH_CONFIG_FAST_COMPILE)
  1279. ///////////////////////////////////////////////////////////////////////////////
  1280. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  1281. // macros.
  1282. #define INTERNAL_CATCH_TRY
  1283. #define INTERNAL_CATCH_CATCH( capturer )
  1284. #else // CATCH_CONFIG_FAST_COMPILE
  1285. #define INTERNAL_CATCH_TRY try
  1286. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  1287. #endif
  1288. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  1289. ///////////////////////////////////////////////////////////////////////////////
  1290. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  1291. do { \
  1292. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1293. INTERNAL_CATCH_TRY { \
  1294. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  1295. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  1296. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  1297. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1298. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1299. } while( (void)0, false && static_cast<bool>( !!(__VA_ARGS__) ) ) // the expression here is never evaluated at runtime but it forces the compiler to give it a look
  1300. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  1301. ///////////////////////////////////////////////////////////////////////////////
  1302. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  1303. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1304. if( Catch::getResultCapture().lastAssertionPassed() )
  1305. ///////////////////////////////////////////////////////////////////////////////
  1306. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  1307. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1308. if( !Catch::getResultCapture().lastAssertionPassed() )
  1309. ///////////////////////////////////////////////////////////////////////////////
  1310. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  1311. do { \
  1312. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1313. try { \
  1314. static_cast<void>(__VA_ARGS__); \
  1315. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  1316. } \
  1317. catch( ... ) { \
  1318. catchAssertionHandler.handleUnexpectedInflightException(); \
  1319. } \
  1320. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1321. } while( false )
  1322. ///////////////////////////////////////////////////////////////////////////////
  1323. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  1324. do { \
  1325. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  1326. if( catchAssertionHandler.allowThrows() ) \
  1327. try { \
  1328. static_cast<void>(__VA_ARGS__); \
  1329. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1330. } \
  1331. catch( ... ) { \
  1332. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1333. } \
  1334. else \
  1335. catchAssertionHandler.handleThrowingCallSkipped(); \
  1336. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1337. } while( false )
  1338. ///////////////////////////////////////////////////////////////////////////////
  1339. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  1340. do { \
  1341. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  1342. if( catchAssertionHandler.allowThrows() ) \
  1343. try { \
  1344. static_cast<void>(expr); \
  1345. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1346. } \
  1347. catch( exceptionType const& ) { \
  1348. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1349. } \
  1350. catch( ... ) { \
  1351. catchAssertionHandler.handleUnexpectedInflightException(); \
  1352. } \
  1353. else \
  1354. catchAssertionHandler.handleThrowingCallSkipped(); \
  1355. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1356. } while( false )
  1357. ///////////////////////////////////////////////////////////////////////////////
  1358. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  1359. do { \
  1360. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
  1361. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  1362. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1363. } while( false )
  1364. ///////////////////////////////////////////////////////////////////////////////
  1365. #define INTERNAL_CATCH_INFO( macroName, log ) \
  1366. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  1367. ///////////////////////////////////////////////////////////////////////////////
  1368. // Although this is matcher-based, it can be used with just a string
  1369. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  1370. do { \
  1371. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1372. if( catchAssertionHandler.allowThrows() ) \
  1373. try { \
  1374. static_cast<void>(__VA_ARGS__); \
  1375. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1376. } \
  1377. catch( ... ) { \
  1378. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher ); \
  1379. } \
  1380. else \
  1381. catchAssertionHandler.handleThrowingCallSkipped(); \
  1382. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1383. } while( false )
  1384. #endif // CATCH_CONFIG_DISABLE
  1385. // end catch_capture.hpp
  1386. // start catch_section.h
  1387. // start catch_section_info.h
  1388. // start catch_totals.h
  1389. #include <cstddef>
  1390. namespace Catch {
  1391. struct Counts {
  1392. Counts operator - ( Counts const& other ) const;
  1393. Counts& operator += ( Counts const& other );
  1394. std::size_t total() const;
  1395. bool allPassed() const;
  1396. bool allOk() const;
  1397. std::size_t passed = 0;
  1398. std::size_t failed = 0;
  1399. std::size_t failedButOk = 0;
  1400. };
  1401. struct Totals {
  1402. Totals operator - ( Totals const& other ) const;
  1403. Totals& operator += ( Totals const& other );
  1404. Totals delta( Totals const& prevTotals ) const;
  1405. Counts assertions;
  1406. Counts testCases;
  1407. };
  1408. }
  1409. // end catch_totals.h
  1410. #include <string>
  1411. namespace Catch {
  1412. struct SectionInfo {
  1413. SectionInfo
  1414. ( SourceLineInfo const& _lineInfo,
  1415. std::string const& _name,
  1416. std::string const& _description = std::string() );
  1417. std::string name;
  1418. std::string description;
  1419. SourceLineInfo lineInfo;
  1420. };
  1421. struct SectionEndInfo {
  1422. SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds );
  1423. SectionInfo sectionInfo;
  1424. Counts prevAssertions;
  1425. double durationInSeconds;
  1426. };
  1427. } // end namespace Catch
  1428. // end catch_section_info.h
  1429. // start catch_timer.h
  1430. #include <cstdint>
  1431. namespace Catch {
  1432. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  1433. auto getEstimatedClockResolution() -> uint64_t;
  1434. class Timer {
  1435. uint64_t m_nanoseconds = 0;
  1436. public:
  1437. void start();
  1438. auto getElapsedNanoseconds() const -> uint64_t;
  1439. auto getElapsedMicroseconds() const -> uint64_t;
  1440. auto getElapsedMilliseconds() const -> unsigned int;
  1441. auto getElapsedSeconds() const -> double;
  1442. };
  1443. } // namespace Catch
  1444. // end catch_timer.h
  1445. #include <string>
  1446. namespace Catch {
  1447. class Section : NonCopyable {
  1448. public:
  1449. Section( SectionInfo const& info );
  1450. ~Section();
  1451. // This indicates whether the section should be executed or not
  1452. explicit operator bool() const;
  1453. private:
  1454. SectionInfo m_info;
  1455. std::string m_name;
  1456. Counts m_assertions;
  1457. bool m_sectionIncluded;
  1458. Timer m_timer;
  1459. };
  1460. } // end namespace Catch
  1461. #define INTERNAL_CATCH_SECTION( ... ) \
  1462. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) )
  1463. // end catch_section.h
  1464. // start catch_benchmark.h
  1465. #include <cstdint>
  1466. #include <string>
  1467. namespace Catch {
  1468. class BenchmarkLooper {
  1469. std::string m_name;
  1470. std::size_t m_count = 0;
  1471. std::size_t m_iterationsToRun = 1;
  1472. uint64_t m_resolution;
  1473. Timer m_timer;
  1474. static auto getResolution() -> uint64_t;
  1475. public:
  1476. // Keep most of this inline as it's on the code path that is being timed
  1477. BenchmarkLooper( StringRef name )
  1478. : m_name( name ),
  1479. m_resolution( getResolution() )
  1480. {
  1481. reportStart();
  1482. m_timer.start();
  1483. }
  1484. explicit operator bool() {
  1485. if( m_count < m_iterationsToRun )
  1486. return true;
  1487. return needsMoreIterations();
  1488. }
  1489. void increment() {
  1490. ++m_count;
  1491. }
  1492. void reportStart();
  1493. auto needsMoreIterations() -> bool;
  1494. };
  1495. } // end namespace Catch
  1496. #define BENCHMARK( name ) \
  1497. for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )
  1498. // end catch_benchmark.h
  1499. // start catch_interfaces_exception.h
  1500. // start catch_interfaces_registry_hub.h
  1501. #include <string>
  1502. #include <memory>
  1503. namespace Catch {
  1504. class TestCase;
  1505. struct ITestCaseRegistry;
  1506. struct IExceptionTranslatorRegistry;
  1507. struct IExceptionTranslator;
  1508. struct IReporterRegistry;
  1509. struct IReporterFactory;
  1510. struct ITagAliasRegistry;
  1511. class StartupExceptionRegistry;
  1512. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  1513. struct IRegistryHub {
  1514. virtual ~IRegistryHub();
  1515. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  1516. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  1517. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  1518. virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0;
  1519. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  1520. };
  1521. struct IMutableRegistryHub {
  1522. virtual ~IMutableRegistryHub();
  1523. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  1524. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  1525. virtual void registerTest( TestCase const& testInfo ) = 0;
  1526. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  1527. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  1528. virtual void registerStartupException() noexcept = 0;
  1529. };
  1530. IRegistryHub& getRegistryHub();
  1531. IMutableRegistryHub& getMutableRegistryHub();
  1532. void cleanUp();
  1533. std::string translateActiveException();
  1534. }
  1535. // end catch_interfaces_registry_hub.h
  1536. #if defined(CATCH_CONFIG_DISABLE)
  1537. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  1538. static std::string translatorName( signature )
  1539. #endif
  1540. #include <exception>
  1541. #include <string>
  1542. #include <vector>
  1543. namespace Catch {
  1544. using exceptionTranslateFunction = std::string(*)();
  1545. struct IExceptionTranslator;
  1546. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  1547. struct IExceptionTranslator {
  1548. virtual ~IExceptionTranslator();
  1549. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  1550. };
  1551. struct IExceptionTranslatorRegistry {
  1552. virtual ~IExceptionTranslatorRegistry();
  1553. virtual std::string translateActiveException() const = 0;
  1554. };
  1555. class ExceptionTranslatorRegistrar {
  1556. template<typename T>
  1557. class ExceptionTranslator : public IExceptionTranslator {
  1558. public:
  1559. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  1560. : m_translateFunction( translateFunction )
  1561. {}
  1562. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  1563. try {
  1564. if( it == itEnd )
  1565. std::rethrow_exception(std::current_exception());
  1566. else
  1567. return (*it)->translate( it+1, itEnd );
  1568. }
  1569. catch( T& ex ) {
  1570. return m_translateFunction( ex );
  1571. }
  1572. }
  1573. protected:
  1574. std::string(*m_translateFunction)( T& );
  1575. };
  1576. public:
  1577. template<typename T>
  1578. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  1579. getMutableRegistryHub().registerTranslator
  1580. ( new ExceptionTranslator<T>( translateFunction ) );
  1581. }
  1582. };
  1583. }
  1584. ///////////////////////////////////////////////////////////////////////////////
  1585. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  1586. static std::string translatorName( signature ); \
  1587. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1588. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  1589. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1590. static std::string translatorName( signature )
  1591. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  1592. // end catch_interfaces_exception.h
  1593. // start catch_approx.h
  1594. #include <type_traits>
  1595. #include <stdexcept>
  1596. namespace Catch {
  1597. namespace Detail {
  1598. class Approx {
  1599. private:
  1600. bool equalityComparisonImpl(double other) const;
  1601. public:
  1602. explicit Approx ( double value );
  1603. static Approx custom();
  1604. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1605. Approx operator()( T const& value ) {
  1606. Approx approx( static_cast<double>(value) );
  1607. approx.epsilon( m_epsilon );
  1608. approx.margin( m_margin );
  1609. approx.scale( m_scale );
  1610. return approx;
  1611. }
  1612. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1613. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  1614. {}
  1615. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1616. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  1617. auto lhs_v = static_cast<double>(lhs);
  1618. return rhs.equalityComparisonImpl(lhs_v);
  1619. }
  1620. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1621. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  1622. return operator==( rhs, lhs );
  1623. }
  1624. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1625. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  1626. return !operator==( lhs, rhs );
  1627. }
  1628. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1629. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  1630. return !operator==( rhs, lhs );
  1631. }
  1632. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1633. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  1634. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  1635. }
  1636. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1637. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  1638. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  1639. }
  1640. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1641. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  1642. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  1643. }
  1644. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1645. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  1646. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  1647. }
  1648. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1649. Approx& epsilon( T const& newEpsilon ) {
  1650. double epsilonAsDouble = static_cast<double>(newEpsilon);
  1651. if( epsilonAsDouble < 0 || epsilonAsDouble > 1.0 ) {
  1652. throw std::domain_error
  1653. ( "Invalid Approx::epsilon: " +
  1654. Catch::Detail::stringify( epsilonAsDouble ) +
  1655. ", Approx::epsilon has to be between 0 and 1" );
  1656. }
  1657. m_epsilon = epsilonAsDouble;
  1658. return *this;
  1659. }
  1660. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1661. Approx& margin( T const& newMargin ) {
  1662. double marginAsDouble = static_cast<double>(newMargin);
  1663. if( marginAsDouble < 0 ) {
  1664. throw std::domain_error
  1665. ( "Invalid Approx::margin: " +
  1666. Catch::Detail::stringify( marginAsDouble ) +
  1667. ", Approx::Margin has to be non-negative." );
  1668. }
  1669. m_margin = marginAsDouble;
  1670. return *this;
  1671. }
  1672. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1673. Approx& scale( T const& newScale ) {
  1674. m_scale = static_cast<double>(newScale);
  1675. return *this;
  1676. }
  1677. std::string toString() const;
  1678. private:
  1679. double m_epsilon;
  1680. double m_margin;
  1681. double m_scale;
  1682. double m_value;
  1683. };
  1684. }
  1685. template<>
  1686. struct StringMaker<Catch::Detail::Approx> {
  1687. static std::string convert(Catch::Detail::Approx const& value);
  1688. };
  1689. } // end namespace Catch
  1690. // end catch_approx.h
  1691. // start catch_string_manip.h
  1692. #include <string>
  1693. #include <iosfwd>
  1694. namespace Catch {
  1695. bool startsWith( std::string const& s, std::string const& prefix );
  1696. bool startsWith( std::string const& s, char prefix );
  1697. bool endsWith( std::string const& s, std::string const& suffix );
  1698. bool endsWith( std::string const& s, char suffix );
  1699. bool contains( std::string const& s, std::string const& infix );
  1700. void toLowerInPlace( std::string& s );
  1701. std::string toLower( std::string const& s );
  1702. std::string trim( std::string const& str );
  1703. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  1704. struct pluralise {
  1705. pluralise( std::size_t count, std::string const& label );
  1706. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  1707. std::size_t m_count;
  1708. std::string m_label;
  1709. };
  1710. }
  1711. // end catch_string_manip.h
  1712. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  1713. // start catch_capture_matchers.h
  1714. // start catch_matchers.h
  1715. #include <string>
  1716. #include <vector>
  1717. namespace Catch {
  1718. namespace Matchers {
  1719. namespace Impl {
  1720. template<typename ArgT> struct MatchAllOf;
  1721. template<typename ArgT> struct MatchAnyOf;
  1722. template<typename ArgT> struct MatchNotOf;
  1723. class MatcherUntypedBase {
  1724. public:
  1725. MatcherUntypedBase() = default;
  1726. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  1727. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  1728. std::string toString() const;
  1729. protected:
  1730. virtual ~MatcherUntypedBase();
  1731. virtual std::string describe() const = 0;
  1732. mutable std::string m_cachedToString;
  1733. };
  1734. template<typename ObjectT>
  1735. struct MatcherMethod {
  1736. virtual bool match( ObjectT const& arg ) const = 0;
  1737. };
  1738. template<typename PtrT>
  1739. struct MatcherMethod<PtrT*> {
  1740. virtual bool match( PtrT* arg ) const = 0;
  1741. };
  1742. template<typename T>
  1743. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  1744. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  1745. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  1746. MatchNotOf<T> operator ! () const;
  1747. };
  1748. template<typename ArgT>
  1749. struct MatchAllOf : MatcherBase<ArgT> {
  1750. bool match( ArgT const& arg ) const override {
  1751. for( auto matcher : m_matchers ) {
  1752. if (!matcher->match(arg))
  1753. return false;
  1754. }
  1755. return true;
  1756. }
  1757. std::string describe() const override {
  1758. std::string description;
  1759. description.reserve( 4 + m_matchers.size()*32 );
  1760. description += "( ";
  1761. bool first = true;
  1762. for( auto matcher : m_matchers ) {
  1763. if( first )
  1764. first = false;
  1765. else
  1766. description += " and ";
  1767. description += matcher->toString();
  1768. }
  1769. description += " )";
  1770. return description;
  1771. }
  1772. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  1773. m_matchers.push_back( &other );
  1774. return *this;
  1775. }
  1776. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1777. };
  1778. template<typename ArgT>
  1779. struct MatchAnyOf : MatcherBase<ArgT> {
  1780. bool match( ArgT const& arg ) const override {
  1781. for( auto matcher : m_matchers ) {
  1782. if (matcher->match(arg))
  1783. return true;
  1784. }
  1785. return false;
  1786. }
  1787. std::string describe() const override {
  1788. std::string description;
  1789. description.reserve( 4 + m_matchers.size()*32 );
  1790. description += "( ";
  1791. bool first = true;
  1792. for( auto matcher : m_matchers ) {
  1793. if( first )
  1794. first = false;
  1795. else
  1796. description += " or ";
  1797. description += matcher->toString();
  1798. }
  1799. description += " )";
  1800. return description;
  1801. }
  1802. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  1803. m_matchers.push_back( &other );
  1804. return *this;
  1805. }
  1806. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1807. };
  1808. template<typename ArgT>
  1809. struct MatchNotOf : MatcherBase<ArgT> {
  1810. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  1811. bool match( ArgT const& arg ) const override {
  1812. return !m_underlyingMatcher.match( arg );
  1813. }
  1814. std::string describe() const override {
  1815. return "not " + m_underlyingMatcher.toString();
  1816. }
  1817. MatcherBase<ArgT> const& m_underlyingMatcher;
  1818. };
  1819. template<typename T>
  1820. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  1821. return MatchAllOf<T>() && *this && other;
  1822. }
  1823. template<typename T>
  1824. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  1825. return MatchAnyOf<T>() || *this || other;
  1826. }
  1827. template<typename T>
  1828. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  1829. return MatchNotOf<T>( *this );
  1830. }
  1831. } // namespace Impl
  1832. } // namespace Matchers
  1833. using namespace Matchers;
  1834. using Matchers::Impl::MatcherBase;
  1835. } // namespace Catch
  1836. // end catch_matchers.h
  1837. // start catch_matchers_floating.h
  1838. #include <type_traits>
  1839. #include <cmath>
  1840. namespace Catch {
  1841. namespace Matchers {
  1842. namespace Floating {
  1843. enum class FloatingPointKind : uint8_t;
  1844. struct WithinAbsMatcher : MatcherBase<double> {
  1845. WithinAbsMatcher(double target, double margin);
  1846. bool match(double const& matchee) const override;
  1847. std::string describe() const override;
  1848. private:
  1849. double m_target;
  1850. double m_margin;
  1851. };
  1852. struct WithinUlpsMatcher : MatcherBase<double> {
  1853. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  1854. bool match(double const& matchee) const override;
  1855. std::string describe() const override;
  1856. private:
  1857. double m_target;
  1858. int m_ulps;
  1859. FloatingPointKind m_type;
  1860. };
  1861. } // namespace Floating
  1862. // The following functions create the actual matcher objects.
  1863. // This allows the types to be inferred
  1864. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  1865. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  1866. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  1867. } // namespace Matchers
  1868. } // namespace Catch
  1869. // end catch_matchers_floating.h
  1870. // start catch_matchers_string.h
  1871. #include <string>
  1872. namespace Catch {
  1873. namespace Matchers {
  1874. namespace StdString {
  1875. struct CasedString
  1876. {
  1877. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  1878. std::string adjustString( std::string const& str ) const;
  1879. std::string caseSensitivitySuffix() const;
  1880. CaseSensitive::Choice m_caseSensitivity;
  1881. std::string m_str;
  1882. };
  1883. struct StringMatcherBase : MatcherBase<std::string> {
  1884. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  1885. std::string describe() const override;
  1886. CasedString m_comparator;
  1887. std::string m_operation;
  1888. };
  1889. struct EqualsMatcher : StringMatcherBase {
  1890. EqualsMatcher( CasedString const& comparator );
  1891. bool match( std::string const& source ) const override;
  1892. };
  1893. struct ContainsMatcher : StringMatcherBase {
  1894. ContainsMatcher( CasedString const& comparator );
  1895. bool match( std::string const& source ) const override;
  1896. };
  1897. struct StartsWithMatcher : StringMatcherBase {
  1898. StartsWithMatcher( CasedString const& comparator );
  1899. bool match( std::string const& source ) const override;
  1900. };
  1901. struct EndsWithMatcher : StringMatcherBase {
  1902. EndsWithMatcher( CasedString const& comparator );
  1903. bool match( std::string const& source ) const override;
  1904. };
  1905. struct RegexMatcher : MatcherBase<std::string> {
  1906. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  1907. bool match( std::string const& matchee ) const override;
  1908. std::string describe() const override;
  1909. private:
  1910. std::string m_regex;
  1911. CaseSensitive::Choice m_caseSensitivity;
  1912. };
  1913. } // namespace StdString
  1914. // The following functions create the actual matcher objects.
  1915. // This allows the types to be inferred
  1916. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1917. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1918. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1919. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1920. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1921. } // namespace Matchers
  1922. } // namespace Catch
  1923. // end catch_matchers_string.h
  1924. // start catch_matchers_vector.h
  1925. #include <algorithm>
  1926. namespace Catch {
  1927. namespace Matchers {
  1928. namespace Vector {
  1929. namespace Detail {
  1930. template <typename InputIterator, typename T>
  1931. size_t count(InputIterator first, InputIterator last, T const& item) {
  1932. size_t cnt = 0;
  1933. for (; first != last; ++first) {
  1934. if (*first == item) {
  1935. ++cnt;
  1936. }
  1937. }
  1938. return cnt;
  1939. }
  1940. template <typename InputIterator, typename T>
  1941. bool contains(InputIterator first, InputIterator last, T const& item) {
  1942. for (; first != last; ++first) {
  1943. if (*first == item) {
  1944. return true;
  1945. }
  1946. }
  1947. return false;
  1948. }
  1949. }
  1950. template<typename T>
  1951. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  1952. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  1953. bool match(std::vector<T> const &v) const override {
  1954. for (auto const& el : v) {
  1955. if (el == m_comparator) {
  1956. return true;
  1957. }
  1958. }
  1959. return false;
  1960. }
  1961. std::string describe() const override {
  1962. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  1963. }
  1964. T const& m_comparator;
  1965. };
  1966. template<typename T>
  1967. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  1968. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  1969. bool match(std::vector<T> const &v) const override {
  1970. // !TBD: see note in EqualsMatcher
  1971. if (m_comparator.size() > v.size())
  1972. return false;
  1973. for (auto const& comparator : m_comparator) {
  1974. auto present = false;
  1975. for (const auto& el : v) {
  1976. if (el == comparator) {
  1977. present = true;
  1978. break;
  1979. }
  1980. }
  1981. if (!present) {
  1982. return false;
  1983. }
  1984. }
  1985. return true;
  1986. }
  1987. std::string describe() const override {
  1988. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  1989. }
  1990. std::vector<T> const& m_comparator;
  1991. };
  1992. template<typename T>
  1993. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  1994. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  1995. bool match(std::vector<T> const &v) const override {
  1996. // !TBD: This currently works if all elements can be compared using !=
  1997. // - a more general approach would be via a compare template that defaults
  1998. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  1999. // - then just call that directly
  2000. if (m_comparator.size() != v.size())
  2001. return false;
  2002. for (std::size_t i = 0; i < v.size(); ++i)
  2003. if (m_comparator[i] != v[i])
  2004. return false;
  2005. return true;
  2006. }
  2007. std::string describe() const override {
  2008. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2009. }
  2010. std::vector<T> const& m_comparator;
  2011. };
  2012. template<typename T>
  2013. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2014. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2015. bool match(std::vector<T> const& vec) const override {
  2016. // Note: This is a reimplementation of std::is_permutation,
  2017. // because I don't want to include <algorithm> inside the common path
  2018. if (m_target.size() != vec.size()) {
  2019. return false;
  2020. }
  2021. auto lfirst = m_target.begin(), llast = m_target.end();
  2022. auto rfirst = vec.begin(), rlast = vec.end();
  2023. // Cut common prefix to optimize checking of permuted parts
  2024. while (lfirst != llast && *lfirst != *rfirst) {
  2025. ++lfirst; ++rfirst;
  2026. }
  2027. if (lfirst == llast) {
  2028. return true;
  2029. }
  2030. for (auto mid = lfirst; mid != llast; ++mid) {
  2031. // Skip already counted items
  2032. if (Detail::contains(lfirst, mid, *mid)) {
  2033. continue;
  2034. }
  2035. size_t num_vec = Detail::count(rfirst, rlast, *mid);
  2036. if (num_vec == 0 || Detail::count(lfirst, llast, *mid) != num_vec) {
  2037. return false;
  2038. }
  2039. }
  2040. return true;
  2041. }
  2042. std::string describe() const override {
  2043. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  2044. }
  2045. private:
  2046. std::vector<T> const& m_target;
  2047. };
  2048. } // namespace Vector
  2049. // The following functions create the actual matcher objects.
  2050. // This allows the types to be inferred
  2051. template<typename T>
  2052. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  2053. return Vector::ContainsMatcher<T>( comparator );
  2054. }
  2055. template<typename T>
  2056. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  2057. return Vector::ContainsElementMatcher<T>( comparator );
  2058. }
  2059. template<typename T>
  2060. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  2061. return Vector::EqualsMatcher<T>( comparator );
  2062. }
  2063. template<typename T>
  2064. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  2065. return Vector::UnorderedEqualsMatcher<T>(target);
  2066. }
  2067. } // namespace Matchers
  2068. } // namespace Catch
  2069. // end catch_matchers_vector.h
  2070. namespace Catch {
  2071. template<typename ArgT, typename MatcherT>
  2072. class MatchExpr : public ITransientExpression {
  2073. ArgT const& m_arg;
  2074. MatcherT m_matcher;
  2075. StringRef m_matcherString;
  2076. public:
  2077. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString )
  2078. : ITransientExpression{ true, matcher.match( arg ) },
  2079. m_arg( arg ),
  2080. m_matcher( matcher ),
  2081. m_matcherString( matcherString )
  2082. {}
  2083. void streamReconstructedExpression( std::ostream &os ) const override {
  2084. auto matcherAsString = m_matcher.toString();
  2085. os << Catch::Detail::stringify( m_arg ) << ' ';
  2086. if( matcherAsString == Detail::unprintableString )
  2087. os << m_matcherString;
  2088. else
  2089. os << matcherAsString;
  2090. }
  2091. };
  2092. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  2093. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString );
  2094. template<typename ArgT, typename MatcherT>
  2095. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString ) -> MatchExpr<ArgT, MatcherT> {
  2096. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  2097. }
  2098. } // namespace Catch
  2099. ///////////////////////////////////////////////////////////////////////////////
  2100. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  2101. do { \
  2102. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2103. INTERNAL_CATCH_TRY { \
  2104. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher ) ); \
  2105. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2106. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2107. } while( false )
  2108. ///////////////////////////////////////////////////////////////////////////////
  2109. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  2110. do { \
  2111. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2112. if( catchAssertionHandler.allowThrows() ) \
  2113. try { \
  2114. static_cast<void>(__VA_ARGS__ ); \
  2115. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2116. } \
  2117. catch( exceptionType const& ex ) { \
  2118. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher ) ); \
  2119. } \
  2120. catch( ... ) { \
  2121. catchAssertionHandler.handleUnexpectedInflightException(); \
  2122. } \
  2123. else \
  2124. catchAssertionHandler.handleThrowingCallSkipped(); \
  2125. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2126. } while( false )
  2127. // end catch_capture_matchers.h
  2128. #endif
  2129. // These files are included here so the single_include script doesn't put them
  2130. // in the conditionally compiled sections
  2131. // start catch_test_case_info.h
  2132. #include <string>
  2133. #include <vector>
  2134. #include <memory>
  2135. #ifdef __clang__
  2136. #pragma clang diagnostic push
  2137. #pragma clang diagnostic ignored "-Wpadded"
  2138. #endif
  2139. namespace Catch {
  2140. struct ITestInvoker;
  2141. struct TestCaseInfo {
  2142. enum SpecialProperties{
  2143. None = 0,
  2144. IsHidden = 1 << 1,
  2145. ShouldFail = 1 << 2,
  2146. MayFail = 1 << 3,
  2147. Throws = 1 << 4,
  2148. NonPortable = 1 << 5,
  2149. Benchmark = 1 << 6
  2150. };
  2151. TestCaseInfo( std::string const& _name,
  2152. std::string const& _className,
  2153. std::string const& _description,
  2154. std::vector<std::string> const& _tags,
  2155. SourceLineInfo const& _lineInfo );
  2156. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  2157. bool isHidden() const;
  2158. bool throws() const;
  2159. bool okToFail() const;
  2160. bool expectedToFail() const;
  2161. std::string tagsAsString() const;
  2162. std::string name;
  2163. std::string className;
  2164. std::string description;
  2165. std::vector<std::string> tags;
  2166. std::vector<std::string> lcaseTags;
  2167. SourceLineInfo lineInfo;
  2168. SpecialProperties properties;
  2169. };
  2170. class TestCase : public TestCaseInfo {
  2171. public:
  2172. TestCase( ITestInvoker* testCase, TestCaseInfo const& info );
  2173. TestCase withName( std::string const& _newName ) const;
  2174. void invoke() const;
  2175. TestCaseInfo const& getTestCaseInfo() const;
  2176. bool operator == ( TestCase const& other ) const;
  2177. bool operator < ( TestCase const& other ) const;
  2178. private:
  2179. std::shared_ptr<ITestInvoker> test;
  2180. };
  2181. TestCase makeTestCase( ITestInvoker* testCase,
  2182. std::string const& className,
  2183. std::string const& name,
  2184. std::string const& description,
  2185. SourceLineInfo const& lineInfo );
  2186. }
  2187. #ifdef __clang__
  2188. #pragma clang diagnostic pop
  2189. #endif
  2190. // end catch_test_case_info.h
  2191. // start catch_interfaces_runner.h
  2192. namespace Catch {
  2193. struct IRunner {
  2194. virtual ~IRunner();
  2195. virtual bool aborting() const = 0;
  2196. };
  2197. }
  2198. // end catch_interfaces_runner.h
  2199. #ifdef __OBJC__
  2200. // start catch_objc.hpp
  2201. #import <objc/runtime.h>
  2202. #include <string>
  2203. // NB. Any general catch headers included here must be included
  2204. // in catch.hpp first to make sure they are included by the single
  2205. // header for non obj-usage
  2206. ///////////////////////////////////////////////////////////////////////////////
  2207. // This protocol is really only here for (self) documenting purposes, since
  2208. // all its methods are optional.
  2209. @protocol OcFixture
  2210. @optional
  2211. -(void) setUp;
  2212. -(void) tearDown;
  2213. @end
  2214. namespace Catch {
  2215. class OcMethod : public ITestInvoker {
  2216. public:
  2217. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  2218. virtual void invoke() const {
  2219. id obj = [[m_cls alloc] init];
  2220. performOptionalSelector( obj, @selector(setUp) );
  2221. performOptionalSelector( obj, m_sel );
  2222. performOptionalSelector( obj, @selector(tearDown) );
  2223. arcSafeRelease( obj );
  2224. }
  2225. private:
  2226. virtual ~OcMethod() {}
  2227. Class m_cls;
  2228. SEL m_sel;
  2229. };
  2230. namespace Detail{
  2231. inline std::string getAnnotation( Class cls,
  2232. std::string const& annotationName,
  2233. std::string const& testCaseName ) {
  2234. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  2235. SEL sel = NSSelectorFromString( selStr );
  2236. arcSafeRelease( selStr );
  2237. id value = performOptionalSelector( cls, sel );
  2238. if( value )
  2239. return [(NSString*)value UTF8String];
  2240. return "";
  2241. }
  2242. }
  2243. inline std::size_t registerTestMethods() {
  2244. std::size_t noTestMethods = 0;
  2245. int noClasses = objc_getClassList( nullptr, 0 );
  2246. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  2247. objc_getClassList( classes, noClasses );
  2248. for( int c = 0; c < noClasses; c++ ) {
  2249. Class cls = classes[c];
  2250. {
  2251. u_int count;
  2252. Method* methods = class_copyMethodList( cls, &count );
  2253. for( u_int m = 0; m < count ; m++ ) {
  2254. SEL selector = method_getName(methods[m]);
  2255. std::string methodName = sel_getName(selector);
  2256. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  2257. std::string testCaseName = methodName.substr( 15 );
  2258. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  2259. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  2260. const char* className = class_getName( cls );
  2261. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo("",0) ) );
  2262. noTestMethods++;
  2263. }
  2264. }
  2265. free(methods);
  2266. }
  2267. }
  2268. return noTestMethods;
  2269. }
  2270. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  2271. namespace Matchers {
  2272. namespace Impl {
  2273. namespace NSStringMatchers {
  2274. struct StringHolder : MatcherBase<NSString*>{
  2275. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  2276. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  2277. StringHolder() {
  2278. arcSafeRelease( m_substr );
  2279. }
  2280. bool match( NSString* arg ) const override {
  2281. return false;
  2282. }
  2283. NSString* CATCH_ARC_STRONG m_substr;
  2284. };
  2285. struct Equals : StringHolder {
  2286. Equals( NSString* substr ) : StringHolder( substr ){}
  2287. bool match( NSString* str ) const override {
  2288. return (str != nil || m_substr == nil ) &&
  2289. [str isEqualToString:m_substr];
  2290. }
  2291. std::string describe() const override {
  2292. return "equals string: " + Catch::Detail::stringify( m_substr );
  2293. }
  2294. };
  2295. struct Contains : StringHolder {
  2296. Contains( NSString* substr ) : StringHolder( substr ){}
  2297. bool match( NSString* str ) const {
  2298. return (str != nil || m_substr == nil ) &&
  2299. [str rangeOfString:m_substr].location != NSNotFound;
  2300. }
  2301. std::string describe() const override {
  2302. return "contains string: " + Catch::Detail::stringify( m_substr );
  2303. }
  2304. };
  2305. struct StartsWith : StringHolder {
  2306. StartsWith( NSString* substr ) : StringHolder( substr ){}
  2307. bool match( NSString* str ) const override {
  2308. return (str != nil || m_substr == nil ) &&
  2309. [str rangeOfString:m_substr].location == 0;
  2310. }
  2311. std::string describe() const override {
  2312. return "starts with: " + Catch::Detail::stringify( m_substr );
  2313. }
  2314. };
  2315. struct EndsWith : StringHolder {
  2316. EndsWith( NSString* substr ) : StringHolder( substr ){}
  2317. bool match( NSString* str ) const override {
  2318. return (str != nil || m_substr == nil ) &&
  2319. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  2320. }
  2321. std::string describe() const override {
  2322. return "ends with: " + Catch::Detail::stringify( m_substr );
  2323. }
  2324. };
  2325. } // namespace NSStringMatchers
  2326. } // namespace Impl
  2327. inline Impl::NSStringMatchers::Equals
  2328. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  2329. inline Impl::NSStringMatchers::Contains
  2330. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  2331. inline Impl::NSStringMatchers::StartsWith
  2332. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  2333. inline Impl::NSStringMatchers::EndsWith
  2334. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  2335. } // namespace Matchers
  2336. using namespace Matchers;
  2337. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  2338. } // namespace Catch
  2339. ///////////////////////////////////////////////////////////////////////////////
  2340. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  2341. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  2342. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  2343. { \
  2344. return @ name; \
  2345. } \
  2346. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  2347. { \
  2348. return @ desc; \
  2349. } \
  2350. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  2351. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  2352. // end catch_objc.hpp
  2353. #endif
  2354. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  2355. // start catch_external_interfaces.h
  2356. // start catch_reporter_bases.hpp
  2357. // start catch_interfaces_reporter.h
  2358. // start catch_config.hpp
  2359. // start catch_test_spec_parser.h
  2360. #ifdef __clang__
  2361. #pragma clang diagnostic push
  2362. #pragma clang diagnostic ignored "-Wpadded"
  2363. #endif
  2364. // start catch_test_spec.h
  2365. #ifdef __clang__
  2366. #pragma clang diagnostic push
  2367. #pragma clang diagnostic ignored "-Wpadded"
  2368. #endif
  2369. // start catch_wildcard_pattern.h
  2370. namespace Catch
  2371. {
  2372. class WildcardPattern {
  2373. enum WildcardPosition {
  2374. NoWildcard = 0,
  2375. WildcardAtStart = 1,
  2376. WildcardAtEnd = 2,
  2377. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  2378. };
  2379. public:
  2380. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  2381. virtual ~WildcardPattern() = default;
  2382. virtual bool matches( std::string const& str ) const;
  2383. private:
  2384. std::string adjustCase( std::string const& str ) const;
  2385. CaseSensitive::Choice m_caseSensitivity;
  2386. WildcardPosition m_wildcard = NoWildcard;
  2387. std::string m_pattern;
  2388. };
  2389. }
  2390. // end catch_wildcard_pattern.h
  2391. #include <string>
  2392. #include <vector>
  2393. #include <memory>
  2394. namespace Catch {
  2395. class TestSpec {
  2396. struct Pattern {
  2397. virtual ~Pattern();
  2398. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  2399. };
  2400. using PatternPtr = std::shared_ptr<Pattern>;
  2401. class NamePattern : public Pattern {
  2402. public:
  2403. NamePattern( std::string const& name );
  2404. virtual ~NamePattern();
  2405. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2406. private:
  2407. WildcardPattern m_wildcardPattern;
  2408. };
  2409. class TagPattern : public Pattern {
  2410. public:
  2411. TagPattern( std::string const& tag );
  2412. virtual ~TagPattern();
  2413. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2414. private:
  2415. std::string m_tag;
  2416. };
  2417. class ExcludedPattern : public Pattern {
  2418. public:
  2419. ExcludedPattern( PatternPtr const& underlyingPattern );
  2420. virtual ~ExcludedPattern();
  2421. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2422. private:
  2423. PatternPtr m_underlyingPattern;
  2424. };
  2425. struct Filter {
  2426. std::vector<PatternPtr> m_patterns;
  2427. bool matches( TestCaseInfo const& testCase ) const;
  2428. };
  2429. public:
  2430. bool hasFilters() const;
  2431. bool matches( TestCaseInfo const& testCase ) const;
  2432. private:
  2433. std::vector<Filter> m_filters;
  2434. friend class TestSpecParser;
  2435. };
  2436. }
  2437. #ifdef __clang__
  2438. #pragma clang diagnostic pop
  2439. #endif
  2440. // end catch_test_spec.h
  2441. // start catch_interfaces_tag_alias_registry.h
  2442. #include <string>
  2443. namespace Catch {
  2444. struct TagAlias;
  2445. struct ITagAliasRegistry {
  2446. virtual ~ITagAliasRegistry();
  2447. // Nullptr if not present
  2448. virtual TagAlias const* find( std::string const& alias ) const = 0;
  2449. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  2450. static ITagAliasRegistry const& get();
  2451. };
  2452. } // end namespace Catch
  2453. // end catch_interfaces_tag_alias_registry.h
  2454. namespace Catch {
  2455. class TestSpecParser {
  2456. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  2457. Mode m_mode = None;
  2458. bool m_exclusion = false;
  2459. std::size_t m_start = std::string::npos, m_pos = 0;
  2460. std::string m_arg;
  2461. std::vector<std::size_t> m_escapeChars;
  2462. TestSpec::Filter m_currentFilter;
  2463. TestSpec m_testSpec;
  2464. ITagAliasRegistry const* m_tagAliases = nullptr;
  2465. public:
  2466. TestSpecParser( ITagAliasRegistry const& tagAliases );
  2467. TestSpecParser& parse( std::string const& arg );
  2468. TestSpec testSpec();
  2469. private:
  2470. void visitChar( char c );
  2471. void startNewMode( Mode mode, std::size_t start );
  2472. void escape();
  2473. std::string subString() const;
  2474. template<typename T>
  2475. void addPattern() {
  2476. std::string token = subString();
  2477. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  2478. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  2479. m_escapeChars.clear();
  2480. if( startsWith( token, "exclude:" ) ) {
  2481. m_exclusion = true;
  2482. token = token.substr( 8 );
  2483. }
  2484. if( !token.empty() ) {
  2485. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  2486. if( m_exclusion )
  2487. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  2488. m_currentFilter.m_patterns.push_back( pattern );
  2489. }
  2490. m_exclusion = false;
  2491. m_mode = None;
  2492. }
  2493. void addFilter();
  2494. };
  2495. TestSpec parseTestSpec( std::string const& arg );
  2496. } // namespace Catch
  2497. #ifdef __clang__
  2498. #pragma clang diagnostic pop
  2499. #endif
  2500. // end catch_test_spec_parser.h
  2501. // start catch_interfaces_config.h
  2502. #include <iosfwd>
  2503. #include <string>
  2504. #include <vector>
  2505. #include <memory>
  2506. namespace Catch {
  2507. enum class Verbosity {
  2508. Quiet = 0,
  2509. Normal,
  2510. High
  2511. };
  2512. struct WarnAbout { enum What {
  2513. Nothing = 0x00,
  2514. NoAssertions = 0x01
  2515. }; };
  2516. struct ShowDurations { enum OrNot {
  2517. DefaultForReporter,
  2518. Always,
  2519. Never
  2520. }; };
  2521. struct RunTests { enum InWhatOrder {
  2522. InDeclarationOrder,
  2523. InLexicographicalOrder,
  2524. InRandomOrder
  2525. }; };
  2526. struct UseColour { enum YesOrNo {
  2527. Auto,
  2528. Yes,
  2529. No
  2530. }; };
  2531. struct WaitForKeypress { enum When {
  2532. Never,
  2533. BeforeStart = 1,
  2534. BeforeExit = 2,
  2535. BeforeStartAndExit = BeforeStart | BeforeExit
  2536. }; };
  2537. class TestSpec;
  2538. struct IConfig : NonCopyable {
  2539. virtual ~IConfig();
  2540. virtual bool allowThrows() const = 0;
  2541. virtual std::ostream& stream() const = 0;
  2542. virtual std::string name() const = 0;
  2543. virtual bool includeSuccessfulResults() const = 0;
  2544. virtual bool shouldDebugBreak() const = 0;
  2545. virtual bool warnAboutMissingAssertions() const = 0;
  2546. virtual int abortAfter() const = 0;
  2547. virtual bool showInvisibles() const = 0;
  2548. virtual ShowDurations::OrNot showDurations() const = 0;
  2549. virtual TestSpec const& testSpec() const = 0;
  2550. virtual RunTests::InWhatOrder runOrder() const = 0;
  2551. virtual unsigned int rngSeed() const = 0;
  2552. virtual int benchmarkResolutionMultiple() const = 0;
  2553. virtual UseColour::YesOrNo useColour() const = 0;
  2554. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  2555. virtual Verbosity verbosity() const = 0;
  2556. };
  2557. using IConfigPtr = std::shared_ptr<IConfig const>;
  2558. }
  2559. // end catch_interfaces_config.h
  2560. // Libstdc++ doesn't like incomplete classes for unique_ptr
  2561. #include <memory>
  2562. #include <vector>
  2563. #include <string>
  2564. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  2565. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  2566. #endif
  2567. namespace Catch {
  2568. struct IStream;
  2569. struct ConfigData {
  2570. bool listTests = false;
  2571. bool listTags = false;
  2572. bool listReporters = false;
  2573. bool listTestNamesOnly = false;
  2574. bool showSuccessfulTests = false;
  2575. bool shouldDebugBreak = false;
  2576. bool noThrow = false;
  2577. bool showHelp = false;
  2578. bool showInvisibles = false;
  2579. bool filenamesAsTags = false;
  2580. bool libIdentify = false;
  2581. int abortAfter = -1;
  2582. unsigned int rngSeed = 0;
  2583. int benchmarkResolutionMultiple = 100;
  2584. Verbosity verbosity = Verbosity::Normal;
  2585. WarnAbout::What warnings = WarnAbout::Nothing;
  2586. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  2587. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  2588. UseColour::YesOrNo useColour = UseColour::Auto;
  2589. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  2590. std::string outputFilename;
  2591. std::string name;
  2592. std::string processName;
  2593. std::vector<std::string> reporterNames;
  2594. std::vector<std::string> testsOrTags;
  2595. std::vector<std::string> sectionsToRun;
  2596. };
  2597. class Config : public IConfig {
  2598. public:
  2599. Config() = default;
  2600. Config( ConfigData const& data );
  2601. virtual ~Config() = default;
  2602. std::string const& getFilename() const;
  2603. bool listTests() const;
  2604. bool listTestNamesOnly() const;
  2605. bool listTags() const;
  2606. bool listReporters() const;
  2607. std::string getProcessName() const;
  2608. std::vector<std::string> const& getReporterNames() const;
  2609. std::vector<std::string> const& getSectionsToRun() const override;
  2610. virtual TestSpec const& testSpec() const override;
  2611. bool showHelp() const;
  2612. // IConfig interface
  2613. bool allowThrows() const override;
  2614. std::ostream& stream() const override;
  2615. std::string name() const override;
  2616. bool includeSuccessfulResults() const override;
  2617. bool warnAboutMissingAssertions() const override;
  2618. ShowDurations::OrNot showDurations() const override;
  2619. RunTests::InWhatOrder runOrder() const override;
  2620. unsigned int rngSeed() const override;
  2621. int benchmarkResolutionMultiple() const override;
  2622. UseColour::YesOrNo useColour() const override;
  2623. bool shouldDebugBreak() const override;
  2624. int abortAfter() const override;
  2625. bool showInvisibles() const override;
  2626. Verbosity verbosity() const override;
  2627. private:
  2628. IStream const* openStream();
  2629. ConfigData m_data;
  2630. std::unique_ptr<IStream const> m_stream;
  2631. TestSpec m_testSpec;
  2632. };
  2633. } // end namespace Catch
  2634. // end catch_config.hpp
  2635. // start catch_assertionresult.h
  2636. #include <string>
  2637. namespace Catch {
  2638. struct AssertionResultData
  2639. {
  2640. AssertionResultData() = delete;
  2641. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  2642. std::string message;
  2643. mutable std::string reconstructedExpression;
  2644. LazyExpression lazyExpression;
  2645. ResultWas::OfType resultType;
  2646. std::string reconstructExpression() const;
  2647. };
  2648. class AssertionResult {
  2649. public:
  2650. AssertionResult() = delete;
  2651. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  2652. bool isOk() const;
  2653. bool succeeded() const;
  2654. ResultWas::OfType getResultType() const;
  2655. bool hasExpression() const;
  2656. bool hasMessage() const;
  2657. std::string getExpression() const;
  2658. std::string getExpressionInMacro() const;
  2659. bool hasExpandedExpression() const;
  2660. std::string getExpandedExpression() const;
  2661. std::string getMessage() const;
  2662. SourceLineInfo getSourceInfo() const;
  2663. StringRef getTestMacroName() const;
  2664. //protected:
  2665. AssertionInfo m_info;
  2666. AssertionResultData m_resultData;
  2667. };
  2668. } // end namespace Catch
  2669. // end catch_assertionresult.h
  2670. // start catch_option.hpp
  2671. namespace Catch {
  2672. // An optional type
  2673. template<typename T>
  2674. class Option {
  2675. public:
  2676. Option() : nullableValue( nullptr ) {}
  2677. Option( T const& _value )
  2678. : nullableValue( new( storage ) T( _value ) )
  2679. {}
  2680. Option( Option const& _other )
  2681. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  2682. {}
  2683. ~Option() {
  2684. reset();
  2685. }
  2686. Option& operator= ( Option const& _other ) {
  2687. if( &_other != this ) {
  2688. reset();
  2689. if( _other )
  2690. nullableValue = new( storage ) T( *_other );
  2691. }
  2692. return *this;
  2693. }
  2694. Option& operator = ( T const& _value ) {
  2695. reset();
  2696. nullableValue = new( storage ) T( _value );
  2697. return *this;
  2698. }
  2699. void reset() {
  2700. if( nullableValue )
  2701. nullableValue->~T();
  2702. nullableValue = nullptr;
  2703. }
  2704. T& operator*() { return *nullableValue; }
  2705. T const& operator*() const { return *nullableValue; }
  2706. T* operator->() { return nullableValue; }
  2707. const T* operator->() const { return nullableValue; }
  2708. T valueOr( T const& defaultValue ) const {
  2709. return nullableValue ? *nullableValue : defaultValue;
  2710. }
  2711. bool some() const { return nullableValue != nullptr; }
  2712. bool none() const { return nullableValue == nullptr; }
  2713. bool operator !() const { return nullableValue == nullptr; }
  2714. explicit operator bool() const {
  2715. return some();
  2716. }
  2717. private:
  2718. T *nullableValue;
  2719. alignas(alignof(T)) char storage[sizeof(T)];
  2720. };
  2721. } // end namespace Catch
  2722. // end catch_option.hpp
  2723. #include <string>
  2724. #include <iosfwd>
  2725. #include <map>
  2726. #include <set>
  2727. #include <memory>
  2728. namespace Catch {
  2729. struct ReporterConfig {
  2730. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  2731. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  2732. std::ostream& stream() const;
  2733. IConfigPtr fullConfig() const;
  2734. private:
  2735. std::ostream* m_stream;
  2736. IConfigPtr m_fullConfig;
  2737. };
  2738. struct ReporterPreferences {
  2739. bool shouldRedirectStdOut = false;
  2740. };
  2741. template<typename T>
  2742. struct LazyStat : Option<T> {
  2743. LazyStat& operator=( T const& _value ) {
  2744. Option<T>::operator=( _value );
  2745. used = false;
  2746. return *this;
  2747. }
  2748. void reset() {
  2749. Option<T>::reset();
  2750. used = false;
  2751. }
  2752. bool used = false;
  2753. };
  2754. struct TestRunInfo {
  2755. TestRunInfo( std::string const& _name );
  2756. std::string name;
  2757. };
  2758. struct GroupInfo {
  2759. GroupInfo( std::string const& _name,
  2760. std::size_t _groupIndex,
  2761. std::size_t _groupsCount );
  2762. std::string name;
  2763. std::size_t groupIndex;
  2764. std::size_t groupsCounts;
  2765. };
  2766. struct AssertionStats {
  2767. AssertionStats( AssertionResult const& _assertionResult,
  2768. std::vector<MessageInfo> const& _infoMessages,
  2769. Totals const& _totals );
  2770. AssertionStats( AssertionStats const& ) = default;
  2771. AssertionStats( AssertionStats && ) = default;
  2772. AssertionStats& operator = ( AssertionStats const& ) = default;
  2773. AssertionStats& operator = ( AssertionStats && ) = default;
  2774. virtual ~AssertionStats();
  2775. AssertionResult assertionResult;
  2776. std::vector<MessageInfo> infoMessages;
  2777. Totals totals;
  2778. };
  2779. struct SectionStats {
  2780. SectionStats( SectionInfo const& _sectionInfo,
  2781. Counts const& _assertions,
  2782. double _durationInSeconds,
  2783. bool _missingAssertions );
  2784. SectionStats( SectionStats const& ) = default;
  2785. SectionStats( SectionStats && ) = default;
  2786. SectionStats& operator = ( SectionStats const& ) = default;
  2787. SectionStats& operator = ( SectionStats && ) = default;
  2788. virtual ~SectionStats();
  2789. SectionInfo sectionInfo;
  2790. Counts assertions;
  2791. double durationInSeconds;
  2792. bool missingAssertions;
  2793. };
  2794. struct TestCaseStats {
  2795. TestCaseStats( TestCaseInfo const& _testInfo,
  2796. Totals const& _totals,
  2797. std::string const& _stdOut,
  2798. std::string const& _stdErr,
  2799. bool _aborting );
  2800. TestCaseStats( TestCaseStats const& ) = default;
  2801. TestCaseStats( TestCaseStats && ) = default;
  2802. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  2803. TestCaseStats& operator = ( TestCaseStats && ) = default;
  2804. virtual ~TestCaseStats();
  2805. TestCaseInfo testInfo;
  2806. Totals totals;
  2807. std::string stdOut;
  2808. std::string stdErr;
  2809. bool aborting;
  2810. };
  2811. struct TestGroupStats {
  2812. TestGroupStats( GroupInfo const& _groupInfo,
  2813. Totals const& _totals,
  2814. bool _aborting );
  2815. TestGroupStats( GroupInfo const& _groupInfo );
  2816. TestGroupStats( TestGroupStats const& ) = default;
  2817. TestGroupStats( TestGroupStats && ) = default;
  2818. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  2819. TestGroupStats& operator = ( TestGroupStats && ) = default;
  2820. virtual ~TestGroupStats();
  2821. GroupInfo groupInfo;
  2822. Totals totals;
  2823. bool aborting;
  2824. };
  2825. struct TestRunStats {
  2826. TestRunStats( TestRunInfo const& _runInfo,
  2827. Totals const& _totals,
  2828. bool _aborting );
  2829. TestRunStats( TestRunStats const& ) = default;
  2830. TestRunStats( TestRunStats && ) = default;
  2831. TestRunStats& operator = ( TestRunStats const& ) = default;
  2832. TestRunStats& operator = ( TestRunStats && ) = default;
  2833. virtual ~TestRunStats();
  2834. TestRunInfo runInfo;
  2835. Totals totals;
  2836. bool aborting;
  2837. };
  2838. struct BenchmarkInfo {
  2839. std::string name;
  2840. };
  2841. struct BenchmarkStats {
  2842. BenchmarkInfo info;
  2843. std::size_t iterations;
  2844. uint64_t elapsedTimeInNanoseconds;
  2845. };
  2846. struct IStreamingReporter {
  2847. virtual ~IStreamingReporter() = default;
  2848. // Implementing class must also provide the following static methods:
  2849. // static std::string getDescription();
  2850. // static std::set<Verbosity> getSupportedVerbosities()
  2851. virtual ReporterPreferences getPreferences() const = 0;
  2852. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  2853. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  2854. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  2855. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  2856. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  2857. // *** experimental ***
  2858. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  2859. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  2860. // The return value indicates if the messages buffer should be cleared:
  2861. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  2862. // *** experimental ***
  2863. virtual void benchmarkEnded( BenchmarkStats const& ) {}
  2864. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  2865. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  2866. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  2867. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  2868. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  2869. // Default empty implementation provided
  2870. virtual void fatalErrorEncountered( StringRef name );
  2871. virtual bool isMulti() const;
  2872. };
  2873. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  2874. struct IReporterFactory {
  2875. virtual ~IReporterFactory();
  2876. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  2877. virtual std::string getDescription() const = 0;
  2878. };
  2879. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2880. struct IReporterRegistry {
  2881. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  2882. using Listeners = std::vector<IReporterFactoryPtr>;
  2883. virtual ~IReporterRegistry();
  2884. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  2885. virtual FactoryMap const& getFactories() const = 0;
  2886. virtual Listeners const& getListeners() const = 0;
  2887. };
  2888. void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter );
  2889. } // end namespace Catch
  2890. // end catch_interfaces_reporter.h
  2891. #include <algorithm>
  2892. #include <cstring>
  2893. #include <cfloat>
  2894. #include <cstdio>
  2895. #include <assert.h>
  2896. #include <memory>
  2897. #include <ostream>
  2898. namespace Catch {
  2899. void prepareExpandedExpression(AssertionResult& result);
  2900. // Returns double formatted as %.3f (format expected on output)
  2901. std::string getFormattedDuration( double duration );
  2902. template<typename DerivedT>
  2903. struct StreamingReporterBase : IStreamingReporter {
  2904. StreamingReporterBase( ReporterConfig const& _config )
  2905. : m_config( _config.fullConfig() ),
  2906. stream( _config.stream() )
  2907. {
  2908. m_reporterPrefs.shouldRedirectStdOut = false;
  2909. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  2910. throw std::domain_error( "Verbosity level not supported by this reporter" );
  2911. }
  2912. ReporterPreferences getPreferences() const override {
  2913. return m_reporterPrefs;
  2914. }
  2915. static std::set<Verbosity> getSupportedVerbosities() {
  2916. return { Verbosity::Normal };
  2917. }
  2918. ~StreamingReporterBase() override = default;
  2919. void noMatchingTestCases(std::string const&) override {}
  2920. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  2921. currentTestRunInfo = _testRunInfo;
  2922. }
  2923. void testGroupStarting(GroupInfo const& _groupInfo) override {
  2924. currentGroupInfo = _groupInfo;
  2925. }
  2926. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  2927. currentTestCaseInfo = _testInfo;
  2928. }
  2929. void sectionStarting(SectionInfo const& _sectionInfo) override {
  2930. m_sectionStack.push_back(_sectionInfo);
  2931. }
  2932. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  2933. m_sectionStack.pop_back();
  2934. }
  2935. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  2936. currentTestCaseInfo.reset();
  2937. }
  2938. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  2939. currentGroupInfo.reset();
  2940. }
  2941. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  2942. currentTestCaseInfo.reset();
  2943. currentGroupInfo.reset();
  2944. currentTestRunInfo.reset();
  2945. }
  2946. void skipTest(TestCaseInfo const&) override {
  2947. // Don't do anything with this by default.
  2948. // It can optionally be overridden in the derived class.
  2949. }
  2950. IConfigPtr m_config;
  2951. std::ostream& stream;
  2952. LazyStat<TestRunInfo> currentTestRunInfo;
  2953. LazyStat<GroupInfo> currentGroupInfo;
  2954. LazyStat<TestCaseInfo> currentTestCaseInfo;
  2955. std::vector<SectionInfo> m_sectionStack;
  2956. ReporterPreferences m_reporterPrefs;
  2957. };
  2958. template<typename DerivedT>
  2959. struct CumulativeReporterBase : IStreamingReporter {
  2960. template<typename T, typename ChildNodeT>
  2961. struct Node {
  2962. explicit Node( T const& _value ) : value( _value ) {}
  2963. virtual ~Node() {}
  2964. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  2965. T value;
  2966. ChildNodes children;
  2967. };
  2968. struct SectionNode {
  2969. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  2970. virtual ~SectionNode() = default;
  2971. bool operator == (SectionNode const& other) const {
  2972. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  2973. }
  2974. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  2975. return operator==(*other);
  2976. }
  2977. SectionStats stats;
  2978. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  2979. using Assertions = std::vector<AssertionStats>;
  2980. ChildSections childSections;
  2981. Assertions assertions;
  2982. std::string stdOut;
  2983. std::string stdErr;
  2984. };
  2985. struct BySectionInfo {
  2986. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  2987. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  2988. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  2989. return ((node->stats.sectionInfo.name == m_other.name) &&
  2990. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  2991. }
  2992. void operator=(BySectionInfo const&) = delete;
  2993. private:
  2994. SectionInfo const& m_other;
  2995. };
  2996. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  2997. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  2998. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  2999. CumulativeReporterBase( ReporterConfig const& _config )
  3000. : m_config( _config.fullConfig() ),
  3001. stream( _config.stream() )
  3002. {
  3003. m_reporterPrefs.shouldRedirectStdOut = false;
  3004. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3005. throw std::domain_error( "Verbosity level not supported by this reporter" );
  3006. }
  3007. ~CumulativeReporterBase() override = default;
  3008. ReporterPreferences getPreferences() const override {
  3009. return m_reporterPrefs;
  3010. }
  3011. static std::set<Verbosity> getSupportedVerbosities() {
  3012. return { Verbosity::Normal };
  3013. }
  3014. void testRunStarting( TestRunInfo const& ) override {}
  3015. void testGroupStarting( GroupInfo const& ) override {}
  3016. void testCaseStarting( TestCaseInfo const& ) override {}
  3017. void sectionStarting( SectionInfo const& sectionInfo ) override {
  3018. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  3019. std::shared_ptr<SectionNode> node;
  3020. if( m_sectionStack.empty() ) {
  3021. if( !m_rootSection )
  3022. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  3023. node = m_rootSection;
  3024. }
  3025. else {
  3026. SectionNode& parentNode = *m_sectionStack.back();
  3027. auto it =
  3028. std::find_if( parentNode.childSections.begin(),
  3029. parentNode.childSections.end(),
  3030. BySectionInfo( sectionInfo ) );
  3031. if( it == parentNode.childSections.end() ) {
  3032. node = std::make_shared<SectionNode>( incompleteStats );
  3033. parentNode.childSections.push_back( node );
  3034. }
  3035. else
  3036. node = *it;
  3037. }
  3038. m_sectionStack.push_back( node );
  3039. m_deepestSection = std::move(node);
  3040. }
  3041. void assertionStarting(AssertionInfo const&) override {}
  3042. bool assertionEnded(AssertionStats const& assertionStats) override {
  3043. assert(!m_sectionStack.empty());
  3044. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  3045. // which getExpandedExpression() calls to build the expression string.
  3046. // Our section stack copy of the assertionResult will likely outlive the
  3047. // temporary, so it must be expanded or discarded now to avoid calling
  3048. // a destroyed object later.
  3049. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  3050. SectionNode& sectionNode = *m_sectionStack.back();
  3051. sectionNode.assertions.push_back(assertionStats);
  3052. return true;
  3053. }
  3054. void sectionEnded(SectionStats const& sectionStats) override {
  3055. assert(!m_sectionStack.empty());
  3056. SectionNode& node = *m_sectionStack.back();
  3057. node.stats = sectionStats;
  3058. m_sectionStack.pop_back();
  3059. }
  3060. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  3061. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  3062. assert(m_sectionStack.size() == 0);
  3063. node->children.push_back(m_rootSection);
  3064. m_testCases.push_back(node);
  3065. m_rootSection.reset();
  3066. assert(m_deepestSection);
  3067. m_deepestSection->stdOut = testCaseStats.stdOut;
  3068. m_deepestSection->stdErr = testCaseStats.stdErr;
  3069. }
  3070. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  3071. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  3072. node->children.swap(m_testCases);
  3073. m_testGroups.push_back(node);
  3074. }
  3075. void testRunEnded(TestRunStats const& testRunStats) override {
  3076. auto node = std::make_shared<TestRunNode>(testRunStats);
  3077. node->children.swap(m_testGroups);
  3078. m_testRuns.push_back(node);
  3079. testRunEndedCumulative();
  3080. }
  3081. virtual void testRunEndedCumulative() = 0;
  3082. void skipTest(TestCaseInfo const&) override {}
  3083. IConfigPtr m_config;
  3084. std::ostream& stream;
  3085. std::vector<AssertionStats> m_assertions;
  3086. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  3087. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  3088. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  3089. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  3090. std::shared_ptr<SectionNode> m_rootSection;
  3091. std::shared_ptr<SectionNode> m_deepestSection;
  3092. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  3093. ReporterPreferences m_reporterPrefs;
  3094. };
  3095. template<char C>
  3096. char const* getLineOfChars() {
  3097. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  3098. if( !*line ) {
  3099. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  3100. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  3101. }
  3102. return line;
  3103. }
  3104. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  3105. TestEventListenerBase( ReporterConfig const& _config );
  3106. void assertionStarting(AssertionInfo const&) override;
  3107. bool assertionEnded(AssertionStats const&) override;
  3108. };
  3109. } // end namespace Catch
  3110. // end catch_reporter_bases.hpp
  3111. // start catch_console_colour.h
  3112. namespace Catch {
  3113. struct Colour {
  3114. enum Code {
  3115. None = 0,
  3116. White,
  3117. Red,
  3118. Green,
  3119. Blue,
  3120. Cyan,
  3121. Yellow,
  3122. Grey,
  3123. Bright = 0x10,
  3124. BrightRed = Bright | Red,
  3125. BrightGreen = Bright | Green,
  3126. LightGrey = Bright | Grey,
  3127. BrightWhite = Bright | White,
  3128. // By intention
  3129. FileName = LightGrey,
  3130. Warning = Yellow,
  3131. ResultError = BrightRed,
  3132. ResultSuccess = BrightGreen,
  3133. ResultExpectedFailure = Warning,
  3134. Error = BrightRed,
  3135. Success = Green,
  3136. OriginalExpression = Cyan,
  3137. ReconstructedExpression = Yellow,
  3138. SecondaryText = LightGrey,
  3139. Headers = White
  3140. };
  3141. // Use constructed object for RAII guard
  3142. Colour( Code _colourCode );
  3143. Colour( Colour&& other ) noexcept;
  3144. Colour& operator=( Colour&& other ) noexcept;
  3145. ~Colour();
  3146. // Use static method for one-shot changes
  3147. static void use( Code _colourCode );
  3148. private:
  3149. bool m_moved = false;
  3150. };
  3151. std::ostream& operator << ( std::ostream& os, Colour const& );
  3152. } // end namespace Catch
  3153. // end catch_console_colour.h
  3154. // start catch_reporter_registrars.hpp
  3155. namespace Catch {
  3156. template<typename T>
  3157. class ReporterRegistrar {
  3158. class ReporterFactory : public IReporterFactory {
  3159. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3160. return std::unique_ptr<T>( new T( config ) );
  3161. }
  3162. virtual std::string getDescription() const override {
  3163. return T::getDescription();
  3164. }
  3165. };
  3166. public:
  3167. explicit ReporterRegistrar( std::string const& name ) {
  3168. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  3169. }
  3170. };
  3171. template<typename T>
  3172. class ListenerRegistrar {
  3173. class ListenerFactory : public IReporterFactory {
  3174. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3175. return std::unique_ptr<T>( new T( config ) );
  3176. }
  3177. virtual std::string getDescription() const override {
  3178. return std::string();
  3179. }
  3180. };
  3181. public:
  3182. ListenerRegistrar() {
  3183. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  3184. }
  3185. };
  3186. }
  3187. #if !defined(CATCH_CONFIG_DISABLE)
  3188. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  3189. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3190. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  3191. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  3192. #define CATCH_REGISTER_LISTENER( listenerType ) \
  3193. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3194. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  3195. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  3196. #else // CATCH_CONFIG_DISABLE
  3197. #define CATCH_REGISTER_REPORTER(name, reporterType)
  3198. #define CATCH_REGISTER_LISTENER(listenerType)
  3199. #endif // CATCH_CONFIG_DISABLE
  3200. // end catch_reporter_registrars.hpp
  3201. // Allow users to base their work off existing reporters
  3202. // start catch_reporter_compact.h
  3203. namespace Catch {
  3204. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  3205. using StreamingReporterBase::StreamingReporterBase;
  3206. ~CompactReporter() override;
  3207. static std::string getDescription();
  3208. ReporterPreferences getPreferences() const override;
  3209. void noMatchingTestCases(std::string const& spec) override;
  3210. void assertionStarting(AssertionInfo const&) override;
  3211. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3212. void sectionEnded(SectionStats const& _sectionStats) override;
  3213. void testRunEnded(TestRunStats const& _testRunStats) override;
  3214. };
  3215. } // end namespace Catch
  3216. // end catch_reporter_compact.h
  3217. // start catch_reporter_console.h
  3218. #if defined(_MSC_VER)
  3219. #pragma warning(push)
  3220. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  3221. // Note that 4062 (not all labels are handled
  3222. // and default is missing) is enabled
  3223. #endif
  3224. namespace Catch {
  3225. // Fwd decls
  3226. struct SummaryColumn;
  3227. class TablePrinter;
  3228. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  3229. std::unique_ptr<TablePrinter> m_tablePrinter;
  3230. ConsoleReporter(ReporterConfig const& config);
  3231. ~ConsoleReporter() override;
  3232. static std::string getDescription();
  3233. void noMatchingTestCases(std::string const& spec) override;
  3234. void assertionStarting(AssertionInfo const&) override;
  3235. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3236. void sectionStarting(SectionInfo const& _sectionInfo) override;
  3237. void sectionEnded(SectionStats const& _sectionStats) override;
  3238. void benchmarkStarting(BenchmarkInfo const& info) override;
  3239. void benchmarkEnded(BenchmarkStats const& stats) override;
  3240. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  3241. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  3242. void testRunEnded(TestRunStats const& _testRunStats) override;
  3243. private:
  3244. void lazyPrint();
  3245. void lazyPrintWithoutClosingBenchmarkTable();
  3246. void lazyPrintRunInfo();
  3247. void lazyPrintGroupInfo();
  3248. void printTestCaseAndSectionHeader();
  3249. void printClosedHeader(std::string const& _name);
  3250. void printOpenHeader(std::string const& _name);
  3251. // if string has a : in first line will set indent to follow it on
  3252. // subsequent lines
  3253. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  3254. void printTotals(Totals const& totals);
  3255. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  3256. void printTotalsDivider(Totals const& totals);
  3257. void printSummaryDivider();
  3258. private:
  3259. bool m_headerPrinted = false;
  3260. };
  3261. } // end namespace Catch
  3262. #if defined(_MSC_VER)
  3263. #pragma warning(pop)
  3264. #endif
  3265. // end catch_reporter_console.h
  3266. // start catch_reporter_junit.h
  3267. // start catch_xmlwriter.h
  3268. #include <vector>
  3269. namespace Catch {
  3270. class XmlEncode {
  3271. public:
  3272. enum ForWhat { ForTextNodes, ForAttributes };
  3273. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  3274. void encodeTo( std::ostream& os ) const;
  3275. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  3276. private:
  3277. std::string m_str;
  3278. ForWhat m_forWhat;
  3279. };
  3280. class XmlWriter {
  3281. public:
  3282. class ScopedElement {
  3283. public:
  3284. ScopedElement( XmlWriter* writer );
  3285. ScopedElement( ScopedElement&& other ) noexcept;
  3286. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  3287. ~ScopedElement();
  3288. ScopedElement& writeText( std::string const& text, bool indent = true );
  3289. template<typename T>
  3290. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  3291. m_writer->writeAttribute( name, attribute );
  3292. return *this;
  3293. }
  3294. private:
  3295. mutable XmlWriter* m_writer = nullptr;
  3296. };
  3297. XmlWriter( std::ostream& os = Catch::cout() );
  3298. ~XmlWriter();
  3299. XmlWriter( XmlWriter const& ) = delete;
  3300. XmlWriter& operator=( XmlWriter const& ) = delete;
  3301. XmlWriter& startElement( std::string const& name );
  3302. ScopedElement scopedElement( std::string const& name );
  3303. XmlWriter& endElement();
  3304. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  3305. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  3306. template<typename T>
  3307. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  3308. ReusableStringStream rss;
  3309. rss << attribute;
  3310. return writeAttribute( name, rss.str() );
  3311. }
  3312. XmlWriter& writeText( std::string const& text, bool indent = true );
  3313. XmlWriter& writeComment( std::string const& text );
  3314. void writeStylesheetRef( std::string const& url );
  3315. XmlWriter& writeBlankLine();
  3316. void ensureTagClosed();
  3317. private:
  3318. void writeDeclaration();
  3319. void newlineIfNecessary();
  3320. bool m_tagIsOpen = false;
  3321. bool m_needsNewline = false;
  3322. std::vector<std::string> m_tags;
  3323. std::string m_indent;
  3324. std::ostream& m_os;
  3325. };
  3326. }
  3327. // end catch_xmlwriter.h
  3328. namespace Catch {
  3329. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  3330. public:
  3331. JunitReporter(ReporterConfig const& _config);
  3332. ~JunitReporter() override;
  3333. static std::string getDescription();
  3334. void noMatchingTestCases(std::string const& /*spec*/) override;
  3335. void testRunStarting(TestRunInfo const& runInfo) override;
  3336. void testGroupStarting(GroupInfo const& groupInfo) override;
  3337. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  3338. bool assertionEnded(AssertionStats const& assertionStats) override;
  3339. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3340. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3341. void testRunEndedCumulative() override;
  3342. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  3343. void writeTestCase(TestCaseNode const& testCaseNode);
  3344. void writeSection(std::string const& className,
  3345. std::string const& rootName,
  3346. SectionNode const& sectionNode);
  3347. void writeAssertions(SectionNode const& sectionNode);
  3348. void writeAssertion(AssertionStats const& stats);
  3349. XmlWriter xml;
  3350. Timer suiteTimer;
  3351. std::string stdOutForSuite;
  3352. std::string stdErrForSuite;
  3353. unsigned int unexpectedExceptions = 0;
  3354. bool m_okToFail = false;
  3355. };
  3356. } // end namespace Catch
  3357. // end catch_reporter_junit.h
  3358. // start catch_reporter_xml.h
  3359. namespace Catch {
  3360. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  3361. public:
  3362. XmlReporter(ReporterConfig const& _config);
  3363. ~XmlReporter() override;
  3364. static std::string getDescription();
  3365. virtual std::string getStylesheetRef() const;
  3366. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  3367. public: // StreamingReporterBase
  3368. void noMatchingTestCases(std::string const& s) override;
  3369. void testRunStarting(TestRunInfo const& testInfo) override;
  3370. void testGroupStarting(GroupInfo const& groupInfo) override;
  3371. void testCaseStarting(TestCaseInfo const& testInfo) override;
  3372. void sectionStarting(SectionInfo const& sectionInfo) override;
  3373. void assertionStarting(AssertionInfo const&) override;
  3374. bool assertionEnded(AssertionStats const& assertionStats) override;
  3375. void sectionEnded(SectionStats const& sectionStats) override;
  3376. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3377. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3378. void testRunEnded(TestRunStats const& testRunStats) override;
  3379. private:
  3380. Timer m_testCaseTimer;
  3381. XmlWriter m_xml;
  3382. int m_sectionDepth = 0;
  3383. };
  3384. } // end namespace Catch
  3385. // end catch_reporter_xml.h
  3386. // end catch_external_interfaces.h
  3387. #endif
  3388. #endif // ! CATCH_CONFIG_IMPL_ONLY
  3389. #ifdef CATCH_IMPL
  3390. // start catch_impl.hpp
  3391. #ifdef __clang__
  3392. #pragma clang diagnostic push
  3393. #pragma clang diagnostic ignored "-Wweak-vtables"
  3394. #endif
  3395. // Keep these here for external reporters
  3396. // start catch_test_case_tracker.h
  3397. #include <string>
  3398. #include <vector>
  3399. #include <memory>
  3400. namespace Catch {
  3401. namespace TestCaseTracking {
  3402. struct NameAndLocation {
  3403. std::string name;
  3404. SourceLineInfo location;
  3405. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  3406. };
  3407. struct ITracker;
  3408. using ITrackerPtr = std::shared_ptr<ITracker>;
  3409. struct ITracker {
  3410. virtual ~ITracker();
  3411. // static queries
  3412. virtual NameAndLocation const& nameAndLocation() const = 0;
  3413. // dynamic queries
  3414. virtual bool isComplete() const = 0; // Successfully completed or failed
  3415. virtual bool isSuccessfullyCompleted() const = 0;
  3416. virtual bool isOpen() const = 0; // Started but not complete
  3417. virtual bool hasChildren() const = 0;
  3418. virtual ITracker& parent() = 0;
  3419. // actions
  3420. virtual void close() = 0; // Successfully complete
  3421. virtual void fail() = 0;
  3422. virtual void markAsNeedingAnotherRun() = 0;
  3423. virtual void addChild( ITrackerPtr const& child ) = 0;
  3424. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  3425. virtual void openChild() = 0;
  3426. // Debug/ checking
  3427. virtual bool isSectionTracker() const = 0;
  3428. virtual bool isIndexTracker() const = 0;
  3429. };
  3430. class TrackerContext {
  3431. enum RunState {
  3432. NotStarted,
  3433. Executing,
  3434. CompletedCycle
  3435. };
  3436. ITrackerPtr m_rootTracker;
  3437. ITracker* m_currentTracker = nullptr;
  3438. RunState m_runState = NotStarted;
  3439. public:
  3440. static TrackerContext& instance();
  3441. ITracker& startRun();
  3442. void endRun();
  3443. void startCycle();
  3444. void completeCycle();
  3445. bool completedCycle() const;
  3446. ITracker& currentTracker();
  3447. void setCurrentTracker( ITracker* tracker );
  3448. };
  3449. class TrackerBase : public ITracker {
  3450. protected:
  3451. enum CycleState {
  3452. NotStarted,
  3453. Executing,
  3454. ExecutingChildren,
  3455. NeedsAnotherRun,
  3456. CompletedSuccessfully,
  3457. Failed
  3458. };
  3459. class TrackerHasName {
  3460. NameAndLocation m_nameAndLocation;
  3461. public:
  3462. TrackerHasName( NameAndLocation const& nameAndLocation );
  3463. bool operator ()( ITrackerPtr const& tracker ) const;
  3464. };
  3465. using Children = std::vector<ITrackerPtr>;
  3466. NameAndLocation m_nameAndLocation;
  3467. TrackerContext& m_ctx;
  3468. ITracker* m_parent;
  3469. Children m_children;
  3470. CycleState m_runState = NotStarted;
  3471. public:
  3472. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3473. NameAndLocation const& nameAndLocation() const override;
  3474. bool isComplete() const override;
  3475. bool isSuccessfullyCompleted() const override;
  3476. bool isOpen() const override;
  3477. bool hasChildren() const override;
  3478. void addChild( ITrackerPtr const& child ) override;
  3479. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  3480. ITracker& parent() override;
  3481. void openChild() override;
  3482. bool isSectionTracker() const override;
  3483. bool isIndexTracker() const override;
  3484. void open();
  3485. void close() override;
  3486. void fail() override;
  3487. void markAsNeedingAnotherRun() override;
  3488. private:
  3489. void moveToParent();
  3490. void moveToThis();
  3491. };
  3492. class SectionTracker : public TrackerBase {
  3493. std::vector<std::string> m_filters;
  3494. public:
  3495. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3496. bool isSectionTracker() const override;
  3497. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  3498. void tryOpen();
  3499. void addInitialFilters( std::vector<std::string> const& filters );
  3500. void addNextFilters( std::vector<std::string> const& filters );
  3501. };
  3502. class IndexTracker : public TrackerBase {
  3503. int m_size;
  3504. int m_index = -1;
  3505. public:
  3506. IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size );
  3507. bool isIndexTracker() const override;
  3508. void close() override;
  3509. static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size );
  3510. int index() const;
  3511. void moveNext();
  3512. };
  3513. } // namespace TestCaseTracking
  3514. using TestCaseTracking::ITracker;
  3515. using TestCaseTracking::TrackerContext;
  3516. using TestCaseTracking::SectionTracker;
  3517. using TestCaseTracking::IndexTracker;
  3518. } // namespace Catch
  3519. // end catch_test_case_tracker.h
  3520. // start catch_leak_detector.h
  3521. namespace Catch {
  3522. struct LeakDetector {
  3523. LeakDetector();
  3524. };
  3525. }
  3526. // end catch_leak_detector.h
  3527. // Cpp files will be included in the single-header file here
  3528. // start catch_approx.cpp
  3529. #include <cmath>
  3530. #include <limits>
  3531. namespace {
  3532. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  3533. // But without the subtraction to allow for INFINITY in comparison
  3534. bool marginComparison(double lhs, double rhs, double margin) {
  3535. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  3536. }
  3537. }
  3538. namespace Catch {
  3539. namespace Detail {
  3540. Approx::Approx ( double value )
  3541. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  3542. m_margin( 0.0 ),
  3543. m_scale( 0.0 ),
  3544. m_value( value )
  3545. {}
  3546. Approx Approx::custom() {
  3547. return Approx( 0 );
  3548. }
  3549. std::string Approx::toString() const {
  3550. ReusableStringStream rss;
  3551. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  3552. return rss.str();
  3553. }
  3554. bool Approx::equalityComparisonImpl(const double other) const {
  3555. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  3556. // Thanks to Richard Harris for his help refining the scaled margin value
  3557. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  3558. }
  3559. } // end namespace Detail
  3560. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  3561. return value.toString();
  3562. }
  3563. } // end namespace Catch
  3564. // end catch_approx.cpp
  3565. // start catch_assertionhandler.cpp
  3566. // start catch_context.h
  3567. #include <memory>
  3568. namespace Catch {
  3569. struct IResultCapture;
  3570. struct IRunner;
  3571. struct IConfig;
  3572. struct IMutableContext;
  3573. using IConfigPtr = std::shared_ptr<IConfig const>;
  3574. struct IContext
  3575. {
  3576. virtual ~IContext();
  3577. virtual IResultCapture* getResultCapture() = 0;
  3578. virtual IRunner* getRunner() = 0;
  3579. virtual IConfigPtr const& getConfig() const = 0;
  3580. };
  3581. struct IMutableContext : IContext
  3582. {
  3583. virtual ~IMutableContext();
  3584. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3585. virtual void setRunner( IRunner* runner ) = 0;
  3586. virtual void setConfig( IConfigPtr const& config ) = 0;
  3587. private:
  3588. static IMutableContext *currentContext;
  3589. friend IMutableContext& getCurrentMutableContext();
  3590. friend void cleanUpContext();
  3591. static void createContext();
  3592. };
  3593. inline IMutableContext& getCurrentMutableContext()
  3594. {
  3595. if( !IMutableContext::currentContext )
  3596. IMutableContext::createContext();
  3597. return *IMutableContext::currentContext;
  3598. }
  3599. inline IContext& getCurrentContext()
  3600. {
  3601. return getCurrentMutableContext();
  3602. }
  3603. void cleanUpContext();
  3604. }
  3605. // end catch_context.h
  3606. // start catch_debugger.h
  3607. namespace Catch {
  3608. bool isDebuggerActive();
  3609. }
  3610. #ifdef CATCH_PLATFORM_MAC
  3611. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  3612. #elif defined(CATCH_PLATFORM_LINUX)
  3613. // If we can use inline assembler, do it because this allows us to break
  3614. // directly at the location of the failing check instead of breaking inside
  3615. // raise() called from it, i.e. one stack frame below.
  3616. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  3617. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  3618. #else // Fall back to the generic way.
  3619. #include <signal.h>
  3620. #define CATCH_TRAP() raise(SIGTRAP)
  3621. #endif
  3622. #elif defined(_MSC_VER)
  3623. #define CATCH_TRAP() __debugbreak()
  3624. #elif defined(__MINGW32__)
  3625. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  3626. #define CATCH_TRAP() DebugBreak()
  3627. #endif
  3628. #ifdef CATCH_TRAP
  3629. #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
  3630. #else
  3631. #define CATCH_BREAK_INTO_DEBUGGER() (void)0, 0
  3632. #endif
  3633. // end catch_debugger.h
  3634. // start catch_run_context.h
  3635. // start catch_fatal_condition.h
  3636. #include <string>
  3637. #if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
  3638. // start catch_windows_h_proxy.h
  3639. #if defined(CATCH_PLATFORM_WINDOWS)
  3640. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  3641. # define CATCH_DEFINED_NOMINMAX
  3642. # define NOMINMAX
  3643. #endif
  3644. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  3645. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  3646. # define WIN32_LEAN_AND_MEAN
  3647. #endif
  3648. #ifdef __AFXDLL
  3649. #include <AfxWin.h>
  3650. #else
  3651. #include <windows.h>
  3652. #endif
  3653. #ifdef CATCH_DEFINED_NOMINMAX
  3654. # undef NOMINMAX
  3655. #endif
  3656. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  3657. # undef WIN32_LEAN_AND_MEAN
  3658. #endif
  3659. #endif // defined(CATCH_PLATFORM_WINDOWS)
  3660. // end catch_windows_h_proxy.h
  3661. # if !defined ( CATCH_CONFIG_WINDOWS_SEH )
  3662. namespace Catch {
  3663. struct FatalConditionHandler {
  3664. void reset();
  3665. };
  3666. }
  3667. # else // CATCH_CONFIG_WINDOWS_SEH is defined
  3668. namespace Catch {
  3669. struct FatalConditionHandler {
  3670. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  3671. FatalConditionHandler();
  3672. static void reset();
  3673. ~FatalConditionHandler();
  3674. private:
  3675. static bool isSet;
  3676. static ULONG guaranteeSize;
  3677. static PVOID exceptionHandlerHandle;
  3678. };
  3679. } // namespace Catch
  3680. # endif // CATCH_CONFIG_WINDOWS_SEH
  3681. #else // Not Windows - assumed to be POSIX compatible //////////////////////////
  3682. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  3683. namespace Catch {
  3684. struct FatalConditionHandler {
  3685. void reset();
  3686. };
  3687. }
  3688. # else // CATCH_CONFIG_POSIX_SIGNALS is defined
  3689. #include <signal.h>
  3690. namespace Catch {
  3691. struct FatalConditionHandler {
  3692. static bool isSet;
  3693. static struct sigaction oldSigActions[];// [sizeof(signalDefs) / sizeof(SignalDefs)];
  3694. static stack_t oldSigStack;
  3695. static char altStackMem[];
  3696. static void handleSignal( int sig );
  3697. FatalConditionHandler();
  3698. ~FatalConditionHandler();
  3699. static void reset();
  3700. };
  3701. } // namespace Catch
  3702. # endif // CATCH_CONFIG_POSIX_SIGNALS
  3703. #endif // not Windows
  3704. // end catch_fatal_condition.h
  3705. #include <string>
  3706. namespace Catch {
  3707. struct IMutableContext;
  3708. ///////////////////////////////////////////////////////////////////////////
  3709. class RunContext : public IResultCapture, public IRunner {
  3710. public:
  3711. RunContext( RunContext const& ) = delete;
  3712. RunContext& operator =( RunContext const& ) = delete;
  3713. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  3714. ~RunContext() override;
  3715. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  3716. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  3717. Totals runTest(TestCase const& testCase);
  3718. IConfigPtr config() const;
  3719. IStreamingReporter& reporter() const;
  3720. public: // IResultCapture
  3721. // Assertion handlers
  3722. void handleExpr
  3723. ( AssertionInfo const& info,
  3724. ITransientExpression const& expr,
  3725. AssertionReaction& reaction ) override;
  3726. void handleMessage
  3727. ( AssertionInfo const& info,
  3728. ResultWas::OfType resultType,
  3729. StringRef const& message,
  3730. AssertionReaction& reaction ) override;
  3731. void handleUnexpectedExceptionNotThrown
  3732. ( AssertionInfo const& info,
  3733. AssertionReaction& reaction ) override;
  3734. void handleUnexpectedInflightException
  3735. ( AssertionInfo const& info,
  3736. std::string const& message,
  3737. AssertionReaction& reaction ) override;
  3738. void handleIncomplete
  3739. ( AssertionInfo const& info ) override;
  3740. void handleNonExpr
  3741. ( AssertionInfo const &info,
  3742. ResultWas::OfType resultType,
  3743. AssertionReaction &reaction ) override;
  3744. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  3745. void sectionEnded( SectionEndInfo const& endInfo ) override;
  3746. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  3747. void benchmarkStarting( BenchmarkInfo const& info ) override;
  3748. void benchmarkEnded( BenchmarkStats const& stats ) override;
  3749. void pushScopedMessage( MessageInfo const& message ) override;
  3750. void popScopedMessage( MessageInfo const& message ) override;
  3751. std::string getCurrentTestName() const override;
  3752. const AssertionResult* getLastResult() const override;
  3753. void exceptionEarlyReported() override;
  3754. void handleFatalErrorCondition( StringRef message ) override;
  3755. bool lastAssertionPassed() override;
  3756. void assertionPassed() override;
  3757. public:
  3758. // !TBD We need to do this another way!
  3759. bool aborting() const override;
  3760. private:
  3761. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  3762. void invokeActiveTestCase();
  3763. void resetAssertionInfo();
  3764. bool testForMissingAssertions( Counts& assertions );
  3765. void assertionEnded( AssertionResult const& result );
  3766. void reportExpr
  3767. ( AssertionInfo const &info,
  3768. ResultWas::OfType resultType,
  3769. ITransientExpression const *expr,
  3770. bool negated );
  3771. void populateReaction( AssertionReaction& reaction );
  3772. private:
  3773. void handleUnfinishedSections();
  3774. TestRunInfo m_runInfo;
  3775. IMutableContext& m_context;
  3776. TestCase const* m_activeTestCase = nullptr;
  3777. ITracker* m_testCaseTracker;
  3778. Option<AssertionResult> m_lastResult;
  3779. IConfigPtr m_config;
  3780. Totals m_totals;
  3781. IStreamingReporterPtr m_reporter;
  3782. std::vector<MessageInfo> m_messages;
  3783. AssertionInfo m_lastAssertionInfo;
  3784. std::vector<SectionEndInfo> m_unfinishedSections;
  3785. std::vector<ITracker*> m_activeSections;
  3786. TrackerContext m_trackerContext;
  3787. bool m_lastAssertionPassed = false;
  3788. bool m_shouldReportUnexpected = true;
  3789. bool m_includeSuccessfulResults;
  3790. };
  3791. } // end namespace Catch
  3792. // end catch_run_context.h
  3793. namespace Catch {
  3794. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  3795. expr.streamReconstructedExpression( os );
  3796. return os;
  3797. }
  3798. LazyExpression::LazyExpression( bool isNegated )
  3799. : m_isNegated( isNegated )
  3800. {}
  3801. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  3802. LazyExpression::operator bool() const {
  3803. return m_transientExpression != nullptr;
  3804. }
  3805. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  3806. if( lazyExpr.m_isNegated )
  3807. os << "!";
  3808. if( lazyExpr ) {
  3809. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  3810. os << "(" << *lazyExpr.m_transientExpression << ")";
  3811. else
  3812. os << *lazyExpr.m_transientExpression;
  3813. }
  3814. else {
  3815. os << "{** error - unchecked empty expression requested **}";
  3816. }
  3817. return os;
  3818. }
  3819. AssertionHandler::AssertionHandler
  3820. ( StringRef macroName,
  3821. SourceLineInfo const& lineInfo,
  3822. StringRef capturedExpression,
  3823. ResultDisposition::Flags resultDisposition )
  3824. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  3825. m_resultCapture( getResultCapture() )
  3826. {}
  3827. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  3828. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  3829. }
  3830. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  3831. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  3832. }
  3833. auto AssertionHandler::allowThrows() const -> bool {
  3834. return getCurrentContext().getConfig()->allowThrows();
  3835. }
  3836. void AssertionHandler::complete() {
  3837. setCompleted();
  3838. if( m_reaction.shouldDebugBreak ) {
  3839. // If you find your debugger stopping you here then go one level up on the
  3840. // call-stack for the code that caused it (typically a failed assertion)
  3841. // (To go back to the test and change execution, jump over the throw, next)
  3842. CATCH_BREAK_INTO_DEBUGGER();
  3843. }
  3844. if( m_reaction.shouldThrow )
  3845. throw Catch::TestFailureException();
  3846. }
  3847. void AssertionHandler::setCompleted() {
  3848. m_completed = true;
  3849. }
  3850. void AssertionHandler::handleUnexpectedInflightException() {
  3851. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  3852. }
  3853. void AssertionHandler::handleExceptionThrownAsExpected() {
  3854. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  3855. }
  3856. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  3857. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  3858. }
  3859. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  3860. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  3861. }
  3862. void AssertionHandler::handleThrowingCallSkipped() {
  3863. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  3864. }
  3865. // This is the overload that takes a string and infers the Equals matcher from it
  3866. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  3867. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString ) {
  3868. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  3869. }
  3870. } // namespace Catch
  3871. // end catch_assertionhandler.cpp
  3872. // start catch_assertionresult.cpp
  3873. namespace Catch {
  3874. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  3875. lazyExpression(_lazyExpression),
  3876. resultType(_resultType) {}
  3877. std::string AssertionResultData::reconstructExpression() const {
  3878. if( reconstructedExpression.empty() ) {
  3879. if( lazyExpression ) {
  3880. ReusableStringStream rss;
  3881. rss << lazyExpression;
  3882. reconstructedExpression = rss.str();
  3883. }
  3884. }
  3885. return reconstructedExpression;
  3886. }
  3887. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  3888. : m_info( info ),
  3889. m_resultData( data )
  3890. {}
  3891. // Result was a success
  3892. bool AssertionResult::succeeded() const {
  3893. return Catch::isOk( m_resultData.resultType );
  3894. }
  3895. // Result was a success, or failure is suppressed
  3896. bool AssertionResult::isOk() const {
  3897. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  3898. }
  3899. ResultWas::OfType AssertionResult::getResultType() const {
  3900. return m_resultData.resultType;
  3901. }
  3902. bool AssertionResult::hasExpression() const {
  3903. return m_info.capturedExpression[0] != 0;
  3904. }
  3905. bool AssertionResult::hasMessage() const {
  3906. return !m_resultData.message.empty();
  3907. }
  3908. std::string AssertionResult::getExpression() const {
  3909. if( isFalseTest( m_info.resultDisposition ) )
  3910. return "!(" + m_info.capturedExpression + ")";
  3911. else
  3912. return m_info.capturedExpression;
  3913. }
  3914. std::string AssertionResult::getExpressionInMacro() const {
  3915. std::string expr;
  3916. if( m_info.macroName[0] == 0 )
  3917. expr = m_info.capturedExpression;
  3918. else {
  3919. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  3920. expr += m_info.macroName.c_str();
  3921. expr += "( ";
  3922. expr += m_info.capturedExpression.c_str();
  3923. expr += " )";
  3924. }
  3925. return expr;
  3926. }
  3927. bool AssertionResult::hasExpandedExpression() const {
  3928. return hasExpression() && getExpandedExpression() != getExpression();
  3929. }
  3930. std::string AssertionResult::getExpandedExpression() const {
  3931. std::string expr = m_resultData.reconstructExpression();
  3932. return expr.empty()
  3933. ? getExpression()
  3934. : expr;
  3935. }
  3936. std::string AssertionResult::getMessage() const {
  3937. return m_resultData.message;
  3938. }
  3939. SourceLineInfo AssertionResult::getSourceInfo() const {
  3940. return m_info.lineInfo;
  3941. }
  3942. StringRef AssertionResult::getTestMacroName() const {
  3943. return m_info.macroName;
  3944. }
  3945. } // end namespace Catch
  3946. // end catch_assertionresult.cpp
  3947. // start catch_benchmark.cpp
  3948. namespace Catch {
  3949. auto BenchmarkLooper::getResolution() -> uint64_t {
  3950. return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
  3951. }
  3952. void BenchmarkLooper::reportStart() {
  3953. getResultCapture().benchmarkStarting( { m_name } );
  3954. }
  3955. auto BenchmarkLooper::needsMoreIterations() -> bool {
  3956. auto elapsed = m_timer.getElapsedNanoseconds();
  3957. // Exponentially increasing iterations until we're confident in our timer resolution
  3958. if( elapsed < m_resolution ) {
  3959. m_iterationsToRun *= 10;
  3960. return true;
  3961. }
  3962. getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
  3963. return false;
  3964. }
  3965. } // end namespace Catch
  3966. // end catch_benchmark.cpp
  3967. // start catch_capture_matchers.cpp
  3968. namespace Catch {
  3969. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  3970. // This is the general overload that takes a any string matcher
  3971. // There is another overload, in catch_assertinhandler.h/.cpp, that only takes a string and infers
  3972. // the Equals matcher (so the header does not mention matchers)
  3973. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString ) {
  3974. std::string exceptionMessage = Catch::translateActiveException();
  3975. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  3976. handler.handleExpr( expr );
  3977. }
  3978. } // namespace Catch
  3979. // end catch_capture_matchers.cpp
  3980. // start catch_commandline.cpp
  3981. // start catch_commandline.h
  3982. // start catch_clara.h
  3983. // Use Catch's value for console width (store Clara's off to the side, if present)
  3984. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  3985. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  3986. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  3987. #endif
  3988. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  3989. #ifdef __clang__
  3990. #pragma clang diagnostic push
  3991. #pragma clang diagnostic ignored "-Wweak-vtables"
  3992. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  3993. #pragma clang diagnostic ignored "-Wshadow"
  3994. #endif
  3995. // start clara.hpp
  3996. // v1.0-develop.2
  3997. // See https://github.com/philsquared/Clara
  3998. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  3999. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  4000. #endif
  4001. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4002. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4003. #endif
  4004. // ----------- #included from clara_textflow.hpp -----------
  4005. // TextFlowCpp
  4006. //
  4007. // A single-header library for wrapping and laying out basic text, by Phil Nash
  4008. //
  4009. // This work is licensed under the BSD 2-Clause license.
  4010. // See the accompanying LICENSE file, or the one at https://opensource.org/licenses/BSD-2-Clause
  4011. //
  4012. // This project is hosted at https://github.com/philsquared/textflowcpp
  4013. #include <cassert>
  4014. #include <ostream>
  4015. #include <sstream>
  4016. #include <vector>
  4017. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4018. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  4019. #endif
  4020. namespace Catch { namespace clara { namespace TextFlow {
  4021. inline auto isWhitespace( char c ) -> bool {
  4022. static std::string chars = " \t\n\r";
  4023. return chars.find( c ) != std::string::npos;
  4024. }
  4025. inline auto isBreakableBefore( char c ) -> bool {
  4026. static std::string chars = "[({<|";
  4027. return chars.find( c ) != std::string::npos;
  4028. }
  4029. inline auto isBreakableAfter( char c ) -> bool {
  4030. static std::string chars = "])}>.,:;*+-=&/\\";
  4031. return chars.find( c ) != std::string::npos;
  4032. }
  4033. class Columns;
  4034. class Column {
  4035. std::vector<std::string> m_strings;
  4036. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  4037. size_t m_indent = 0;
  4038. size_t m_initialIndent = std::string::npos;
  4039. public:
  4040. class iterator {
  4041. friend Column;
  4042. Column const& m_column;
  4043. size_t m_stringIndex = 0;
  4044. size_t m_pos = 0;
  4045. size_t m_len = 0;
  4046. size_t m_end = 0;
  4047. bool m_suffix = false;
  4048. iterator( Column const& column, size_t stringIndex )
  4049. : m_column( column ),
  4050. m_stringIndex( stringIndex )
  4051. {}
  4052. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  4053. auto isBoundary( size_t at ) const -> bool {
  4054. assert( at > 0 );
  4055. assert( at <= line().size() );
  4056. return at == line().size() ||
  4057. ( isWhitespace( line()[at] ) && !isWhitespace( line()[at-1] ) ) ||
  4058. isBreakableBefore( line()[at] ) ||
  4059. isBreakableAfter( line()[at-1] );
  4060. }
  4061. void calcLength() {
  4062. assert( m_stringIndex < m_column.m_strings.size() );
  4063. m_suffix = false;
  4064. auto width = m_column.m_width-indent();
  4065. m_end = m_pos;
  4066. while( m_end < line().size() && line()[m_end] != '\n' )
  4067. ++m_end;
  4068. if( m_end < m_pos + width ) {
  4069. m_len = m_end - m_pos;
  4070. }
  4071. else {
  4072. size_t len = width;
  4073. while (len > 0 && !isBoundary(m_pos + len))
  4074. --len;
  4075. while (len > 0 && isWhitespace( line()[m_pos + len - 1] ))
  4076. --len;
  4077. if (len > 0) {
  4078. m_len = len;
  4079. } else {
  4080. m_suffix = true;
  4081. m_len = width - 1;
  4082. }
  4083. }
  4084. }
  4085. auto indent() const -> size_t {
  4086. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  4087. return initial == std::string::npos ? m_column.m_indent : initial;
  4088. }
  4089. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  4090. return std::string( indent(), ' ' ) + (m_suffix ? plain + "-" : plain);
  4091. }
  4092. public:
  4093. explicit iterator( Column const& column ) : m_column( column ) {
  4094. assert( m_column.m_width > m_column.m_indent );
  4095. assert( m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent );
  4096. calcLength();
  4097. if( m_len == 0 )
  4098. m_stringIndex++; // Empty string
  4099. }
  4100. auto operator *() const -> std::string {
  4101. assert( m_stringIndex < m_column.m_strings.size() );
  4102. assert( m_pos <= m_end );
  4103. if( m_pos + m_column.m_width < m_end )
  4104. return addIndentAndSuffix(line().substr(m_pos, m_len));
  4105. else
  4106. return addIndentAndSuffix(line().substr(m_pos, m_end - m_pos));
  4107. }
  4108. auto operator ++() -> iterator& {
  4109. m_pos += m_len;
  4110. if( m_pos < line().size() && line()[m_pos] == '\n' )
  4111. m_pos += 1;
  4112. else
  4113. while( m_pos < line().size() && isWhitespace( line()[m_pos] ) )
  4114. ++m_pos;
  4115. if( m_pos == line().size() ) {
  4116. m_pos = 0;
  4117. ++m_stringIndex;
  4118. }
  4119. if( m_stringIndex < m_column.m_strings.size() )
  4120. calcLength();
  4121. return *this;
  4122. }
  4123. auto operator ++(int) -> iterator {
  4124. iterator prev( *this );
  4125. operator++();
  4126. return prev;
  4127. }
  4128. auto operator ==( iterator const& other ) const -> bool {
  4129. return
  4130. m_pos == other.m_pos &&
  4131. m_stringIndex == other.m_stringIndex &&
  4132. &m_column == &other.m_column;
  4133. }
  4134. auto operator !=( iterator const& other ) const -> bool {
  4135. return !operator==( other );
  4136. }
  4137. };
  4138. using const_iterator = iterator;
  4139. explicit Column( std::string const& text ) { m_strings.push_back( text ); }
  4140. auto width( size_t newWidth ) -> Column& {
  4141. assert( newWidth > 0 );
  4142. m_width = newWidth;
  4143. return *this;
  4144. }
  4145. auto indent( size_t newIndent ) -> Column& {
  4146. m_indent = newIndent;
  4147. return *this;
  4148. }
  4149. auto initialIndent( size_t newIndent ) -> Column& {
  4150. m_initialIndent = newIndent;
  4151. return *this;
  4152. }
  4153. auto width() const -> size_t { return m_width; }
  4154. auto begin() const -> iterator { return iterator( *this ); }
  4155. auto end() const -> iterator { return { *this, m_strings.size() }; }
  4156. inline friend std::ostream& operator << ( std::ostream& os, Column const& col ) {
  4157. bool first = true;
  4158. for( auto line : col ) {
  4159. if( first )
  4160. first = false;
  4161. else
  4162. os << "\n";
  4163. os << line;
  4164. }
  4165. return os;
  4166. }
  4167. auto operator + ( Column const& other ) -> Columns;
  4168. auto toString() const -> std::string {
  4169. std::ostringstream oss;
  4170. oss << *this;
  4171. return oss.str();
  4172. }
  4173. };
  4174. class Spacer : public Column {
  4175. public:
  4176. explicit Spacer( size_t spaceWidth ) : Column( "" ) {
  4177. width( spaceWidth );
  4178. }
  4179. };
  4180. class Columns {
  4181. std::vector<Column> m_columns;
  4182. public:
  4183. class iterator {
  4184. friend Columns;
  4185. struct EndTag {};
  4186. std::vector<Column> const& m_columns;
  4187. std::vector<Column::iterator> m_iterators;
  4188. size_t m_activeIterators;
  4189. iterator( Columns const& columns, EndTag )
  4190. : m_columns( columns.m_columns ),
  4191. m_activeIterators( 0 )
  4192. {
  4193. m_iterators.reserve( m_columns.size() );
  4194. for( auto const& col : m_columns )
  4195. m_iterators.push_back( col.end() );
  4196. }
  4197. public:
  4198. explicit iterator( Columns const& columns )
  4199. : m_columns( columns.m_columns ),
  4200. m_activeIterators( m_columns.size() )
  4201. {
  4202. m_iterators.reserve( m_columns.size() );
  4203. for( auto const& col : m_columns )
  4204. m_iterators.push_back( col.begin() );
  4205. }
  4206. auto operator ==( iterator const& other ) const -> bool {
  4207. return m_iterators == other.m_iterators;
  4208. }
  4209. auto operator !=( iterator const& other ) const -> bool {
  4210. return m_iterators != other.m_iterators;
  4211. }
  4212. auto operator *() const -> std::string {
  4213. std::string row, padding;
  4214. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4215. auto width = m_columns[i].width();
  4216. if( m_iterators[i] != m_columns[i].end() ) {
  4217. std::string col = *m_iterators[i];
  4218. row += padding + col;
  4219. if( col.size() < width )
  4220. padding = std::string( width - col.size(), ' ' );
  4221. else
  4222. padding = "";
  4223. }
  4224. else {
  4225. padding += std::string( width, ' ' );
  4226. }
  4227. }
  4228. return row;
  4229. }
  4230. auto operator ++() -> iterator& {
  4231. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4232. if (m_iterators[i] != m_columns[i].end())
  4233. ++m_iterators[i];
  4234. }
  4235. return *this;
  4236. }
  4237. auto operator ++(int) -> iterator {
  4238. iterator prev( *this );
  4239. operator++();
  4240. return prev;
  4241. }
  4242. };
  4243. using const_iterator = iterator;
  4244. auto begin() const -> iterator { return iterator( *this ); }
  4245. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  4246. auto operator += ( Column const& col ) -> Columns& {
  4247. m_columns.push_back( col );
  4248. return *this;
  4249. }
  4250. auto operator + ( Column const& col ) -> Columns {
  4251. Columns combined = *this;
  4252. combined += col;
  4253. return combined;
  4254. }
  4255. inline friend std::ostream& operator << ( std::ostream& os, Columns const& cols ) {
  4256. bool first = true;
  4257. for( auto line : cols ) {
  4258. if( first )
  4259. first = false;
  4260. else
  4261. os << "\n";
  4262. os << line;
  4263. }
  4264. return os;
  4265. }
  4266. auto toString() const -> std::string {
  4267. std::ostringstream oss;
  4268. oss << *this;
  4269. return oss.str();
  4270. }
  4271. };
  4272. inline auto Column::operator + ( Column const& other ) -> Columns {
  4273. Columns cols;
  4274. cols += *this;
  4275. cols += other;
  4276. return cols;
  4277. }
  4278. }}} // namespace Catch::clara::TextFlow
  4279. // ----------- end of #include from clara_textflow.hpp -----------
  4280. // ........... back in clara.hpp
  4281. #include <memory>
  4282. #include <set>
  4283. #include <algorithm>
  4284. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  4285. #define CATCH_PLATFORM_WINDOWS
  4286. #endif
  4287. namespace Catch { namespace clara {
  4288. namespace detail {
  4289. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  4290. template<typename L>
  4291. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  4292. template<typename ClassT, typename ReturnT, typename... Args>
  4293. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  4294. static const bool isValid = false;
  4295. };
  4296. template<typename ClassT, typename ReturnT, typename ArgT>
  4297. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  4298. static const bool isValid = true;
  4299. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;;
  4300. using ReturnType = ReturnT;
  4301. };
  4302. class TokenStream;
  4303. // Transport for raw args (copied from main args, or supplied via init list for testing)
  4304. class Args {
  4305. friend TokenStream;
  4306. std::string m_exeName;
  4307. std::vector<std::string> m_args;
  4308. public:
  4309. Args( int argc, char *argv[] ) {
  4310. m_exeName = argv[0];
  4311. for( int i = 1; i < argc; ++i )
  4312. m_args.push_back( argv[i] );
  4313. }
  4314. Args( std::initializer_list<std::string> args )
  4315. : m_exeName( *args.begin() ),
  4316. m_args( args.begin()+1, args.end() )
  4317. {}
  4318. auto exeName() const -> std::string {
  4319. return m_exeName;
  4320. }
  4321. };
  4322. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  4323. // may encode an option + its argument if the : or = form is used
  4324. enum class TokenType {
  4325. Option, Argument
  4326. };
  4327. struct Token {
  4328. TokenType type;
  4329. std::string token;
  4330. };
  4331. inline auto isOptPrefix( char c ) -> bool {
  4332. return c == '-'
  4333. #ifdef CATCH_PLATFORM_WINDOWS
  4334. || c == '/'
  4335. #endif
  4336. ;
  4337. }
  4338. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  4339. class TokenStream {
  4340. using Iterator = std::vector<std::string>::const_iterator;
  4341. Iterator it;
  4342. Iterator itEnd;
  4343. std::vector<Token> m_tokenBuffer;
  4344. void loadBuffer() {
  4345. m_tokenBuffer.resize( 0 );
  4346. // Skip any empty strings
  4347. while( it != itEnd && it->empty() )
  4348. ++it;
  4349. if( it != itEnd ) {
  4350. auto const &next = *it;
  4351. if( isOptPrefix( next[0] ) ) {
  4352. auto delimiterPos = next.find_first_of( " :=" );
  4353. if( delimiterPos != std::string::npos ) {
  4354. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  4355. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  4356. } else {
  4357. if( next[1] != '-' && next.size() > 2 ) {
  4358. std::string opt = "- ";
  4359. for( size_t i = 1; i < next.size(); ++i ) {
  4360. opt[1] = next[i];
  4361. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  4362. }
  4363. } else {
  4364. m_tokenBuffer.push_back( { TokenType::Option, next } );
  4365. }
  4366. }
  4367. } else {
  4368. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  4369. }
  4370. }
  4371. }
  4372. public:
  4373. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  4374. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  4375. loadBuffer();
  4376. }
  4377. explicit operator bool() const {
  4378. return !m_tokenBuffer.empty() || it != itEnd;
  4379. }
  4380. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  4381. auto operator*() const -> Token {
  4382. assert( !m_tokenBuffer.empty() );
  4383. return m_tokenBuffer.front();
  4384. }
  4385. auto operator->() const -> Token const * {
  4386. assert( !m_tokenBuffer.empty() );
  4387. return &m_tokenBuffer.front();
  4388. }
  4389. auto operator++() -> TokenStream & {
  4390. if( m_tokenBuffer.size() >= 2 ) {
  4391. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  4392. } else {
  4393. if( it != itEnd )
  4394. ++it;
  4395. loadBuffer();
  4396. }
  4397. return *this;
  4398. }
  4399. };
  4400. class ResultBase {
  4401. public:
  4402. enum Type {
  4403. Ok, LogicError, RuntimeError
  4404. };
  4405. protected:
  4406. ResultBase( Type type ) : m_type( type ) {}
  4407. virtual ~ResultBase() = default;
  4408. virtual void enforceOk() const = 0;
  4409. Type m_type;
  4410. };
  4411. template<typename T>
  4412. class ResultValueBase : public ResultBase {
  4413. public:
  4414. auto value() const -> T const & {
  4415. enforceOk();
  4416. return m_value;
  4417. }
  4418. protected:
  4419. ResultValueBase( Type type ) : ResultBase( type ) {}
  4420. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  4421. if( m_type == ResultBase::Ok )
  4422. new( &m_value ) T( other.m_value );
  4423. }
  4424. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  4425. new( &m_value ) T( value );
  4426. }
  4427. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  4428. if( m_type == ResultBase::Ok )
  4429. m_value.~T();
  4430. ResultBase::operator=(other);
  4431. if( m_type == ResultBase::Ok )
  4432. new( &m_value ) T( other.m_value );
  4433. return *this;
  4434. }
  4435. ~ResultValueBase() {
  4436. if( m_type == Ok )
  4437. m_value.~T();
  4438. }
  4439. union {
  4440. T m_value;
  4441. };
  4442. };
  4443. template<>
  4444. class ResultValueBase<void> : public ResultBase {
  4445. protected:
  4446. using ResultBase::ResultBase;
  4447. };
  4448. template<typename T = void>
  4449. class BasicResult : public ResultValueBase<T> {
  4450. public:
  4451. template<typename U>
  4452. explicit BasicResult( BasicResult<U> const &other )
  4453. : ResultValueBase<T>( other.type() ),
  4454. m_errorMessage( other.errorMessage() )
  4455. {
  4456. assert( type() != ResultBase::Ok );
  4457. }
  4458. template<typename U>
  4459. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  4460. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  4461. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  4462. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  4463. explicit operator bool() const { return m_type == ResultBase::Ok; }
  4464. auto type() const -> ResultBase::Type { return m_type; }
  4465. auto errorMessage() const -> std::string { return m_errorMessage; }
  4466. protected:
  4467. virtual void enforceOk() const {
  4468. // !TBD: If no exceptions, std::terminate here or something
  4469. switch( m_type ) {
  4470. case ResultBase::LogicError:
  4471. throw std::logic_error( m_errorMessage );
  4472. case ResultBase::RuntimeError:
  4473. throw std::runtime_error( m_errorMessage );
  4474. case ResultBase::Ok:
  4475. break;
  4476. }
  4477. }
  4478. std::string m_errorMessage; // Only populated if resultType is an error
  4479. BasicResult( ResultBase::Type type, std::string const &message )
  4480. : ResultValueBase<T>(type),
  4481. m_errorMessage(message)
  4482. {
  4483. assert( m_type != ResultBase::Ok );
  4484. }
  4485. using ResultValueBase<T>::ResultValueBase;
  4486. using ResultBase::m_type;
  4487. };
  4488. enum class ParseResultType {
  4489. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  4490. };
  4491. class ParseState {
  4492. public:
  4493. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  4494. : m_type(type),
  4495. m_remainingTokens( remainingTokens )
  4496. {}
  4497. auto type() const -> ParseResultType { return m_type; }
  4498. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  4499. private:
  4500. ParseResultType m_type;
  4501. TokenStream m_remainingTokens;
  4502. };
  4503. using Result = BasicResult<void>;
  4504. using ParserResult = BasicResult<ParseResultType>;
  4505. using InternalParseResult = BasicResult<ParseState>;
  4506. struct HelpColumns {
  4507. std::string left;
  4508. std::string right;
  4509. };
  4510. template<typename T>
  4511. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  4512. std::stringstream ss;
  4513. ss << source;
  4514. ss >> target;
  4515. if( ss.fail() )
  4516. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  4517. else
  4518. return ParserResult::ok( ParseResultType::Matched );
  4519. }
  4520. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  4521. target = source;
  4522. return ParserResult::ok( ParseResultType::Matched );
  4523. }
  4524. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  4525. std::string srcLC = source;
  4526. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( ::tolower(c) ); } );
  4527. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  4528. target = true;
  4529. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  4530. target = false;
  4531. else
  4532. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  4533. return ParserResult::ok( ParseResultType::Matched );
  4534. }
  4535. struct BoundRefBase {
  4536. BoundRefBase() = default;
  4537. BoundRefBase( BoundRefBase const & ) = delete;
  4538. BoundRefBase( BoundRefBase && ) = delete;
  4539. BoundRefBase &operator=( BoundRefBase const & ) = delete;
  4540. BoundRefBase &operator=( BoundRefBase && ) = delete;
  4541. virtual ~BoundRefBase() = default;
  4542. virtual auto isFlag() const -> bool = 0;
  4543. virtual auto isContainer() const -> bool { return false; }
  4544. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  4545. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  4546. };
  4547. struct BoundValueRefBase : BoundRefBase {
  4548. auto isFlag() const -> bool override { return false; }
  4549. auto setFlag( bool ) -> ParserResult override {
  4550. return ParserResult::logicError( "Flags can only be set on boolean fields" );
  4551. }
  4552. };
  4553. struct BoundFlagRefBase : BoundRefBase {
  4554. auto isFlag() const -> bool override { return true; }
  4555. auto setValue( std::string const &arg ) -> ParserResult override {
  4556. bool flag;
  4557. auto result = convertInto( arg, flag );
  4558. if( result )
  4559. setFlag( flag );
  4560. return result;
  4561. }
  4562. };
  4563. template<typename T>
  4564. struct BoundRef : BoundValueRefBase {
  4565. T &m_ref;
  4566. explicit BoundRef( T &ref ) : m_ref( ref ) {}
  4567. auto setValue( std::string const &arg ) -> ParserResult override {
  4568. return convertInto( arg, m_ref );
  4569. }
  4570. };
  4571. template<typename T>
  4572. struct BoundRef<std::vector<T>> : BoundValueRefBase {
  4573. std::vector<T> &m_ref;
  4574. explicit BoundRef( std::vector<T> &ref ) : m_ref( ref ) {}
  4575. auto isContainer() const -> bool override { return true; }
  4576. auto setValue( std::string const &arg ) -> ParserResult override {
  4577. T temp;
  4578. auto result = convertInto( arg, temp );
  4579. if( result )
  4580. m_ref.push_back( temp );
  4581. return result;
  4582. }
  4583. };
  4584. struct BoundFlagRef : BoundFlagRefBase {
  4585. bool &m_ref;
  4586. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  4587. auto setFlag( bool flag ) -> ParserResult override {
  4588. m_ref = flag;
  4589. return ParserResult::ok( ParseResultType::Matched );
  4590. }
  4591. };
  4592. template<typename ReturnType>
  4593. struct LambdaInvoker {
  4594. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  4595. template<typename L, typename ArgType>
  4596. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4597. return lambda( arg );
  4598. }
  4599. };
  4600. template<>
  4601. struct LambdaInvoker<void> {
  4602. template<typename L, typename ArgType>
  4603. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4604. lambda( arg );
  4605. return ParserResult::ok( ParseResultType::Matched );
  4606. }
  4607. };
  4608. template<typename ArgType, typename L>
  4609. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  4610. ArgType temp;
  4611. auto result = convertInto( arg, temp );
  4612. return !result
  4613. ? result
  4614. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  4615. };
  4616. template<typename L>
  4617. struct BoundLambda : BoundValueRefBase {
  4618. L m_lambda;
  4619. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4620. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  4621. auto setValue( std::string const &arg ) -> ParserResult override {
  4622. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  4623. }
  4624. };
  4625. template<typename L>
  4626. struct BoundFlagLambda : BoundFlagRefBase {
  4627. L m_lambda;
  4628. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4629. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  4630. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  4631. auto setFlag( bool flag ) -> ParserResult override {
  4632. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  4633. }
  4634. };
  4635. enum class Optionality { Optional, Required };
  4636. struct Parser;
  4637. class ParserBase {
  4638. public:
  4639. virtual ~ParserBase() = default;
  4640. virtual auto validate() const -> Result { return Result::ok(); }
  4641. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  4642. virtual auto cardinality() const -> size_t { return 1; }
  4643. auto parse( Args const &args ) const -> InternalParseResult {
  4644. return parse( args.exeName(), TokenStream( args ) );
  4645. }
  4646. };
  4647. template<typename DerivedT>
  4648. class ComposableParserImpl : public ParserBase {
  4649. public:
  4650. template<typename T>
  4651. auto operator|( T const &other ) const -> Parser;
  4652. };
  4653. // Common code and state for Args and Opts
  4654. template<typename DerivedT>
  4655. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  4656. protected:
  4657. Optionality m_optionality = Optionality::Optional;
  4658. std::shared_ptr<BoundRefBase> m_ref;
  4659. std::string m_hint;
  4660. std::string m_description;
  4661. explicit ParserRefImpl( std::shared_ptr<BoundRefBase> const &ref ) : m_ref( ref ) {}
  4662. public:
  4663. template<typename T>
  4664. ParserRefImpl( T &ref, std::string const &hint )
  4665. : m_ref( std::make_shared<BoundRef<T>>( ref ) ),
  4666. m_hint( hint )
  4667. {}
  4668. template<typename LambdaT>
  4669. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  4670. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  4671. m_hint(hint)
  4672. {}
  4673. auto operator()( std::string const &description ) -> DerivedT & {
  4674. m_description = description;
  4675. return static_cast<DerivedT &>( *this );
  4676. }
  4677. auto optional() -> DerivedT & {
  4678. m_optionality = Optionality::Optional;
  4679. return static_cast<DerivedT &>( *this );
  4680. };
  4681. auto required() -> DerivedT & {
  4682. m_optionality = Optionality::Required;
  4683. return static_cast<DerivedT &>( *this );
  4684. };
  4685. auto isOptional() const -> bool {
  4686. return m_optionality == Optionality::Optional;
  4687. }
  4688. auto cardinality() const -> size_t override {
  4689. if( m_ref->isContainer() )
  4690. return 0;
  4691. else
  4692. return 1;
  4693. }
  4694. auto hint() const -> std::string { return m_hint; }
  4695. };
  4696. class ExeName : public ComposableParserImpl<ExeName> {
  4697. std::shared_ptr<std::string> m_name;
  4698. std::shared_ptr<BoundRefBase> m_ref;
  4699. template<typename LambdaT>
  4700. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundRefBase> {
  4701. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  4702. }
  4703. public:
  4704. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  4705. explicit ExeName( std::string &ref ) : ExeName() {
  4706. m_ref = std::make_shared<BoundRef<std::string>>( ref );
  4707. }
  4708. template<typename LambdaT>
  4709. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  4710. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  4711. }
  4712. // The exe name is not parsed out of the normal tokens, but is handled specially
  4713. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4714. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  4715. }
  4716. auto name() const -> std::string { return *m_name; }
  4717. auto set( std::string const& newName ) -> ParserResult {
  4718. auto lastSlash = newName.find_last_of( "\\/" );
  4719. auto filename = ( lastSlash == std::string::npos )
  4720. ? newName
  4721. : newName.substr( lastSlash+1 );
  4722. *m_name = filename;
  4723. if( m_ref )
  4724. return m_ref->setValue( filename );
  4725. else
  4726. return ParserResult::ok( ParseResultType::Matched );
  4727. }
  4728. };
  4729. class Arg : public ParserRefImpl<Arg> {
  4730. public:
  4731. using ParserRefImpl::ParserRefImpl;
  4732. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  4733. auto validationResult = validate();
  4734. if( !validationResult )
  4735. return InternalParseResult( validationResult );
  4736. auto remainingTokens = tokens;
  4737. auto const &token = *remainingTokens;
  4738. if( token.type != TokenType::Argument )
  4739. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  4740. auto result = m_ref->setValue( remainingTokens->token );
  4741. if( !result )
  4742. return InternalParseResult( result );
  4743. else
  4744. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  4745. }
  4746. };
  4747. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  4748. #ifdef CATCH_PLATFORM_WINDOWS
  4749. if( optName[0] == '/' )
  4750. return "-" + optName.substr( 1 );
  4751. else
  4752. #endif
  4753. return optName;
  4754. }
  4755. class Opt : public ParserRefImpl<Opt> {
  4756. protected:
  4757. std::vector<std::string> m_optNames;
  4758. public:
  4759. template<typename LambdaT>
  4760. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  4761. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  4762. template<typename LambdaT>
  4763. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4764. template<typename T>
  4765. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4766. auto operator[]( std::string const &optName ) -> Opt & {
  4767. m_optNames.push_back( optName );
  4768. return *this;
  4769. }
  4770. auto getHelpColumns() const -> std::vector<HelpColumns> {
  4771. std::ostringstream oss;
  4772. bool first = true;
  4773. for( auto const &opt : m_optNames ) {
  4774. if (first)
  4775. first = false;
  4776. else
  4777. oss << ", ";
  4778. oss << opt;
  4779. }
  4780. if( !m_hint.empty() )
  4781. oss << " <" << m_hint << ">";
  4782. return { { oss.str(), m_description } };
  4783. }
  4784. auto isMatch( std::string const &optToken ) const -> bool {
  4785. auto normalisedToken = normaliseOpt( optToken );
  4786. for( auto const &name : m_optNames ) {
  4787. if( normaliseOpt( name ) == normalisedToken )
  4788. return true;
  4789. }
  4790. return false;
  4791. }
  4792. using ParserBase::parse;
  4793. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4794. auto validationResult = validate();
  4795. if( !validationResult )
  4796. return InternalParseResult( validationResult );
  4797. auto remainingTokens = tokens;
  4798. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  4799. auto const &token = *remainingTokens;
  4800. if( isMatch(token.token ) ) {
  4801. if( m_ref->isFlag() ) {
  4802. auto result = m_ref->setFlag( true );
  4803. if( !result )
  4804. return InternalParseResult( result );
  4805. if( result.value() == ParseResultType::ShortCircuitAll )
  4806. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  4807. } else {
  4808. ++remainingTokens;
  4809. if( !remainingTokens )
  4810. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  4811. auto const &argToken = *remainingTokens;
  4812. if( argToken.type != TokenType::Argument )
  4813. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  4814. auto result = m_ref->setValue( argToken.token );
  4815. if( !result )
  4816. return InternalParseResult( result );
  4817. if( result.value() == ParseResultType::ShortCircuitAll )
  4818. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  4819. }
  4820. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  4821. }
  4822. }
  4823. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  4824. }
  4825. auto validate() const -> Result override {
  4826. if( m_optNames.empty() )
  4827. return Result::logicError( "No options supplied to Opt" );
  4828. for( auto const &name : m_optNames ) {
  4829. if( name.empty() )
  4830. return Result::logicError( "Option name cannot be empty" );
  4831. #ifdef CATCH_PLATFORM_WINDOWS
  4832. if( name[0] != '-' && name[0] != '/' )
  4833. return Result::logicError( "Option name must begin with '-' or '/'" );
  4834. #else
  4835. if( name[0] != '-' )
  4836. return Result::logicError( "Option name must begin with '-'" );
  4837. #endif
  4838. }
  4839. return ParserRefImpl::validate();
  4840. }
  4841. };
  4842. struct Help : Opt {
  4843. Help( bool &showHelpFlag )
  4844. : Opt([&]( bool flag ) {
  4845. showHelpFlag = flag;
  4846. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  4847. })
  4848. {
  4849. static_cast<Opt &>( *this )
  4850. ("display usage information")
  4851. ["-?"]["-h"]["--help"]
  4852. .optional();
  4853. }
  4854. };
  4855. struct Parser : ParserBase {
  4856. mutable ExeName m_exeName;
  4857. std::vector<Opt> m_options;
  4858. std::vector<Arg> m_args;
  4859. auto operator|=( ExeName const &exeName ) -> Parser & {
  4860. m_exeName = exeName;
  4861. return *this;
  4862. }
  4863. auto operator|=( Arg const &arg ) -> Parser & {
  4864. m_args.push_back(arg);
  4865. return *this;
  4866. }
  4867. auto operator|=( Opt const &opt ) -> Parser & {
  4868. m_options.push_back(opt);
  4869. return *this;
  4870. }
  4871. auto operator|=( Parser const &other ) -> Parser & {
  4872. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  4873. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  4874. return *this;
  4875. }
  4876. template<typename T>
  4877. auto operator|( T const &other ) const -> Parser {
  4878. return Parser( *this ) |= other;
  4879. }
  4880. auto getHelpColumns() const -> std::vector<HelpColumns> {
  4881. std::vector<HelpColumns> cols;
  4882. for (auto const &o : m_options) {
  4883. auto childCols = o.getHelpColumns();
  4884. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  4885. }
  4886. return cols;
  4887. }
  4888. void writeToStream( std::ostream &os ) const {
  4889. if (!m_exeName.name().empty()) {
  4890. os << "usage:\n" << " " << m_exeName.name() << " ";
  4891. bool required = true, first = true;
  4892. for( auto const &arg : m_args ) {
  4893. if (first)
  4894. first = false;
  4895. else
  4896. os << " ";
  4897. if( arg.isOptional() && required ) {
  4898. os << "[";
  4899. required = false;
  4900. }
  4901. os << "<" << arg.hint() << ">";
  4902. if( arg.cardinality() == 0 )
  4903. os << " ... ";
  4904. }
  4905. if( !required )
  4906. os << "]";
  4907. if( !m_options.empty() )
  4908. os << " options";
  4909. os << "\n\nwhere options are:" << std::endl;
  4910. }
  4911. auto rows = getHelpColumns();
  4912. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  4913. size_t optWidth = 0;
  4914. for( auto const &cols : rows )
  4915. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  4916. for( auto const &cols : rows ) {
  4917. auto row =
  4918. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  4919. TextFlow::Spacer(4) +
  4920. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  4921. os << row << std::endl;
  4922. }
  4923. }
  4924. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  4925. parser.writeToStream( os );
  4926. return os;
  4927. }
  4928. auto validate() const -> Result override {
  4929. for( auto const &opt : m_options ) {
  4930. auto result = opt.validate();
  4931. if( !result )
  4932. return result;
  4933. }
  4934. for( auto const &arg : m_args ) {
  4935. auto result = arg.validate();
  4936. if( !result )
  4937. return result;
  4938. }
  4939. return Result::ok();
  4940. }
  4941. using ParserBase::parse;
  4942. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  4943. struct ParserInfo {
  4944. ParserBase const* parser = nullptr;
  4945. size_t count = 0;
  4946. };
  4947. const size_t totalParsers = m_options.size() + m_args.size();
  4948. assert( totalParsers < 512 );
  4949. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  4950. ParserInfo parseInfos[512];
  4951. {
  4952. size_t i = 0;
  4953. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  4954. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  4955. }
  4956. m_exeName.set( exeName );
  4957. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  4958. while( result.value().remainingTokens() ) {
  4959. bool tokenParsed = false;
  4960. for( size_t i = 0; i < totalParsers; ++i ) {
  4961. auto& parseInfo = parseInfos[i];
  4962. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  4963. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  4964. if (!result)
  4965. return result;
  4966. if (result.value().type() != ParseResultType::NoMatch) {
  4967. tokenParsed = true;
  4968. ++parseInfo.count;
  4969. break;
  4970. }
  4971. }
  4972. }
  4973. if( result.value().type() == ParseResultType::ShortCircuitAll )
  4974. return result;
  4975. if( !tokenParsed )
  4976. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  4977. }
  4978. // !TBD Check missing required options
  4979. return result;
  4980. }
  4981. };
  4982. template<typename DerivedT>
  4983. template<typename T>
  4984. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  4985. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  4986. }
  4987. } // namespace detail
  4988. // A Combined parser
  4989. using detail::Parser;
  4990. // A parser for options
  4991. using detail::Opt;
  4992. // A parser for arguments
  4993. using detail::Arg;
  4994. // Wrapper for argc, argv from main()
  4995. using detail::Args;
  4996. // Specifies the name of the executable
  4997. using detail::ExeName;
  4998. // Convenience wrapper for option parser that specifies the help option
  4999. using detail::Help;
  5000. // enum of result types from a parse
  5001. using detail::ParseResultType;
  5002. // Result type for parser operation
  5003. using detail::ParserResult;
  5004. }} // namespace Catch::clara
  5005. // end clara.hpp
  5006. #ifdef __clang__
  5007. #pragma clang diagnostic pop
  5008. #endif
  5009. // Restore Clara's value for console width, if present
  5010. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5011. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5012. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5013. #endif
  5014. // end catch_clara.h
  5015. namespace Catch {
  5016. clara::Parser makeCommandLineParser( ConfigData& config );
  5017. } // end namespace Catch
  5018. // end catch_commandline.h
  5019. #include <fstream>
  5020. #include <ctime>
  5021. namespace Catch {
  5022. clara::Parser makeCommandLineParser( ConfigData& config ) {
  5023. using namespace clara;
  5024. auto const setWarning = [&]( std::string const& warning ) {
  5025. if( warning != "NoAssertions" )
  5026. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  5027. config.warnings = static_cast<WarnAbout::What>( config.warnings | WarnAbout::NoAssertions );
  5028. return ParserResult::ok( ParseResultType::Matched );
  5029. };
  5030. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  5031. std::ifstream f( filename.c_str() );
  5032. if( !f.is_open() )
  5033. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  5034. std::string line;
  5035. while( std::getline( f, line ) ) {
  5036. line = trim(line);
  5037. if( !line.empty() && !startsWith( line, '#' ) ) {
  5038. if( !startsWith( line, '"' ) )
  5039. line = '"' + line + '"';
  5040. config.testsOrTags.push_back( line + ',' );
  5041. }
  5042. }
  5043. return ParserResult::ok( ParseResultType::Matched );
  5044. };
  5045. auto const setTestOrder = [&]( std::string const& order ) {
  5046. if( startsWith( "declared", order ) )
  5047. config.runOrder = RunTests::InDeclarationOrder;
  5048. else if( startsWith( "lexical", order ) )
  5049. config.runOrder = RunTests::InLexicographicalOrder;
  5050. else if( startsWith( "random", order ) )
  5051. config.runOrder = RunTests::InRandomOrder;
  5052. else
  5053. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  5054. return ParserResult::ok( ParseResultType::Matched );
  5055. };
  5056. auto const setRngSeed = [&]( std::string const& seed ) {
  5057. if( seed != "time" )
  5058. return clara::detail::convertInto( seed, config.rngSeed );
  5059. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  5060. return ParserResult::ok( ParseResultType::Matched );
  5061. };
  5062. auto const setColourUsage = [&]( std::string const& useColour ) {
  5063. auto mode = toLower( useColour );
  5064. if( mode == "yes" )
  5065. config.useColour = UseColour::Yes;
  5066. else if( mode == "no" )
  5067. config.useColour = UseColour::No;
  5068. else if( mode == "auto" )
  5069. config.useColour = UseColour::Auto;
  5070. else
  5071. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  5072. return ParserResult::ok( ParseResultType::Matched );
  5073. };
  5074. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  5075. auto keypressLc = toLower( keypress );
  5076. if( keypressLc == "start" )
  5077. config.waitForKeypress = WaitForKeypress::BeforeStart;
  5078. else if( keypressLc == "exit" )
  5079. config.waitForKeypress = WaitForKeypress::BeforeExit;
  5080. else if( keypressLc == "both" )
  5081. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  5082. else
  5083. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  5084. return ParserResult::ok( ParseResultType::Matched );
  5085. };
  5086. auto const setVerbosity = [&]( std::string const& verbosity ) {
  5087. auto lcVerbosity = toLower( verbosity );
  5088. if( lcVerbosity == "quiet" )
  5089. config.verbosity = Verbosity::Quiet;
  5090. else if( lcVerbosity == "normal" )
  5091. config.verbosity = Verbosity::Normal;
  5092. else if( lcVerbosity == "high" )
  5093. config.verbosity = Verbosity::High;
  5094. else
  5095. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  5096. return ParserResult::ok( ParseResultType::Matched );
  5097. };
  5098. auto cli
  5099. = ExeName( config.processName )
  5100. | Help( config.showHelp )
  5101. | Opt( config.listTests )
  5102. ["-l"]["--list-tests"]
  5103. ( "list all/matching test cases" )
  5104. | Opt( config.listTags )
  5105. ["-t"]["--list-tags"]
  5106. ( "list all/matching tags" )
  5107. | Opt( config.showSuccessfulTests )
  5108. ["-s"]["--success"]
  5109. ( "include successful tests in output" )
  5110. | Opt( config.shouldDebugBreak )
  5111. ["-b"]["--break"]
  5112. ( "break into debugger on failure" )
  5113. | Opt( config.noThrow )
  5114. ["-e"]["--nothrow"]
  5115. ( "skip exception tests" )
  5116. | Opt( config.showInvisibles )
  5117. ["-i"]["--invisibles"]
  5118. ( "show invisibles (tabs, newlines)" )
  5119. | Opt( config.outputFilename, "filename" )
  5120. ["-o"]["--out"]
  5121. ( "output filename" )
  5122. | Opt( config.reporterNames, "name" )
  5123. ["-r"]["--reporter"]
  5124. ( "reporter to use (defaults to console)" )
  5125. | Opt( config.name, "name" )
  5126. ["-n"]["--name"]
  5127. ( "suite name" )
  5128. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  5129. ["-a"]["--abort"]
  5130. ( "abort at first failure" )
  5131. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  5132. ["-x"]["--abortx"]
  5133. ( "abort after x failures" )
  5134. | Opt( setWarning, "warning name" )
  5135. ["-w"]["--warn"]
  5136. ( "enable warnings" )
  5137. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  5138. ["-d"]["--durations"]
  5139. ( "show test durations" )
  5140. | Opt( loadTestNamesFromFile, "filename" )
  5141. ["-f"]["--input-file"]
  5142. ( "load test names to run from a file" )
  5143. | Opt( config.filenamesAsTags )
  5144. ["-#"]["--filenames-as-tags"]
  5145. ( "adds a tag for the filename" )
  5146. | Opt( config.sectionsToRun, "section name" )
  5147. ["-c"]["--section"]
  5148. ( "specify section to run" )
  5149. | Opt( setVerbosity, "quiet|normal|high" )
  5150. ["-v"]["--verbosity"]
  5151. ( "set output verbosity" )
  5152. | Opt( config.listTestNamesOnly )
  5153. ["--list-test-names-only"]
  5154. ( "list all/matching test cases names only" )
  5155. | Opt( config.listReporters )
  5156. ["--list-reporters"]
  5157. ( "list all reporters" )
  5158. | Opt( setTestOrder, "decl|lex|rand" )
  5159. ["--order"]
  5160. ( "test case order (defaults to decl)" )
  5161. | Opt( setRngSeed, "'time'|number" )
  5162. ["--rng-seed"]
  5163. ( "set a specific seed for random numbers" )
  5164. | Opt( setColourUsage, "yes|no" )
  5165. ["--use-colour"]
  5166. ( "should output be colourised" )
  5167. | Opt( config.libIdentify )
  5168. ["--libidentify"]
  5169. ( "report name and version according to libidentify standard" )
  5170. | Opt( setWaitForKeypress, "start|exit|both" )
  5171. ["--wait-for-keypress"]
  5172. ( "waits for a keypress before exiting" )
  5173. | Opt( config.benchmarkResolutionMultiple, "multiplier" )
  5174. ["--benchmark-resolution-multiple"]
  5175. ( "multiple of clock resolution to run benchmarks" )
  5176. | Arg( config.testsOrTags, "test name|pattern|tags" )
  5177. ( "which test or tests to use" );
  5178. return cli;
  5179. }
  5180. } // end namespace Catch
  5181. // end catch_commandline.cpp
  5182. // start catch_common.cpp
  5183. #include <cstring>
  5184. #include <ostream>
  5185. namespace Catch {
  5186. bool SourceLineInfo::empty() const noexcept {
  5187. return file[0] == '\0';
  5188. }
  5189. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  5190. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  5191. }
  5192. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  5193. return line < other.line || ( line == other.line && (std::strcmp(file, other.file) < 0));
  5194. }
  5195. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  5196. #ifndef __GNUG__
  5197. os << info.file << '(' << info.line << ')';
  5198. #else
  5199. os << info.file << ':' << info.line;
  5200. #endif
  5201. return os;
  5202. }
  5203. std::string StreamEndStop::operator+() const {
  5204. return std::string();
  5205. }
  5206. NonCopyable::NonCopyable() = default;
  5207. NonCopyable::~NonCopyable() = default;
  5208. }
  5209. // end catch_common.cpp
  5210. // start catch_config.cpp
  5211. // start catch_enforce.h
  5212. #include <stdexcept>
  5213. #include <iosfwd>
  5214. #define CATCH_PREPARE_EXCEPTION( type, msg ) \
  5215. type( static_cast<std::ostringstream&&>( Catch::ReusableStringStream().get() << msg ).str() )
  5216. #define CATCH_INTERNAL_ERROR( msg ) \
  5217. throw CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg);
  5218. #define CATCH_ERROR( msg ) \
  5219. throw CATCH_PREPARE_EXCEPTION( std::domain_error, msg )
  5220. #define CATCH_ENFORCE( condition, msg ) \
  5221. do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
  5222. // end catch_enforce.h
  5223. namespace Catch {
  5224. Config::Config( ConfigData const& data )
  5225. : m_data( data ),
  5226. m_stream( openStream() )
  5227. {
  5228. if( !data.testsOrTags.empty() ) {
  5229. TestSpecParser parser( ITagAliasRegistry::get() );
  5230. for( auto const& testOrTags : data.testsOrTags )
  5231. parser.parse( testOrTags );
  5232. m_testSpec = parser.testSpec();
  5233. }
  5234. }
  5235. std::string const& Config::getFilename() const {
  5236. return m_data.outputFilename ;
  5237. }
  5238. bool Config::listTests() const { return m_data.listTests; }
  5239. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  5240. bool Config::listTags() const { return m_data.listTags; }
  5241. bool Config::listReporters() const { return m_data.listReporters; }
  5242. std::string Config::getProcessName() const { return m_data.processName; }
  5243. std::vector<std::string> const& Config::getReporterNames() const { return m_data.reporterNames; }
  5244. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  5245. TestSpec const& Config::testSpec() const { return m_testSpec; }
  5246. bool Config::showHelp() const { return m_data.showHelp; }
  5247. // IConfig interface
  5248. bool Config::allowThrows() const { return !m_data.noThrow; }
  5249. std::ostream& Config::stream() const { return m_stream->stream(); }
  5250. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  5251. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  5252. bool Config::warnAboutMissingAssertions() const { return m_data.warnings & WarnAbout::NoAssertions; }
  5253. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  5254. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  5255. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  5256. int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
  5257. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  5258. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  5259. int Config::abortAfter() const { return m_data.abortAfter; }
  5260. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  5261. Verbosity Config::verbosity() const { return m_data.verbosity; }
  5262. IStream const* Config::openStream() {
  5263. return Catch::makeStream(m_data.outputFilename);
  5264. }
  5265. } // end namespace Catch
  5266. // end catch_config.cpp
  5267. // start catch_console_colour.cpp
  5268. #if defined(__clang__)
  5269. # pragma clang diagnostic push
  5270. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  5271. #endif
  5272. // start catch_errno_guard.h
  5273. namespace Catch {
  5274. class ErrnoGuard {
  5275. public:
  5276. ErrnoGuard();
  5277. ~ErrnoGuard();
  5278. private:
  5279. int m_oldErrno;
  5280. };
  5281. }
  5282. // end catch_errno_guard.h
  5283. #include <sstream>
  5284. namespace Catch {
  5285. namespace {
  5286. struct IColourImpl {
  5287. virtual ~IColourImpl() = default;
  5288. virtual void use( Colour::Code _colourCode ) = 0;
  5289. };
  5290. struct NoColourImpl : IColourImpl {
  5291. void use( Colour::Code ) {}
  5292. static IColourImpl* instance() {
  5293. static NoColourImpl s_instance;
  5294. return &s_instance;
  5295. }
  5296. };
  5297. } // anon namespace
  5298. } // namespace Catch
  5299. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  5300. # ifdef CATCH_PLATFORM_WINDOWS
  5301. # define CATCH_CONFIG_COLOUR_WINDOWS
  5302. # else
  5303. # define CATCH_CONFIG_COLOUR_ANSI
  5304. # endif
  5305. #endif
  5306. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  5307. namespace Catch {
  5308. namespace {
  5309. class Win32ColourImpl : public IColourImpl {
  5310. public:
  5311. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  5312. {
  5313. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  5314. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  5315. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  5316. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  5317. }
  5318. virtual void use( Colour::Code _colourCode ) override {
  5319. switch( _colourCode ) {
  5320. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  5321. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5322. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  5323. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  5324. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  5325. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  5326. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  5327. case Colour::Grey: return setTextAttribute( 0 );
  5328. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  5329. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  5330. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  5331. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5332. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5333. }
  5334. }
  5335. private:
  5336. void setTextAttribute( WORD _textAttribute ) {
  5337. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  5338. }
  5339. HANDLE stdoutHandle;
  5340. WORD originalForegroundAttributes;
  5341. WORD originalBackgroundAttributes;
  5342. };
  5343. IColourImpl* platformColourInstance() {
  5344. static Win32ColourImpl s_instance;
  5345. IConfigPtr config = getCurrentContext().getConfig();
  5346. UseColour::YesOrNo colourMode = config
  5347. ? config->useColour()
  5348. : UseColour::Auto;
  5349. if( colourMode == UseColour::Auto )
  5350. colourMode = UseColour::Yes;
  5351. return colourMode == UseColour::Yes
  5352. ? &s_instance
  5353. : NoColourImpl::instance();
  5354. }
  5355. } // end anon namespace
  5356. } // end namespace Catch
  5357. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  5358. #include <unistd.h>
  5359. namespace Catch {
  5360. namespace {
  5361. // use POSIX/ ANSI console terminal codes
  5362. // Thanks to Adam Strzelecki for original contribution
  5363. // (http://github.com/nanoant)
  5364. // https://github.com/philsquared/Catch/pull/131
  5365. class PosixColourImpl : public IColourImpl {
  5366. public:
  5367. virtual void use( Colour::Code _colourCode ) override {
  5368. switch( _colourCode ) {
  5369. case Colour::None:
  5370. case Colour::White: return setColour( "[0m" );
  5371. case Colour::Red: return setColour( "[0;31m" );
  5372. case Colour::Green: return setColour( "[0;32m" );
  5373. case Colour::Blue: return setColour( "[0;34m" );
  5374. case Colour::Cyan: return setColour( "[0;36m" );
  5375. case Colour::Yellow: return setColour( "[0;33m" );
  5376. case Colour::Grey: return setColour( "[1;30m" );
  5377. case Colour::LightGrey: return setColour( "[0;37m" );
  5378. case Colour::BrightRed: return setColour( "[1;31m" );
  5379. case Colour::BrightGreen: return setColour( "[1;32m" );
  5380. case Colour::BrightWhite: return setColour( "[1;37m" );
  5381. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5382. }
  5383. }
  5384. static IColourImpl* instance() {
  5385. static PosixColourImpl s_instance;
  5386. return &s_instance;
  5387. }
  5388. private:
  5389. void setColour( const char* _escapeCode ) {
  5390. Catch::cout() << '\033' << _escapeCode;
  5391. }
  5392. };
  5393. bool useColourOnPlatform() {
  5394. return
  5395. #ifdef CATCH_PLATFORM_MAC
  5396. !isDebuggerActive() &&
  5397. #endif
  5398. isatty(STDOUT_FILENO);
  5399. }
  5400. IColourImpl* platformColourInstance() {
  5401. ErrnoGuard guard;
  5402. IConfigPtr config = getCurrentContext().getConfig();
  5403. UseColour::YesOrNo colourMode = config
  5404. ? config->useColour()
  5405. : UseColour::Auto;
  5406. if( colourMode == UseColour::Auto )
  5407. colourMode = useColourOnPlatform()
  5408. ? UseColour::Yes
  5409. : UseColour::No;
  5410. return colourMode == UseColour::Yes
  5411. ? PosixColourImpl::instance()
  5412. : NoColourImpl::instance();
  5413. }
  5414. } // end anon namespace
  5415. } // end namespace Catch
  5416. #else // not Windows or ANSI ///////////////////////////////////////////////
  5417. namespace Catch {
  5418. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  5419. } // end namespace Catch
  5420. #endif // Windows/ ANSI/ None
  5421. namespace Catch {
  5422. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  5423. Colour::Colour( Colour&& rhs ) noexcept {
  5424. m_moved = rhs.m_moved;
  5425. rhs.m_moved = true;
  5426. }
  5427. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  5428. m_moved = rhs.m_moved;
  5429. rhs.m_moved = true;
  5430. return *this;
  5431. }
  5432. Colour::~Colour(){ if( !m_moved ) use( None ); }
  5433. void Colour::use( Code _colourCode ) {
  5434. static IColourImpl* impl = platformColourInstance();
  5435. impl->use( _colourCode );
  5436. }
  5437. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  5438. return os;
  5439. }
  5440. } // end namespace Catch
  5441. #if defined(__clang__)
  5442. # pragma clang diagnostic pop
  5443. #endif
  5444. // end catch_console_colour.cpp
  5445. // start catch_context.cpp
  5446. namespace Catch {
  5447. class Context : public IMutableContext, NonCopyable {
  5448. public: // IContext
  5449. virtual IResultCapture* getResultCapture() override {
  5450. return m_resultCapture;
  5451. }
  5452. virtual IRunner* getRunner() override {
  5453. return m_runner;
  5454. }
  5455. virtual IConfigPtr const& getConfig() const override {
  5456. return m_config;
  5457. }
  5458. virtual ~Context() override;
  5459. public: // IMutableContext
  5460. virtual void setResultCapture( IResultCapture* resultCapture ) override {
  5461. m_resultCapture = resultCapture;
  5462. }
  5463. virtual void setRunner( IRunner* runner ) override {
  5464. m_runner = runner;
  5465. }
  5466. virtual void setConfig( IConfigPtr const& config ) override {
  5467. m_config = config;
  5468. }
  5469. friend IMutableContext& getCurrentMutableContext();
  5470. private:
  5471. IConfigPtr m_config;
  5472. IRunner* m_runner = nullptr;
  5473. IResultCapture* m_resultCapture = nullptr;
  5474. };
  5475. IMutableContext *IMutableContext::currentContext = nullptr;
  5476. void IMutableContext::createContext()
  5477. {
  5478. currentContext = new Context();
  5479. }
  5480. void cleanUpContext() {
  5481. delete IMutableContext::currentContext;
  5482. IMutableContext::currentContext = nullptr;
  5483. }
  5484. IContext::~IContext() = default;
  5485. IMutableContext::~IMutableContext() = default;
  5486. Context::~Context() = default;
  5487. }
  5488. // end catch_context.cpp
  5489. // start catch_debug_console.cpp
  5490. // start catch_debug_console.h
  5491. #include <string>
  5492. namespace Catch {
  5493. void writeToDebugConsole( std::string const& text );
  5494. }
  5495. // end catch_debug_console.h
  5496. #ifdef CATCH_PLATFORM_WINDOWS
  5497. namespace Catch {
  5498. void writeToDebugConsole( std::string const& text ) {
  5499. ::OutputDebugStringA( text.c_str() );
  5500. }
  5501. }
  5502. #else
  5503. namespace Catch {
  5504. void writeToDebugConsole( std::string const& text ) {
  5505. // !TBD: Need a version for Mac/ XCode and other IDEs
  5506. Catch::cout() << text;
  5507. }
  5508. }
  5509. #endif // Platform
  5510. // end catch_debug_console.cpp
  5511. // start catch_debugger.cpp
  5512. #ifdef CATCH_PLATFORM_MAC
  5513. # include <assert.h>
  5514. # include <stdbool.h>
  5515. # include <sys/types.h>
  5516. # include <unistd.h>
  5517. # include <sys/sysctl.h>
  5518. # include <cstddef>
  5519. # include <ostream>
  5520. namespace Catch {
  5521. // The following function is taken directly from the following technical note:
  5522. // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  5523. // Returns true if the current process is being debugged (either
  5524. // running under the debugger or has a debugger attached post facto).
  5525. bool isDebuggerActive(){
  5526. int mib[4];
  5527. struct kinfo_proc info;
  5528. std::size_t size;
  5529. // Initialize the flags so that, if sysctl fails for some bizarre
  5530. // reason, we get a predictable result.
  5531. info.kp_proc.p_flag = 0;
  5532. // Initialize mib, which tells sysctl the info we want, in this case
  5533. // we're looking for information about a specific process ID.
  5534. mib[0] = CTL_KERN;
  5535. mib[1] = KERN_PROC;
  5536. mib[2] = KERN_PROC_PID;
  5537. mib[3] = getpid();
  5538. // Call sysctl.
  5539. size = sizeof(info);
  5540. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  5541. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  5542. return false;
  5543. }
  5544. // We're being debugged if the P_TRACED flag is set.
  5545. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  5546. }
  5547. } // namespace Catch
  5548. #elif defined(CATCH_PLATFORM_LINUX)
  5549. #include <fstream>
  5550. #include <string>
  5551. namespace Catch{
  5552. // The standard POSIX way of detecting a debugger is to attempt to
  5553. // ptrace() the process, but this needs to be done from a child and not
  5554. // this process itself to still allow attaching to this process later
  5555. // if wanted, so is rather heavy. Under Linux we have the PID of the
  5556. // "debugger" (which doesn't need to be gdb, of course, it could also
  5557. // be strace, for example) in /proc/$PID/status, so just get it from
  5558. // there instead.
  5559. bool isDebuggerActive(){
  5560. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  5561. // This way our users can properly assert over errno values
  5562. ErrnoGuard guard;
  5563. std::ifstream in("/proc/self/status");
  5564. for( std::string line; std::getline(in, line); ) {
  5565. static const int PREFIX_LEN = 11;
  5566. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  5567. // We're traced if the PID is not 0 and no other PID starts
  5568. // with 0 digit, so it's enough to check for just a single
  5569. // character.
  5570. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  5571. }
  5572. }
  5573. return false;
  5574. }
  5575. } // namespace Catch
  5576. #elif defined(_MSC_VER)
  5577. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5578. namespace Catch {
  5579. bool isDebuggerActive() {
  5580. return IsDebuggerPresent() != 0;
  5581. }
  5582. }
  5583. #elif defined(__MINGW32__)
  5584. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5585. namespace Catch {
  5586. bool isDebuggerActive() {
  5587. return IsDebuggerPresent() != 0;
  5588. }
  5589. }
  5590. #else
  5591. namespace Catch {
  5592. bool isDebuggerActive() { return false; }
  5593. }
  5594. #endif // Platform
  5595. // end catch_debugger.cpp
  5596. // start catch_decomposer.cpp
  5597. namespace Catch {
  5598. ITransientExpression::~ITransientExpression() = default;
  5599. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  5600. if( lhs.size() + rhs.size() < 40 &&
  5601. lhs.find('\n') == std::string::npos &&
  5602. rhs.find('\n') == std::string::npos )
  5603. os << lhs << " " << op << " " << rhs;
  5604. else
  5605. os << lhs << "\n" << op << "\n" << rhs;
  5606. }
  5607. }
  5608. // end catch_decomposer.cpp
  5609. // start catch_errno_guard.cpp
  5610. #include <cerrno>
  5611. namespace Catch {
  5612. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  5613. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  5614. }
  5615. // end catch_errno_guard.cpp
  5616. // start catch_exception_translator_registry.cpp
  5617. // start catch_exception_translator_registry.h
  5618. #include <vector>
  5619. #include <string>
  5620. #include <memory>
  5621. namespace Catch {
  5622. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  5623. public:
  5624. ~ExceptionTranslatorRegistry();
  5625. virtual void registerTranslator( const IExceptionTranslator* translator );
  5626. virtual std::string translateActiveException() const override;
  5627. std::string tryTranslators() const;
  5628. private:
  5629. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  5630. };
  5631. }
  5632. // end catch_exception_translator_registry.h
  5633. #ifdef __OBJC__
  5634. #import "Foundation/Foundation.h"
  5635. #endif
  5636. namespace Catch {
  5637. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  5638. }
  5639. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  5640. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  5641. }
  5642. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  5643. try {
  5644. #ifdef __OBJC__
  5645. // In Objective-C try objective-c exceptions first
  5646. @try {
  5647. return tryTranslators();
  5648. }
  5649. @catch (NSException *exception) {
  5650. return Catch::Detail::stringify( [exception description] );
  5651. }
  5652. #else
  5653. return tryTranslators();
  5654. #endif
  5655. }
  5656. catch( TestFailureException& ) {
  5657. std::rethrow_exception(std::current_exception());
  5658. }
  5659. catch( std::exception& ex ) {
  5660. return ex.what();
  5661. }
  5662. catch( std::string& msg ) {
  5663. return msg;
  5664. }
  5665. catch( const char* msg ) {
  5666. return msg;
  5667. }
  5668. catch(...) {
  5669. return "Unknown exception";
  5670. }
  5671. }
  5672. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  5673. if( m_translators.empty() )
  5674. std::rethrow_exception(std::current_exception());
  5675. else
  5676. return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() );
  5677. }
  5678. }
  5679. // end catch_exception_translator_registry.cpp
  5680. // start catch_fatal_condition.cpp
  5681. #if defined(__GNUC__)
  5682. # pragma GCC diagnostic push
  5683. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  5684. #endif
  5685. namespace {
  5686. // Report the error condition
  5687. void reportFatal( char const * const message ) {
  5688. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  5689. }
  5690. }
  5691. #if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
  5692. # if !defined ( CATCH_CONFIG_WINDOWS_SEH )
  5693. namespace Catch {
  5694. void FatalConditionHandler::reset() {}
  5695. }
  5696. # else // CATCH_CONFIG_WINDOWS_SEH is defined
  5697. namespace Catch {
  5698. struct SignalDefs { DWORD id; const char* name; };
  5699. // There is no 1-1 mapping between signals and windows exceptions.
  5700. // Windows can easily distinguish between SO and SigSegV,
  5701. // but SigInt, SigTerm, etc are handled differently.
  5702. static SignalDefs signalDefs[] = {
  5703. { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
  5704. { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
  5705. { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
  5706. { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
  5707. };
  5708. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  5709. for (auto const& def : signalDefs) {
  5710. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  5711. reportFatal(def.name);
  5712. }
  5713. }
  5714. // If its not an exception we care about, pass it along.
  5715. // This stops us from eating debugger breaks etc.
  5716. return EXCEPTION_CONTINUE_SEARCH;
  5717. }
  5718. FatalConditionHandler::FatalConditionHandler() {
  5719. isSet = true;
  5720. // 32k seems enough for Catch to handle stack overflow,
  5721. // but the value was found experimentally, so there is no strong guarantee
  5722. guaranteeSize = 32 * 1024;
  5723. exceptionHandlerHandle = nullptr;
  5724. // Register as first handler in current chain
  5725. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  5726. // Pass in guarantee size to be filled
  5727. SetThreadStackGuarantee(&guaranteeSize);
  5728. }
  5729. void FatalConditionHandler::reset() {
  5730. if (isSet) {
  5731. // Unregister handler and restore the old guarantee
  5732. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  5733. SetThreadStackGuarantee(&guaranteeSize);
  5734. exceptionHandlerHandle = nullptr;
  5735. isSet = false;
  5736. }
  5737. }
  5738. FatalConditionHandler::~FatalConditionHandler() {
  5739. reset();
  5740. }
  5741. bool FatalConditionHandler::isSet = false;
  5742. ULONG FatalConditionHandler::guaranteeSize = 0;
  5743. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  5744. } // namespace Catch
  5745. # endif // CATCH_CONFIG_WINDOWS_SEH
  5746. #else // Not Windows - assumed to be POSIX compatible //////////////////////////
  5747. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  5748. namespace Catch {
  5749. void FatalConditionHandler::reset() {}
  5750. }
  5751. # else // CATCH_CONFIG_POSIX_SIGNALS is defined
  5752. #include <signal.h>
  5753. namespace Catch {
  5754. struct SignalDefs {
  5755. int id;
  5756. const char* name;
  5757. };
  5758. static SignalDefs signalDefs[] = {
  5759. { SIGINT, "SIGINT - Terminal interrupt signal" },
  5760. { SIGILL, "SIGILL - Illegal instruction signal" },
  5761. { SIGFPE, "SIGFPE - Floating point error signal" },
  5762. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  5763. { SIGTERM, "SIGTERM - Termination request signal" },
  5764. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  5765. };
  5766. void FatalConditionHandler::handleSignal( int sig ) {
  5767. char const * name = "<unknown signal>";
  5768. for (auto const& def : signalDefs) {
  5769. if (sig == def.id) {
  5770. name = def.name;
  5771. break;
  5772. }
  5773. }
  5774. reset();
  5775. reportFatal(name);
  5776. raise( sig );
  5777. }
  5778. FatalConditionHandler::FatalConditionHandler() {
  5779. isSet = true;
  5780. stack_t sigStack;
  5781. sigStack.ss_sp = altStackMem;
  5782. sigStack.ss_size = SIGSTKSZ;
  5783. sigStack.ss_flags = 0;
  5784. sigaltstack(&sigStack, &oldSigStack);
  5785. struct sigaction sa = { };
  5786. sa.sa_handler = handleSignal;
  5787. sa.sa_flags = SA_ONSTACK;
  5788. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  5789. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  5790. }
  5791. }
  5792. FatalConditionHandler::~FatalConditionHandler() {
  5793. reset();
  5794. }
  5795. void FatalConditionHandler::reset() {
  5796. if( isSet ) {
  5797. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  5798. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  5799. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  5800. }
  5801. // Return the old stack
  5802. sigaltstack(&oldSigStack, nullptr);
  5803. isSet = false;
  5804. }
  5805. }
  5806. bool FatalConditionHandler::isSet = false;
  5807. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  5808. stack_t FatalConditionHandler::oldSigStack = {};
  5809. char FatalConditionHandler::altStackMem[SIGSTKSZ] = {};
  5810. } // namespace Catch
  5811. # endif // CATCH_CONFIG_POSIX_SIGNALS
  5812. #endif // not Windows
  5813. #if defined(__GNUC__)
  5814. # pragma GCC diagnostic pop
  5815. #endif
  5816. // end catch_fatal_condition.cpp
  5817. // start catch_interfaces_capture.cpp
  5818. namespace Catch {
  5819. IResultCapture::~IResultCapture() = default;
  5820. }
  5821. // end catch_interfaces_capture.cpp
  5822. // start catch_interfaces_config.cpp
  5823. namespace Catch {
  5824. IConfig::~IConfig() = default;
  5825. }
  5826. // end catch_interfaces_config.cpp
  5827. // start catch_interfaces_exception.cpp
  5828. namespace Catch {
  5829. IExceptionTranslator::~IExceptionTranslator() = default;
  5830. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  5831. }
  5832. // end catch_interfaces_exception.cpp
  5833. // start catch_interfaces_registry_hub.cpp
  5834. namespace Catch {
  5835. IRegistryHub::~IRegistryHub() = default;
  5836. IMutableRegistryHub::~IMutableRegistryHub() = default;
  5837. }
  5838. // end catch_interfaces_registry_hub.cpp
  5839. // start catch_interfaces_reporter.cpp
  5840. // start catch_reporter_multi.h
  5841. namespace Catch {
  5842. class MultipleReporters : public IStreamingReporter {
  5843. using Reporters = std::vector<IStreamingReporterPtr>;
  5844. Reporters m_reporters;
  5845. public:
  5846. void add( IStreamingReporterPtr&& reporter );
  5847. public: // IStreamingReporter
  5848. ReporterPreferences getPreferences() const override;
  5849. void noMatchingTestCases( std::string const& spec ) override;
  5850. static std::set<Verbosity> getSupportedVerbosities();
  5851. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  5852. void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override;
  5853. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  5854. void testGroupStarting( GroupInfo const& groupInfo ) override;
  5855. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  5856. void sectionStarting( SectionInfo const& sectionInfo ) override;
  5857. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  5858. // The return value indicates if the messages buffer should be cleared:
  5859. bool assertionEnded( AssertionStats const& assertionStats ) override;
  5860. void sectionEnded( SectionStats const& sectionStats ) override;
  5861. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  5862. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  5863. void testRunEnded( TestRunStats const& testRunStats ) override;
  5864. void skipTest( TestCaseInfo const& testInfo ) override;
  5865. bool isMulti() const override;
  5866. };
  5867. } // end namespace Catch
  5868. // end catch_reporter_multi.h
  5869. namespace Catch {
  5870. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  5871. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  5872. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  5873. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  5874. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  5875. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  5876. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  5877. GroupInfo::GroupInfo( std::string const& _name,
  5878. std::size_t _groupIndex,
  5879. std::size_t _groupsCount )
  5880. : name( _name ),
  5881. groupIndex( _groupIndex ),
  5882. groupsCounts( _groupsCount )
  5883. {}
  5884. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  5885. std::vector<MessageInfo> const& _infoMessages,
  5886. Totals const& _totals )
  5887. : assertionResult( _assertionResult ),
  5888. infoMessages( _infoMessages ),
  5889. totals( _totals )
  5890. {
  5891. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  5892. if( assertionResult.hasMessage() ) {
  5893. // Copy message into messages list.
  5894. // !TBD This should have been done earlier, somewhere
  5895. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  5896. builder << assertionResult.getMessage();
  5897. builder.m_info.message = builder.m_stream.str();
  5898. infoMessages.push_back( builder.m_info );
  5899. }
  5900. }
  5901. AssertionStats::~AssertionStats() = default;
  5902. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  5903. Counts const& _assertions,
  5904. double _durationInSeconds,
  5905. bool _missingAssertions )
  5906. : sectionInfo( _sectionInfo ),
  5907. assertions( _assertions ),
  5908. durationInSeconds( _durationInSeconds ),
  5909. missingAssertions( _missingAssertions )
  5910. {}
  5911. SectionStats::~SectionStats() = default;
  5912. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  5913. Totals const& _totals,
  5914. std::string const& _stdOut,
  5915. std::string const& _stdErr,
  5916. bool _aborting )
  5917. : testInfo( _testInfo ),
  5918. totals( _totals ),
  5919. stdOut( _stdOut ),
  5920. stdErr( _stdErr ),
  5921. aborting( _aborting )
  5922. {}
  5923. TestCaseStats::~TestCaseStats() = default;
  5924. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  5925. Totals const& _totals,
  5926. bool _aborting )
  5927. : groupInfo( _groupInfo ),
  5928. totals( _totals ),
  5929. aborting( _aborting )
  5930. {}
  5931. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  5932. : groupInfo( _groupInfo ),
  5933. aborting( false )
  5934. {}
  5935. TestGroupStats::~TestGroupStats() = default;
  5936. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  5937. Totals const& _totals,
  5938. bool _aborting )
  5939. : runInfo( _runInfo ),
  5940. totals( _totals ),
  5941. aborting( _aborting )
  5942. {}
  5943. TestRunStats::~TestRunStats() = default;
  5944. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  5945. bool IStreamingReporter::isMulti() const { return false; }
  5946. IReporterFactory::~IReporterFactory() = default;
  5947. IReporterRegistry::~IReporterRegistry() = default;
  5948. void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter ) {
  5949. if( !existingReporter ) {
  5950. existingReporter = std::move( additionalReporter );
  5951. return;
  5952. }
  5953. MultipleReporters* multi = nullptr;
  5954. if( existingReporter->isMulti() ) {
  5955. multi = static_cast<MultipleReporters*>( existingReporter.get() );
  5956. }
  5957. else {
  5958. auto newMulti = std::unique_ptr<MultipleReporters>( new MultipleReporters );
  5959. newMulti->add( std::move( existingReporter ) );
  5960. multi = newMulti.get();
  5961. existingReporter = std::move( newMulti );
  5962. }
  5963. multi->add( std::move( additionalReporter ) );
  5964. }
  5965. } // end namespace Catch
  5966. // end catch_interfaces_reporter.cpp
  5967. // start catch_interfaces_runner.cpp
  5968. namespace Catch {
  5969. IRunner::~IRunner() = default;
  5970. }
  5971. // end catch_interfaces_runner.cpp
  5972. // start catch_interfaces_testcase.cpp
  5973. namespace Catch {
  5974. ITestInvoker::~ITestInvoker() = default;
  5975. ITestCaseRegistry::~ITestCaseRegistry() = default;
  5976. }
  5977. // end catch_interfaces_testcase.cpp
  5978. // start catch_leak_detector.cpp
  5979. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  5980. #include <crtdbg.h>
  5981. namespace Catch {
  5982. LeakDetector::LeakDetector() {
  5983. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  5984. flag |= _CRTDBG_LEAK_CHECK_DF;
  5985. flag |= _CRTDBG_ALLOC_MEM_DF;
  5986. _CrtSetDbgFlag(flag);
  5987. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  5988. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  5989. // Change this to leaking allocation's number to break there
  5990. _CrtSetBreakAlloc(-1);
  5991. }
  5992. }
  5993. #else
  5994. Catch::LeakDetector::LeakDetector() {}
  5995. #endif
  5996. // end catch_leak_detector.cpp
  5997. // start catch_list.cpp
  5998. // start catch_list.h
  5999. #include <set>
  6000. namespace Catch {
  6001. std::size_t listTests( Config const& config );
  6002. std::size_t listTestsNamesOnly( Config const& config );
  6003. struct TagInfo {
  6004. void add( std::string const& spelling );
  6005. std::string all() const;
  6006. std::set<std::string> spellings;
  6007. std::size_t count = 0;
  6008. };
  6009. std::size_t listTags( Config const& config );
  6010. std::size_t listReporters( Config const& /*config*/ );
  6011. Option<std::size_t> list( Config const& config );
  6012. } // end namespace Catch
  6013. // end catch_list.h
  6014. // start catch_text.h
  6015. namespace Catch {
  6016. using namespace clara::TextFlow;
  6017. }
  6018. // end catch_text.h
  6019. #include <limits>
  6020. #include <algorithm>
  6021. #include <iomanip>
  6022. namespace Catch {
  6023. std::size_t listTests( Config const& config ) {
  6024. TestSpec testSpec = config.testSpec();
  6025. if( config.testSpec().hasFilters() )
  6026. Catch::cout() << "Matching test cases:\n";
  6027. else {
  6028. Catch::cout() << "All available test cases:\n";
  6029. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  6030. }
  6031. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6032. for( auto const& testCaseInfo : matchedTestCases ) {
  6033. Colour::Code colour = testCaseInfo.isHidden()
  6034. ? Colour::SecondaryText
  6035. : Colour::None;
  6036. Colour colourGuard( colour );
  6037. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  6038. if( config.verbosity() >= Verbosity::High ) {
  6039. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  6040. std::string description = testCaseInfo.description;
  6041. if( description.empty() )
  6042. description = "(NO DESCRIPTION)";
  6043. Catch::cout() << Column( description ).indent(4) << std::endl;
  6044. }
  6045. if( !testCaseInfo.tags.empty() )
  6046. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  6047. }
  6048. if( !config.testSpec().hasFilters() )
  6049. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  6050. else
  6051. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  6052. return matchedTestCases.size();
  6053. }
  6054. std::size_t listTestsNamesOnly( Config const& config ) {
  6055. TestSpec testSpec = config.testSpec();
  6056. if( !config.testSpec().hasFilters() )
  6057. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  6058. std::size_t matchedTests = 0;
  6059. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6060. for( auto const& testCaseInfo : matchedTestCases ) {
  6061. matchedTests++;
  6062. if( startsWith( testCaseInfo.name, '#' ) )
  6063. Catch::cout() << '"' << testCaseInfo.name << '"';
  6064. else
  6065. Catch::cout() << testCaseInfo.name;
  6066. if ( config.verbosity() >= Verbosity::High )
  6067. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  6068. Catch::cout() << std::endl;
  6069. }
  6070. return matchedTests;
  6071. }
  6072. void TagInfo::add( std::string const& spelling ) {
  6073. ++count;
  6074. spellings.insert( spelling );
  6075. }
  6076. std::string TagInfo::all() const {
  6077. std::string out;
  6078. for( auto const& spelling : spellings )
  6079. out += "[" + spelling + "]";
  6080. return out;
  6081. }
  6082. std::size_t listTags( Config const& config ) {
  6083. TestSpec testSpec = config.testSpec();
  6084. if( config.testSpec().hasFilters() )
  6085. Catch::cout() << "Tags for matching test cases:\n";
  6086. else {
  6087. Catch::cout() << "All available tags:\n";
  6088. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  6089. }
  6090. std::map<std::string, TagInfo> tagCounts;
  6091. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6092. for( auto const& testCase : matchedTestCases ) {
  6093. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  6094. std::string lcaseTagName = toLower( tagName );
  6095. auto countIt = tagCounts.find( lcaseTagName );
  6096. if( countIt == tagCounts.end() )
  6097. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  6098. countIt->second.add( tagName );
  6099. }
  6100. }
  6101. for( auto const& tagCount : tagCounts ) {
  6102. ReusableStringStream rss;
  6103. rss << " " << std::setw(2) << tagCount.second.count << " ";
  6104. auto str = rss.str();
  6105. auto wrapper = Column( tagCount.second.all() )
  6106. .initialIndent( 0 )
  6107. .indent( str.size() )
  6108. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  6109. Catch::cout() << str << wrapper << '\n';
  6110. }
  6111. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  6112. return tagCounts.size();
  6113. }
  6114. std::size_t listReporters( Config const& /*config*/ ) {
  6115. Catch::cout() << "Available reporters:\n";
  6116. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  6117. std::size_t maxNameLen = 0;
  6118. for( auto const& factoryKvp : factories )
  6119. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  6120. for( auto const& factoryKvp : factories ) {
  6121. Catch::cout()
  6122. << Column( factoryKvp.first + ":" )
  6123. .indent(2)
  6124. .width( 5+maxNameLen )
  6125. + Column( factoryKvp.second->getDescription() )
  6126. .initialIndent(0)
  6127. .indent(2)
  6128. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  6129. << "\n";
  6130. }
  6131. Catch::cout() << std::endl;
  6132. return factories.size();
  6133. }
  6134. Option<std::size_t> list( Config const& config ) {
  6135. Option<std::size_t> listedCount;
  6136. if( config.listTests() )
  6137. listedCount = listedCount.valueOr(0) + listTests( config );
  6138. if( config.listTestNamesOnly() )
  6139. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
  6140. if( config.listTags() )
  6141. listedCount = listedCount.valueOr(0) + listTags( config );
  6142. if( config.listReporters() )
  6143. listedCount = listedCount.valueOr(0) + listReporters( config );
  6144. return listedCount;
  6145. }
  6146. } // end namespace Catch
  6147. // end catch_list.cpp
  6148. // start catch_matchers.cpp
  6149. namespace Catch {
  6150. namespace Matchers {
  6151. namespace Impl {
  6152. std::string MatcherUntypedBase::toString() const {
  6153. if( m_cachedToString.empty() )
  6154. m_cachedToString = describe();
  6155. return m_cachedToString;
  6156. }
  6157. MatcherUntypedBase::~MatcherUntypedBase() = default;
  6158. } // namespace Impl
  6159. } // namespace Matchers
  6160. using namespace Matchers;
  6161. using Matchers::Impl::MatcherBase;
  6162. } // namespace Catch
  6163. // end catch_matchers.cpp
  6164. // start catch_matchers_floating.cpp
  6165. #include <cstdlib>
  6166. #include <cstdint>
  6167. #include <cstring>
  6168. #include <stdexcept>
  6169. namespace Catch {
  6170. namespace Matchers {
  6171. namespace Floating {
  6172. enum class FloatingPointKind : uint8_t {
  6173. Float,
  6174. Double
  6175. };
  6176. }
  6177. }
  6178. }
  6179. namespace {
  6180. template <typename T>
  6181. struct Converter;
  6182. template <>
  6183. struct Converter<float> {
  6184. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  6185. Converter(float f) {
  6186. std::memcpy(&i, &f, sizeof(f));
  6187. }
  6188. int32_t i;
  6189. };
  6190. template <>
  6191. struct Converter<double> {
  6192. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  6193. Converter(double d) {
  6194. std::memcpy(&i, &d, sizeof(d));
  6195. }
  6196. int64_t i;
  6197. };
  6198. template <typename T>
  6199. auto convert(T t) -> Converter<T> {
  6200. return Converter<T>(t);
  6201. }
  6202. template <typename FP>
  6203. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  6204. // Comparison with NaN should always be false.
  6205. // This way we can rule it out before getting into the ugly details
  6206. if (std::isnan(lhs) || std::isnan(rhs)) {
  6207. return false;
  6208. }
  6209. auto lc = convert(lhs);
  6210. auto rc = convert(rhs);
  6211. if ((lc.i < 0) != (rc.i < 0)) {
  6212. // Potentially we can have +0 and -0
  6213. return lhs == rhs;
  6214. }
  6215. auto ulpDiff = std::abs(lc.i - rc.i);
  6216. return ulpDiff <= maxUlpDiff;
  6217. }
  6218. }
  6219. namespace Catch {
  6220. namespace Matchers {
  6221. namespace Floating {
  6222. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  6223. :m_target{ target }, m_margin{ margin } {
  6224. if (m_margin < 0) {
  6225. throw std::domain_error("Allowed margin difference has to be >= 0");
  6226. }
  6227. }
  6228. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6229. // But without the subtraction to allow for INFINITY in comparison
  6230. bool WithinAbsMatcher::match(double const& matchee) const {
  6231. return (matchee + m_margin >= m_target) && (m_target + m_margin >= m_margin);
  6232. }
  6233. std::string WithinAbsMatcher::describe() const {
  6234. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  6235. }
  6236. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  6237. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  6238. if (m_ulps < 0) {
  6239. throw std::domain_error("Allowed ulp difference has to be >= 0");
  6240. }
  6241. }
  6242. bool WithinUlpsMatcher::match(double const& matchee) const {
  6243. switch (m_type) {
  6244. case FloatingPointKind::Float:
  6245. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  6246. case FloatingPointKind::Double:
  6247. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  6248. default:
  6249. throw std::domain_error("Unknown FloatingPointKind value");
  6250. }
  6251. }
  6252. std::string WithinUlpsMatcher::describe() const {
  6253. return "is within " + std::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  6254. }
  6255. }// namespace Floating
  6256. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  6257. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  6258. }
  6259. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  6260. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  6261. }
  6262. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  6263. return Floating::WithinAbsMatcher(target, margin);
  6264. }
  6265. } // namespace Matchers
  6266. } // namespace Catch
  6267. // end catch_matchers_floating.cpp
  6268. // start catch_matchers_string.cpp
  6269. #include <regex>
  6270. namespace Catch {
  6271. namespace Matchers {
  6272. namespace StdString {
  6273. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  6274. : m_caseSensitivity( caseSensitivity ),
  6275. m_str( adjustString( str ) )
  6276. {}
  6277. std::string CasedString::adjustString( std::string const& str ) const {
  6278. return m_caseSensitivity == CaseSensitive::No
  6279. ? toLower( str )
  6280. : str;
  6281. }
  6282. std::string CasedString::caseSensitivitySuffix() const {
  6283. return m_caseSensitivity == CaseSensitive::No
  6284. ? " (case insensitive)"
  6285. : std::string();
  6286. }
  6287. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  6288. : m_comparator( comparator ),
  6289. m_operation( operation ) {
  6290. }
  6291. std::string StringMatcherBase::describe() const {
  6292. std::string description;
  6293. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  6294. m_comparator.caseSensitivitySuffix().size());
  6295. description += m_operation;
  6296. description += ": \"";
  6297. description += m_comparator.m_str;
  6298. description += "\"";
  6299. description += m_comparator.caseSensitivitySuffix();
  6300. return description;
  6301. }
  6302. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  6303. bool EqualsMatcher::match( std::string const& source ) const {
  6304. return m_comparator.adjustString( source ) == m_comparator.m_str;
  6305. }
  6306. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  6307. bool ContainsMatcher::match( std::string const& source ) const {
  6308. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  6309. }
  6310. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  6311. bool StartsWithMatcher::match( std::string const& source ) const {
  6312. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6313. }
  6314. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  6315. bool EndsWithMatcher::match( std::string const& source ) const {
  6316. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6317. }
  6318. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  6319. bool RegexMatcher::match(std::string const& matchee) const {
  6320. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  6321. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  6322. flags |= std::regex::icase;
  6323. }
  6324. auto reg = std::regex(m_regex, flags);
  6325. return std::regex_match(matchee, reg);
  6326. }
  6327. std::string RegexMatcher::describe() const {
  6328. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  6329. }
  6330. } // namespace StdString
  6331. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6332. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  6333. }
  6334. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6335. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  6336. }
  6337. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6338. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  6339. }
  6340. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6341. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  6342. }
  6343. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  6344. return StdString::RegexMatcher(regex, caseSensitivity);
  6345. }
  6346. } // namespace Matchers
  6347. } // namespace Catch
  6348. // end catch_matchers_string.cpp
  6349. // start catch_message.cpp
  6350. namespace Catch {
  6351. MessageInfo::MessageInfo( std::string const& _macroName,
  6352. SourceLineInfo const& _lineInfo,
  6353. ResultWas::OfType _type )
  6354. : macroName( _macroName ),
  6355. lineInfo( _lineInfo ),
  6356. type( _type ),
  6357. sequence( ++globalCount )
  6358. {}
  6359. bool MessageInfo::operator==( MessageInfo const& other ) const {
  6360. return sequence == other.sequence;
  6361. }
  6362. bool MessageInfo::operator<( MessageInfo const& other ) const {
  6363. return sequence < other.sequence;
  6364. }
  6365. // This may need protecting if threading support is added
  6366. unsigned int MessageInfo::globalCount = 0;
  6367. ////////////////////////////////////////////////////////////////////////////
  6368. Catch::MessageBuilder::MessageBuilder( std::string const& macroName,
  6369. SourceLineInfo const& lineInfo,
  6370. ResultWas::OfType type )
  6371. :m_info(macroName, lineInfo, type) {}
  6372. ////////////////////////////////////////////////////////////////////////////
  6373. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  6374. : m_info( builder.m_info )
  6375. {
  6376. m_info.message = builder.m_stream.str();
  6377. getResultCapture().pushScopedMessage( m_info );
  6378. }
  6379. #if defined(_MSC_VER)
  6380. #pragma warning(push)
  6381. #pragma warning(disable:4996) // std::uncaught_exception is deprecated in C++17
  6382. #endif
  6383. ScopedMessage::~ScopedMessage() {
  6384. if ( !std::uncaught_exception() ){
  6385. getResultCapture().popScopedMessage(m_info);
  6386. }
  6387. }
  6388. #if defined(_MSC_VER)
  6389. #pragma warning(pop)
  6390. #endif
  6391. } // end namespace Catch
  6392. // end catch_message.cpp
  6393. // start catch_random_number_generator.cpp
  6394. // start catch_random_number_generator.h
  6395. #include <algorithm>
  6396. namespace Catch {
  6397. struct IConfig;
  6398. void seedRng( IConfig const& config );
  6399. unsigned int rngSeed();
  6400. struct RandomNumberGenerator {
  6401. using result_type = unsigned int;
  6402. static constexpr result_type (min)() { return 0; }
  6403. static constexpr result_type (max)() { return 1000000; }
  6404. result_type operator()( result_type n ) const;
  6405. result_type operator()() const;
  6406. template<typename V>
  6407. static void shuffle( V& vector ) {
  6408. RandomNumberGenerator rng;
  6409. std::shuffle( vector.begin(), vector.end(), rng );
  6410. }
  6411. };
  6412. }
  6413. // end catch_random_number_generator.h
  6414. #include <cstdlib>
  6415. namespace Catch {
  6416. void seedRng( IConfig const& config ) {
  6417. if( config.rngSeed() != 0 )
  6418. std::srand( config.rngSeed() );
  6419. }
  6420. unsigned int rngSeed() {
  6421. return getCurrentContext().getConfig()->rngSeed();
  6422. }
  6423. RandomNumberGenerator::result_type RandomNumberGenerator::operator()( result_type n ) const {
  6424. return std::rand() % n;
  6425. }
  6426. RandomNumberGenerator::result_type RandomNumberGenerator::operator()() const {
  6427. return std::rand() % (max)();
  6428. }
  6429. }
  6430. // end catch_random_number_generator.cpp
  6431. // start catch_registry_hub.cpp
  6432. // start catch_test_case_registry_impl.h
  6433. #include <vector>
  6434. #include <set>
  6435. #include <algorithm>
  6436. #include <ios>
  6437. namespace Catch {
  6438. class TestCase;
  6439. struct IConfig;
  6440. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  6441. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  6442. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  6443. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  6444. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  6445. class TestRegistry : public ITestCaseRegistry {
  6446. public:
  6447. virtual ~TestRegistry() = default;
  6448. virtual void registerTest( TestCase const& testCase );
  6449. std::vector<TestCase> const& getAllTests() const override;
  6450. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  6451. private:
  6452. std::vector<TestCase> m_functions;
  6453. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  6454. mutable std::vector<TestCase> m_sortedFunctions;
  6455. std::size_t m_unnamedCount = 0;
  6456. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  6457. };
  6458. ///////////////////////////////////////////////////////////////////////////
  6459. class TestInvokerAsFunction : public ITestInvoker {
  6460. void(*m_testAsFunction)();
  6461. public:
  6462. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  6463. void invoke() const override;
  6464. };
  6465. std::string extractClassName( std::string const& classOrQualifiedMethodName );
  6466. ///////////////////////////////////////////////////////////////////////////
  6467. } // end namespace Catch
  6468. // end catch_test_case_registry_impl.h
  6469. // start catch_reporter_registry.h
  6470. #include <map>
  6471. namespace Catch {
  6472. class ReporterRegistry : public IReporterRegistry {
  6473. public:
  6474. ~ReporterRegistry() override;
  6475. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  6476. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  6477. void registerListener( IReporterFactoryPtr const& factory );
  6478. FactoryMap const& getFactories() const override;
  6479. Listeners const& getListeners() const override;
  6480. private:
  6481. FactoryMap m_factories;
  6482. Listeners m_listeners;
  6483. };
  6484. }
  6485. // end catch_reporter_registry.h
  6486. // start catch_tag_alias_registry.h
  6487. // start catch_tag_alias.h
  6488. #include <string>
  6489. namespace Catch {
  6490. struct TagAlias {
  6491. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  6492. std::string tag;
  6493. SourceLineInfo lineInfo;
  6494. };
  6495. } // end namespace Catch
  6496. // end catch_tag_alias.h
  6497. #include <map>
  6498. namespace Catch {
  6499. class TagAliasRegistry : public ITagAliasRegistry {
  6500. public:
  6501. ~TagAliasRegistry() override;
  6502. TagAlias const* find( std::string const& alias ) const override;
  6503. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  6504. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  6505. private:
  6506. std::map<std::string, TagAlias> m_registry;
  6507. };
  6508. } // end namespace Catch
  6509. // end catch_tag_alias_registry.h
  6510. // start catch_startup_exception_registry.h
  6511. #include <vector>
  6512. #include <exception>
  6513. namespace Catch {
  6514. class StartupExceptionRegistry {
  6515. public:
  6516. void add(std::exception_ptr const& exception) noexcept;
  6517. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  6518. private:
  6519. std::vector<std::exception_ptr> m_exceptions;
  6520. };
  6521. } // end namespace Catch
  6522. // end catch_startup_exception_registry.h
  6523. namespace Catch {
  6524. namespace {
  6525. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  6526. private NonCopyable {
  6527. public: // IRegistryHub
  6528. RegistryHub() = default;
  6529. IReporterRegistry const& getReporterRegistry() const override {
  6530. return m_reporterRegistry;
  6531. }
  6532. ITestCaseRegistry const& getTestCaseRegistry() const override {
  6533. return m_testCaseRegistry;
  6534. }
  6535. IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() override {
  6536. return m_exceptionTranslatorRegistry;
  6537. }
  6538. ITagAliasRegistry const& getTagAliasRegistry() const override {
  6539. return m_tagAliasRegistry;
  6540. }
  6541. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  6542. return m_exceptionRegistry;
  6543. }
  6544. public: // IMutableRegistryHub
  6545. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  6546. m_reporterRegistry.registerReporter( name, factory );
  6547. }
  6548. void registerListener( IReporterFactoryPtr const& factory ) override {
  6549. m_reporterRegistry.registerListener( factory );
  6550. }
  6551. void registerTest( TestCase const& testInfo ) override {
  6552. m_testCaseRegistry.registerTest( testInfo );
  6553. }
  6554. void registerTranslator( const IExceptionTranslator* translator ) override {
  6555. m_exceptionTranslatorRegistry.registerTranslator( translator );
  6556. }
  6557. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  6558. m_tagAliasRegistry.add( alias, tag, lineInfo );
  6559. }
  6560. void registerStartupException() noexcept override {
  6561. m_exceptionRegistry.add(std::current_exception());
  6562. }
  6563. private:
  6564. TestRegistry m_testCaseRegistry;
  6565. ReporterRegistry m_reporterRegistry;
  6566. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  6567. TagAliasRegistry m_tagAliasRegistry;
  6568. StartupExceptionRegistry m_exceptionRegistry;
  6569. };
  6570. // Single, global, instance
  6571. RegistryHub*& getTheRegistryHub() {
  6572. static RegistryHub* theRegistryHub = nullptr;
  6573. if( !theRegistryHub )
  6574. theRegistryHub = new RegistryHub();
  6575. return theRegistryHub;
  6576. }
  6577. }
  6578. IRegistryHub& getRegistryHub() {
  6579. return *getTheRegistryHub();
  6580. }
  6581. IMutableRegistryHub& getMutableRegistryHub() {
  6582. return *getTheRegistryHub();
  6583. }
  6584. void cleanUp() {
  6585. delete getTheRegistryHub();
  6586. getTheRegistryHub() = nullptr;
  6587. cleanUpContext();
  6588. ReusableStringStream::cleanup();
  6589. }
  6590. std::string translateActiveException() {
  6591. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  6592. }
  6593. } // end namespace Catch
  6594. // end catch_registry_hub.cpp
  6595. // start catch_reporter_registry.cpp
  6596. namespace Catch {
  6597. ReporterRegistry::~ReporterRegistry() = default;
  6598. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  6599. auto it = m_factories.find( name );
  6600. if( it == m_factories.end() )
  6601. return nullptr;
  6602. return it->second->create( ReporterConfig( config ) );
  6603. }
  6604. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  6605. m_factories.emplace(name, factory);
  6606. }
  6607. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  6608. m_listeners.push_back( factory );
  6609. }
  6610. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  6611. return m_factories;
  6612. }
  6613. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  6614. return m_listeners;
  6615. }
  6616. }
  6617. // end catch_reporter_registry.cpp
  6618. // start catch_result_type.cpp
  6619. namespace Catch {
  6620. bool isOk( ResultWas::OfType resultType ) {
  6621. return ( resultType & ResultWas::FailureBit ) == 0;
  6622. }
  6623. bool isJustInfo( int flags ) {
  6624. return flags == ResultWas::Info;
  6625. }
  6626. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  6627. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  6628. }
  6629. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  6630. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  6631. } // end namespace Catch
  6632. // end catch_result_type.cpp
  6633. // start catch_run_context.cpp
  6634. #include <cassert>
  6635. #include <algorithm>
  6636. #include <sstream>
  6637. namespace Catch {
  6638. class RedirectedStream {
  6639. std::ostream& m_originalStream;
  6640. std::ostream& m_redirectionStream;
  6641. std::streambuf* m_prevBuf;
  6642. public:
  6643. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  6644. : m_originalStream( originalStream ),
  6645. m_redirectionStream( redirectionStream ),
  6646. m_prevBuf( m_originalStream.rdbuf() )
  6647. {
  6648. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  6649. }
  6650. ~RedirectedStream() {
  6651. m_originalStream.rdbuf( m_prevBuf );
  6652. }
  6653. };
  6654. class RedirectedStdOut {
  6655. ReusableStringStream m_rss;
  6656. RedirectedStream m_cout;
  6657. public:
  6658. RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  6659. auto str() const -> std::string { return m_rss.str(); }
  6660. };
  6661. // StdErr has two constituent streams in C++, std::cerr and std::clog
  6662. // This means that we need to redirect 2 streams into 1 to keep proper
  6663. // order of writes
  6664. class RedirectedStdErr {
  6665. ReusableStringStream m_rss;
  6666. RedirectedStream m_cerr;
  6667. RedirectedStream m_clog;
  6668. public:
  6669. RedirectedStdErr()
  6670. : m_cerr( Catch::cerr(), m_rss.get() ),
  6671. m_clog( Catch::clog(), m_rss.get() )
  6672. {}
  6673. auto str() const -> std::string { return m_rss.str(); }
  6674. };
  6675. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  6676. : m_runInfo(_config->name()),
  6677. m_context(getCurrentMutableContext()),
  6678. m_config(_config),
  6679. m_reporter(std::move(reporter)),
  6680. m_lastAssertionInfo{ "", SourceLineInfo("",0), "", ResultDisposition::Normal },
  6681. m_includeSuccessfulResults( m_config->includeSuccessfulResults() )
  6682. {
  6683. m_context.setRunner(this);
  6684. m_context.setConfig(m_config);
  6685. m_context.setResultCapture(this);
  6686. m_reporter->testRunStarting(m_runInfo);
  6687. }
  6688. RunContext::~RunContext() {
  6689. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  6690. }
  6691. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  6692. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  6693. }
  6694. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  6695. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  6696. }
  6697. Totals RunContext::runTest(TestCase const& testCase) {
  6698. Totals prevTotals = m_totals;
  6699. std::string redirectedCout;
  6700. std::string redirectedCerr;
  6701. TestCaseInfo testInfo = testCase.getTestCaseInfo();
  6702. m_reporter->testCaseStarting(testInfo);
  6703. m_activeTestCase = &testCase;
  6704. ITracker& rootTracker = m_trackerContext.startRun();
  6705. assert(rootTracker.isSectionTracker());
  6706. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  6707. do {
  6708. m_trackerContext.startCycle();
  6709. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  6710. runCurrentTest(redirectedCout, redirectedCerr);
  6711. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  6712. Totals deltaTotals = m_totals.delta(prevTotals);
  6713. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  6714. deltaTotals.assertions.failed++;
  6715. deltaTotals.testCases.passed--;
  6716. deltaTotals.testCases.failed++;
  6717. }
  6718. m_totals.testCases += deltaTotals.testCases;
  6719. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  6720. deltaTotals,
  6721. redirectedCout,
  6722. redirectedCerr,
  6723. aborting()));
  6724. m_activeTestCase = nullptr;
  6725. m_testCaseTracker = nullptr;
  6726. return deltaTotals;
  6727. }
  6728. IConfigPtr RunContext::config() const {
  6729. return m_config;
  6730. }
  6731. IStreamingReporter& RunContext::reporter() const {
  6732. return *m_reporter;
  6733. }
  6734. void RunContext::assertionEnded(AssertionResult const & result) {
  6735. if (result.getResultType() == ResultWas::Ok) {
  6736. m_totals.assertions.passed++;
  6737. m_lastAssertionPassed = true;
  6738. } else if (!result.isOk()) {
  6739. m_lastAssertionPassed = false;
  6740. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  6741. m_totals.assertions.failedButOk++;
  6742. else
  6743. m_totals.assertions.failed++;
  6744. }
  6745. else {
  6746. m_lastAssertionPassed = true;
  6747. }
  6748. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  6749. // and should be let to clear themselves out.
  6750. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  6751. // Reset working state
  6752. resetAssertionInfo();
  6753. m_lastResult = result;
  6754. }
  6755. void RunContext::resetAssertionInfo() {
  6756. m_lastAssertionInfo.macroName = StringRef();
  6757. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  6758. }
  6759. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  6760. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  6761. if (!sectionTracker.isOpen())
  6762. return false;
  6763. m_activeSections.push_back(&sectionTracker);
  6764. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  6765. m_reporter->sectionStarting(sectionInfo);
  6766. assertions = m_totals.assertions;
  6767. return true;
  6768. }
  6769. bool RunContext::testForMissingAssertions(Counts& assertions) {
  6770. if (assertions.total() != 0)
  6771. return false;
  6772. if (!m_config->warnAboutMissingAssertions())
  6773. return false;
  6774. if (m_trackerContext.currentTracker().hasChildren())
  6775. return false;
  6776. m_totals.assertions.failed++;
  6777. assertions.failed++;
  6778. return true;
  6779. }
  6780. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  6781. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  6782. bool missingAssertions = testForMissingAssertions(assertions);
  6783. if (!m_activeSections.empty()) {
  6784. m_activeSections.back()->close();
  6785. m_activeSections.pop_back();
  6786. }
  6787. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  6788. m_messages.clear();
  6789. }
  6790. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  6791. if (m_unfinishedSections.empty())
  6792. m_activeSections.back()->fail();
  6793. else
  6794. m_activeSections.back()->close();
  6795. m_activeSections.pop_back();
  6796. m_unfinishedSections.push_back(endInfo);
  6797. }
  6798. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  6799. m_reporter->benchmarkStarting( info );
  6800. }
  6801. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  6802. m_reporter->benchmarkEnded( stats );
  6803. }
  6804. void RunContext::pushScopedMessage(MessageInfo const & message) {
  6805. m_messages.push_back(message);
  6806. }
  6807. void RunContext::popScopedMessage(MessageInfo const & message) {
  6808. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  6809. }
  6810. std::string RunContext::getCurrentTestName() const {
  6811. return m_activeTestCase
  6812. ? m_activeTestCase->getTestCaseInfo().name
  6813. : std::string();
  6814. }
  6815. const AssertionResult * RunContext::getLastResult() const {
  6816. return &(*m_lastResult);
  6817. }
  6818. void RunContext::exceptionEarlyReported() {
  6819. m_shouldReportUnexpected = false;
  6820. }
  6821. void RunContext::handleFatalErrorCondition( StringRef message ) {
  6822. // First notify reporter that bad things happened
  6823. m_reporter->fatalErrorEncountered(message);
  6824. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  6825. // Instead, fake a result data.
  6826. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  6827. tempResult.message = message;
  6828. AssertionResult result(m_lastAssertionInfo, tempResult);
  6829. assertionEnded(result);
  6830. handleUnfinishedSections();
  6831. // Recreate section for test case (as we will lose the one that was in scope)
  6832. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  6833. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  6834. Counts assertions;
  6835. assertions.failed = 1;
  6836. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  6837. m_reporter->sectionEnded(testCaseSectionStats);
  6838. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  6839. Totals deltaTotals;
  6840. deltaTotals.testCases.failed = 1;
  6841. deltaTotals.assertions.failed = 1;
  6842. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  6843. deltaTotals,
  6844. std::string(),
  6845. std::string(),
  6846. false));
  6847. m_totals.testCases.failed++;
  6848. testGroupEnded(std::string(), m_totals, 1, 1);
  6849. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  6850. }
  6851. bool RunContext::lastAssertionPassed() {
  6852. return m_lastAssertionPassed;
  6853. }
  6854. void RunContext::assertionPassed() {
  6855. m_lastAssertionPassed = true;
  6856. ++m_totals.assertions.passed;
  6857. resetAssertionInfo();
  6858. }
  6859. bool RunContext::aborting() const {
  6860. return m_totals.assertions.failed == static_cast<std::size_t>(m_config->abortAfter());
  6861. }
  6862. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  6863. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  6864. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  6865. m_reporter->sectionStarting(testCaseSection);
  6866. Counts prevAssertions = m_totals.assertions;
  6867. double duration = 0;
  6868. m_shouldReportUnexpected = true;
  6869. m_lastAssertionInfo = { "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal };
  6870. seedRng(*m_config);
  6871. Timer timer;
  6872. try {
  6873. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  6874. RedirectedStdOut redirectedStdOut;
  6875. RedirectedStdErr redirectedStdErr;
  6876. timer.start();
  6877. invokeActiveTestCase();
  6878. redirectedCout += redirectedStdOut.str();
  6879. redirectedCerr += redirectedStdErr.str();
  6880. } else {
  6881. timer.start();
  6882. invokeActiveTestCase();
  6883. }
  6884. duration = timer.getElapsedSeconds();
  6885. } catch (TestFailureException&) {
  6886. // This just means the test was aborted due to failure
  6887. } catch (...) {
  6888. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  6889. // are reported without translation at the point of origin.
  6890. if( m_shouldReportUnexpected ) {
  6891. AssertionReaction dummyReaction;
  6892. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  6893. }
  6894. }
  6895. m_testCaseTracker->close();
  6896. handleUnfinishedSections();
  6897. m_messages.clear();
  6898. Counts assertions = m_totals.assertions - prevAssertions;
  6899. bool missingAssertions = testForMissingAssertions(assertions);
  6900. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  6901. m_reporter->sectionEnded(testCaseSectionStats);
  6902. }
  6903. void RunContext::invokeActiveTestCase() {
  6904. FatalConditionHandler fatalConditionHandler; // Handle signals
  6905. m_activeTestCase->invoke();
  6906. fatalConditionHandler.reset();
  6907. }
  6908. void RunContext::handleUnfinishedSections() {
  6909. // If sections ended prematurely due to an exception we stored their
  6910. // infos here so we can tear them down outside the unwind process.
  6911. for (auto it = m_unfinishedSections.rbegin(),
  6912. itEnd = m_unfinishedSections.rend();
  6913. it != itEnd;
  6914. ++it)
  6915. sectionEnded(*it);
  6916. m_unfinishedSections.clear();
  6917. }
  6918. void RunContext::handleExpr(
  6919. AssertionInfo const& info,
  6920. ITransientExpression const& expr,
  6921. AssertionReaction& reaction
  6922. ) {
  6923. m_reporter->assertionStarting( info );
  6924. bool negated = isFalseTest( info.resultDisposition );
  6925. bool result = expr.getResult() != negated;
  6926. if( result ) {
  6927. if (!m_includeSuccessfulResults) {
  6928. assertionPassed();
  6929. }
  6930. else {
  6931. reportExpr(info, ResultWas::Ok, &expr, negated);
  6932. }
  6933. }
  6934. else {
  6935. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  6936. populateReaction( reaction );
  6937. }
  6938. }
  6939. void RunContext::reportExpr(
  6940. AssertionInfo const &info,
  6941. ResultWas::OfType resultType,
  6942. ITransientExpression const *expr,
  6943. bool negated ) {
  6944. m_lastAssertionInfo = info;
  6945. AssertionResultData data( resultType, LazyExpression( negated ) );
  6946. AssertionResult assertionResult{ info, data };
  6947. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  6948. assertionEnded( assertionResult );
  6949. }
  6950. void RunContext::handleMessage(
  6951. AssertionInfo const& info,
  6952. ResultWas::OfType resultType,
  6953. StringRef const& message,
  6954. AssertionReaction& reaction
  6955. ) {
  6956. m_reporter->assertionStarting( info );
  6957. m_lastAssertionInfo = info;
  6958. AssertionResultData data( resultType, LazyExpression( false ) );
  6959. data.message = message;
  6960. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  6961. assertionEnded( assertionResult );
  6962. if( !assertionResult.isOk() )
  6963. populateReaction( reaction );
  6964. }
  6965. void RunContext::handleUnexpectedExceptionNotThrown(
  6966. AssertionInfo const& info,
  6967. AssertionReaction& reaction
  6968. ) {
  6969. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  6970. }
  6971. void RunContext::handleUnexpectedInflightException(
  6972. AssertionInfo const& info,
  6973. std::string const& message,
  6974. AssertionReaction& reaction
  6975. ) {
  6976. m_lastAssertionInfo = info;
  6977. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  6978. data.message = message;
  6979. AssertionResult assertionResult{ info, data };
  6980. assertionEnded( assertionResult );
  6981. populateReaction( reaction );
  6982. }
  6983. void RunContext::populateReaction( AssertionReaction& reaction ) {
  6984. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  6985. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  6986. }
  6987. void RunContext::handleIncomplete(
  6988. AssertionInfo const& info
  6989. ) {
  6990. m_lastAssertionInfo = info;
  6991. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  6992. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  6993. AssertionResult assertionResult{ info, data };
  6994. assertionEnded( assertionResult );
  6995. }
  6996. void RunContext::handleNonExpr(
  6997. AssertionInfo const &info,
  6998. ResultWas::OfType resultType,
  6999. AssertionReaction &reaction
  7000. ) {
  7001. m_lastAssertionInfo = info;
  7002. AssertionResultData data( resultType, LazyExpression( false ) );
  7003. AssertionResult assertionResult{ info, data };
  7004. assertionEnded( assertionResult );
  7005. if( !assertionResult.isOk() )
  7006. populateReaction( reaction );
  7007. }
  7008. IResultCapture& getResultCapture() {
  7009. if (auto* capture = getCurrentContext().getResultCapture())
  7010. return *capture;
  7011. else
  7012. CATCH_INTERNAL_ERROR("No result capture instance");
  7013. }
  7014. }
  7015. // end catch_run_context.cpp
  7016. // start catch_section.cpp
  7017. namespace Catch {
  7018. Section::Section( SectionInfo const& info )
  7019. : m_info( info ),
  7020. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  7021. {
  7022. m_timer.start();
  7023. }
  7024. #if defined(_MSC_VER)
  7025. #pragma warning(push)
  7026. #pragma warning(disable:4996) // std::uncaught_exception is deprecated in C++17
  7027. #endif
  7028. Section::~Section() {
  7029. if( m_sectionIncluded ) {
  7030. SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() );
  7031. if( std::uncaught_exception() )
  7032. getResultCapture().sectionEndedEarly( endInfo );
  7033. else
  7034. getResultCapture().sectionEnded( endInfo );
  7035. }
  7036. }
  7037. #if defined(_MSC_VER)
  7038. #pragma warning(pop)
  7039. #endif
  7040. // This indicates whether the section should be executed or not
  7041. Section::operator bool() const {
  7042. return m_sectionIncluded;
  7043. }
  7044. } // end namespace Catch
  7045. // end catch_section.cpp
  7046. // start catch_section_info.cpp
  7047. namespace Catch {
  7048. SectionInfo::SectionInfo
  7049. ( SourceLineInfo const& _lineInfo,
  7050. std::string const& _name,
  7051. std::string const& _description )
  7052. : name( _name ),
  7053. description( _description ),
  7054. lineInfo( _lineInfo )
  7055. {}
  7056. SectionEndInfo::SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds )
  7057. : sectionInfo( _sectionInfo ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds )
  7058. {}
  7059. } // end namespace Catch
  7060. // end catch_section_info.cpp
  7061. // start catch_session.cpp
  7062. // start catch_session.h
  7063. #include <memory>
  7064. namespace Catch {
  7065. class Session : NonCopyable {
  7066. public:
  7067. Session();
  7068. ~Session() override;
  7069. void showHelp() const;
  7070. void libIdentify();
  7071. int applyCommandLine( int argc, char* argv[] );
  7072. void useConfigData( ConfigData const& configData );
  7073. int run( int argc, char* argv[] );
  7074. #if defined(WIN32) && defined(UNICODE)
  7075. int run( int argc, wchar_t* const argv[] );
  7076. #endif
  7077. int run();
  7078. clara::Parser const& cli() const;
  7079. void cli( clara::Parser const& newParser );
  7080. ConfigData& configData();
  7081. Config& config();
  7082. private:
  7083. int runInternal();
  7084. clara::Parser m_cli;
  7085. ConfigData m_configData;
  7086. std::shared_ptr<Config> m_config;
  7087. bool m_startupExceptions = false;
  7088. };
  7089. } // end namespace Catch
  7090. // end catch_session.h
  7091. // start catch_version.h
  7092. #include <iosfwd>
  7093. namespace Catch {
  7094. // Versioning information
  7095. struct Version {
  7096. Version( Version const& ) = delete;
  7097. Version& operator=( Version const& ) = delete;
  7098. Version( unsigned int _majorVersion,
  7099. unsigned int _minorVersion,
  7100. unsigned int _patchNumber,
  7101. char const * const _branchName,
  7102. unsigned int _buildNumber );
  7103. unsigned int const majorVersion;
  7104. unsigned int const minorVersion;
  7105. unsigned int const patchNumber;
  7106. // buildNumber is only used if branchName is not null
  7107. char const * const branchName;
  7108. unsigned int const buildNumber;
  7109. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  7110. };
  7111. Version const& libraryVersion();
  7112. }
  7113. // end catch_version.h
  7114. #include <cstdlib>
  7115. #include <iomanip>
  7116. namespace Catch {
  7117. namespace {
  7118. const int MaxExitCode = 255;
  7119. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  7120. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  7121. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  7122. return reporter;
  7123. }
  7124. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  7125. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  7126. #endif
  7127. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  7128. auto const& reporterNames = config->getReporterNames();
  7129. if (reporterNames.empty())
  7130. return createReporter(CATCH_CONFIG_DEFAULT_REPORTER, config);
  7131. IStreamingReporterPtr reporter;
  7132. for (auto const& name : reporterNames)
  7133. addReporter(reporter, createReporter(name, config));
  7134. return reporter;
  7135. }
  7136. #undef CATCH_CONFIG_DEFAULT_REPORTER
  7137. void addListeners(IStreamingReporterPtr& reporters, IConfigPtr const& config) {
  7138. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  7139. for (auto const& listener : listeners)
  7140. addReporter(reporters, listener->create(Catch::ReporterConfig(config)));
  7141. }
  7142. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  7143. IStreamingReporterPtr reporter = makeReporter(config);
  7144. addListeners(reporter, config);
  7145. RunContext context(config, std::move(reporter));
  7146. Totals totals;
  7147. context.testGroupStarting(config->name(), 1, 1);
  7148. TestSpec testSpec = config->testSpec();
  7149. if (!testSpec.hasFilters())
  7150. testSpec = TestSpecParser(ITagAliasRegistry::get()).parse("~[.]").testSpec(); // All not hidden tests
  7151. auto const& allTestCases = getAllTestCasesSorted(*config);
  7152. for (auto const& testCase : allTestCases) {
  7153. if (!context.aborting() && matchTest(testCase, testSpec, *config))
  7154. totals += context.runTest(testCase);
  7155. else
  7156. context.reporter().skipTest(testCase);
  7157. }
  7158. context.testGroupEnded(config->name(), totals, 1, 1);
  7159. return totals;
  7160. }
  7161. void applyFilenamesAsTags(Catch::IConfig const& config) {
  7162. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  7163. for (auto& testCase : tests) {
  7164. auto tags = testCase.tags;
  7165. std::string filename = testCase.lineInfo.file;
  7166. auto lastSlash = filename.find_last_of("\\/");
  7167. if (lastSlash != std::string::npos) {
  7168. filename.erase(0, lastSlash);
  7169. filename[0] = '#';
  7170. }
  7171. auto lastDot = filename.find_last_of('.');
  7172. if (lastDot != std::string::npos) {
  7173. filename.erase(lastDot);
  7174. }
  7175. tags.push_back(std::move(filename));
  7176. setTags(testCase, tags);
  7177. }
  7178. }
  7179. } // anon namespace
  7180. Session::Session() {
  7181. static bool alreadyInstantiated = false;
  7182. if( alreadyInstantiated ) {
  7183. try { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  7184. catch(...) { getMutableRegistryHub().registerStartupException(); }
  7185. }
  7186. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  7187. if ( !exceptions.empty() ) {
  7188. m_startupExceptions = true;
  7189. Colour colourGuard( Colour::Red );
  7190. Catch::cerr() << "Errors occured during startup!" << '\n';
  7191. // iterate over all exceptions and notify user
  7192. for ( const auto& ex_ptr : exceptions ) {
  7193. try {
  7194. std::rethrow_exception(ex_ptr);
  7195. } catch ( std::exception const& ex ) {
  7196. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  7197. }
  7198. }
  7199. }
  7200. alreadyInstantiated = true;
  7201. m_cli = makeCommandLineParser( m_configData );
  7202. }
  7203. Session::~Session() {
  7204. Catch::cleanUp();
  7205. }
  7206. void Session::showHelp() const {
  7207. Catch::cout()
  7208. << "\nCatch v" << libraryVersion() << "\n"
  7209. << m_cli << std::endl
  7210. << "For more detailed usage please see the project docs\n" << std::endl;
  7211. }
  7212. void Session::libIdentify() {
  7213. Catch::cout()
  7214. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  7215. << std::left << std::setw(16) << "category: " << "testframework\n"
  7216. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  7217. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  7218. }
  7219. int Session::applyCommandLine( int argc, char* argv[] ) {
  7220. if( m_startupExceptions )
  7221. return 1;
  7222. auto result = m_cli.parse( clara::Args( argc, argv ) );
  7223. if( !result ) {
  7224. Catch::cerr()
  7225. << Colour( Colour::Red )
  7226. << "\nError(s) in input:\n"
  7227. << Column( result.errorMessage() ).indent( 2 )
  7228. << "\n\n";
  7229. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  7230. return MaxExitCode;
  7231. }
  7232. if( m_configData.showHelp )
  7233. showHelp();
  7234. if( m_configData.libIdentify )
  7235. libIdentify();
  7236. m_config.reset();
  7237. return 0;
  7238. }
  7239. void Session::useConfigData( ConfigData const& configData ) {
  7240. m_configData = configData;
  7241. m_config.reset();
  7242. }
  7243. int Session::run( int argc, char* argv[] ) {
  7244. if( m_startupExceptions )
  7245. return 1;
  7246. int returnCode = applyCommandLine( argc, argv );
  7247. if( returnCode == 0 )
  7248. returnCode = run();
  7249. return returnCode;
  7250. }
  7251. #if defined(WIN32) && defined(UNICODE)
  7252. int Session::run( int argc, wchar_t* const argv[] ) {
  7253. char **utf8Argv = new char *[ argc ];
  7254. for ( int i = 0; i < argc; ++i ) {
  7255. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  7256. utf8Argv[ i ] = new char[ bufSize ];
  7257. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  7258. }
  7259. int returnCode = run( argc, utf8Argv );
  7260. for ( int i = 0; i < argc; ++i )
  7261. delete [] utf8Argv[ i ];
  7262. delete [] utf8Argv;
  7263. return returnCode;
  7264. }
  7265. #endif
  7266. int Session::run() {
  7267. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  7268. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  7269. static_cast<void>(std::getchar());
  7270. }
  7271. int exitCode = runInternal();
  7272. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  7273. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  7274. static_cast<void>(std::getchar());
  7275. }
  7276. return exitCode;
  7277. }
  7278. clara::Parser const& Session::cli() const {
  7279. return m_cli;
  7280. }
  7281. void Session::cli( clara::Parser const& newParser ) {
  7282. m_cli = newParser;
  7283. }
  7284. ConfigData& Session::configData() {
  7285. return m_configData;
  7286. }
  7287. Config& Session::config() {
  7288. if( !m_config )
  7289. m_config = std::make_shared<Config>( m_configData );
  7290. return *m_config;
  7291. }
  7292. int Session::runInternal() {
  7293. if( m_startupExceptions )
  7294. return 1;
  7295. if( m_configData.showHelp || m_configData.libIdentify )
  7296. return 0;
  7297. try
  7298. {
  7299. config(); // Force config to be constructed
  7300. seedRng( *m_config );
  7301. if( m_configData.filenamesAsTags )
  7302. applyFilenamesAsTags( *m_config );
  7303. // Handle list request
  7304. if( Option<std::size_t> listed = list( config() ) )
  7305. return static_cast<int>( *listed );
  7306. return (std::min)( MaxExitCode, static_cast<int>( runTests( m_config ).assertions.failed ) );
  7307. }
  7308. catch( std::exception& ex ) {
  7309. Catch::cerr() << ex.what() << std::endl;
  7310. return MaxExitCode;
  7311. }
  7312. }
  7313. } // end namespace Catch
  7314. // end catch_session.cpp
  7315. // start catch_startup_exception_registry.cpp
  7316. namespace Catch {
  7317. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  7318. try {
  7319. m_exceptions.push_back(exception);
  7320. }
  7321. catch(...) {
  7322. // If we run out of memory during start-up there's really not a lot more we can do about it
  7323. std::terminate();
  7324. }
  7325. }
  7326. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  7327. return m_exceptions;
  7328. }
  7329. } // end namespace Catch
  7330. // end catch_startup_exception_registry.cpp
  7331. // start catch_stream.cpp
  7332. #include <cstdio>
  7333. #include <iostream>
  7334. #include <fstream>
  7335. #include <sstream>
  7336. #include <vector>
  7337. #include <memory>
  7338. #if defined(__clang__)
  7339. # pragma clang diagnostic push
  7340. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7341. #endif
  7342. namespace Catch {
  7343. Catch::IStream::~IStream() = default;
  7344. namespace detail { namespace {
  7345. template<typename WriterF, std::size_t bufferSize=256>
  7346. class StreamBufImpl : public std::streambuf {
  7347. char data[bufferSize];
  7348. WriterF m_writer;
  7349. public:
  7350. StreamBufImpl() {
  7351. setp( data, data + sizeof(data) );
  7352. }
  7353. ~StreamBufImpl() noexcept {
  7354. StreamBufImpl::sync();
  7355. }
  7356. private:
  7357. int overflow( int c ) override {
  7358. sync();
  7359. if( c != EOF ) {
  7360. if( pbase() == epptr() )
  7361. m_writer( std::string( 1, static_cast<char>( c ) ) );
  7362. else
  7363. sputc( static_cast<char>( c ) );
  7364. }
  7365. return 0;
  7366. }
  7367. int sync() override {
  7368. if( pbase() != pptr() ) {
  7369. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  7370. setp( pbase(), epptr() );
  7371. }
  7372. return 0;
  7373. }
  7374. };
  7375. ///////////////////////////////////////////////////////////////////////////
  7376. struct OutputDebugWriter {
  7377. void operator()( std::string const&str ) {
  7378. writeToDebugConsole( str );
  7379. }
  7380. };
  7381. ///////////////////////////////////////////////////////////////////////////
  7382. class FileStream : public IStream {
  7383. mutable std::ofstream m_ofs;
  7384. public:
  7385. FileStream( StringRef filename ) {
  7386. m_ofs.open( filename.c_str() );
  7387. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  7388. }
  7389. ~FileStream() override = default;
  7390. public: // IStream
  7391. std::ostream& stream() const override {
  7392. return m_ofs;
  7393. }
  7394. };
  7395. ///////////////////////////////////////////////////////////////////////////
  7396. class CoutStream : public IStream {
  7397. mutable std::ostream m_os;
  7398. public:
  7399. // Store the streambuf from cout up-front because
  7400. // cout may get redirected when running tests
  7401. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  7402. ~CoutStream() override = default;
  7403. public: // IStream
  7404. std::ostream& stream() const override { return m_os; }
  7405. };
  7406. ///////////////////////////////////////////////////////////////////////////
  7407. class DebugOutStream : public IStream {
  7408. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  7409. mutable std::ostream m_os;
  7410. public:
  7411. DebugOutStream()
  7412. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  7413. m_os( m_streamBuf.get() )
  7414. {}
  7415. ~DebugOutStream() override = default;
  7416. public: // IStream
  7417. std::ostream& stream() const override { return m_os; }
  7418. };
  7419. }} // namespace anon::detail
  7420. ///////////////////////////////////////////////////////////////////////////
  7421. auto makeStream( StringRef const &filename ) -> IStream const* {
  7422. if( filename.empty() )
  7423. return new detail::CoutStream();
  7424. else if( filename[0] == '%' ) {
  7425. if( filename == "%debug" )
  7426. return new detail::DebugOutStream();
  7427. else
  7428. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  7429. }
  7430. else
  7431. return new detail::FileStream( filename );
  7432. }
  7433. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  7434. struct StringStreams {
  7435. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  7436. std::vector<std::size_t> m_unused;
  7437. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  7438. static StringStreams* s_instance;
  7439. auto add() -> std::size_t {
  7440. if( m_unused.empty() ) {
  7441. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  7442. return m_streams.size()-1;
  7443. }
  7444. else {
  7445. auto index = m_unused.back();
  7446. m_unused.pop_back();
  7447. return index;
  7448. }
  7449. }
  7450. void release( std::size_t index ) {
  7451. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  7452. m_unused.push_back(index);
  7453. }
  7454. // !TBD: put in TLS
  7455. static auto instance() -> StringStreams& {
  7456. if( !s_instance )
  7457. s_instance = new StringStreams();
  7458. return *s_instance;
  7459. }
  7460. static void cleanup() {
  7461. delete s_instance;
  7462. s_instance = nullptr;
  7463. }
  7464. };
  7465. StringStreams* StringStreams::s_instance = nullptr;
  7466. void ReusableStringStream::cleanup() {
  7467. StringStreams::cleanup();
  7468. }
  7469. ReusableStringStream::ReusableStringStream()
  7470. : m_index( StringStreams::instance().add() ),
  7471. m_oss( StringStreams::instance().m_streams[m_index].get() )
  7472. {}
  7473. ReusableStringStream::~ReusableStringStream() {
  7474. static_cast<std::ostringstream*>( m_oss )->str("");
  7475. m_oss->clear();
  7476. StringStreams::instance().release( m_index );
  7477. }
  7478. auto ReusableStringStream::str() const -> std::string {
  7479. return static_cast<std::ostringstream*>( m_oss )->str();
  7480. }
  7481. ///////////////////////////////////////////////////////////////////////////
  7482. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  7483. std::ostream& cout() { return std::cout; }
  7484. std::ostream& cerr() { return std::cerr; }
  7485. std::ostream& clog() { return std::clog; }
  7486. #endif
  7487. }
  7488. #if defined(__clang__)
  7489. # pragma clang diagnostic pop
  7490. #endif
  7491. // end catch_stream.cpp
  7492. // start catch_string_manip.cpp
  7493. #include <algorithm>
  7494. #include <ostream>
  7495. #include <cstring>
  7496. #include <cctype>
  7497. namespace Catch {
  7498. bool startsWith( std::string const& s, std::string const& prefix ) {
  7499. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  7500. }
  7501. bool startsWith( std::string const& s, char prefix ) {
  7502. return !s.empty() && s[0] == prefix;
  7503. }
  7504. bool endsWith( std::string const& s, std::string const& suffix ) {
  7505. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  7506. }
  7507. bool endsWith( std::string const& s, char suffix ) {
  7508. return !s.empty() && s[s.size()-1] == suffix;
  7509. }
  7510. bool contains( std::string const& s, std::string const& infix ) {
  7511. return s.find( infix ) != std::string::npos;
  7512. }
  7513. char toLowerCh(char c) {
  7514. return static_cast<char>( std::tolower( c ) );
  7515. }
  7516. void toLowerInPlace( std::string& s ) {
  7517. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  7518. }
  7519. std::string toLower( std::string const& s ) {
  7520. std::string lc = s;
  7521. toLowerInPlace( lc );
  7522. return lc;
  7523. }
  7524. std::string trim( std::string const& str ) {
  7525. static char const* whitespaceChars = "\n\r\t ";
  7526. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  7527. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  7528. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  7529. }
  7530. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  7531. bool replaced = false;
  7532. std::size_t i = str.find( replaceThis );
  7533. while( i != std::string::npos ) {
  7534. replaced = true;
  7535. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  7536. if( i < str.size()-withThis.size() )
  7537. i = str.find( replaceThis, i+withThis.size() );
  7538. else
  7539. i = std::string::npos;
  7540. }
  7541. return replaced;
  7542. }
  7543. pluralise::pluralise( std::size_t count, std::string const& label )
  7544. : m_count( count ),
  7545. m_label( label )
  7546. {}
  7547. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  7548. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  7549. if( pluraliser.m_count != 1 )
  7550. os << 's';
  7551. return os;
  7552. }
  7553. }
  7554. // end catch_string_manip.cpp
  7555. // start catch_stringref.cpp
  7556. #if defined(__clang__)
  7557. # pragma clang diagnostic push
  7558. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7559. #endif
  7560. #include <ostream>
  7561. #include <cstring>
  7562. namespace Catch {
  7563. StringRef::StringRef( char const* rawChars ) noexcept
  7564. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  7565. {}
  7566. StringRef::operator std::string() const {
  7567. return std::string( m_start, m_size );
  7568. }
  7569. void StringRef::swap( StringRef& other ) noexcept {
  7570. std::swap( m_start, other.m_start );
  7571. std::swap( m_size, other.m_size );
  7572. std::swap( m_data, other.m_data );
  7573. }
  7574. auto StringRef::c_str() const -> char const* {
  7575. if( isSubstring() )
  7576. const_cast<StringRef*>( this )->takeOwnership();
  7577. return m_start;
  7578. }
  7579. auto StringRef::data() const noexcept -> char const* {
  7580. return m_start;
  7581. }
  7582. auto StringRef::isOwned() const noexcept -> bool {
  7583. return m_data != nullptr;
  7584. }
  7585. auto StringRef::isSubstring() const noexcept -> bool {
  7586. return m_start[m_size] != '\0';
  7587. }
  7588. void StringRef::takeOwnership() {
  7589. if( !isOwned() ) {
  7590. m_data = new char[m_size+1];
  7591. memcpy( m_data, m_start, m_size );
  7592. m_data[m_size] = '\0';
  7593. m_start = m_data;
  7594. }
  7595. }
  7596. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  7597. if( start < m_size )
  7598. return StringRef( m_start+start, size );
  7599. else
  7600. return StringRef();
  7601. }
  7602. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  7603. return
  7604. size() == other.size() &&
  7605. (std::strncmp( m_start, other.m_start, size() ) == 0);
  7606. }
  7607. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  7608. return !operator==( other );
  7609. }
  7610. auto StringRef::operator[](size_type index) const noexcept -> char {
  7611. return m_start[index];
  7612. }
  7613. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  7614. size_type noChars = m_size;
  7615. // Make adjustments for uft encodings
  7616. for( size_type i=0; i < m_size; ++i ) {
  7617. char c = m_start[i];
  7618. if( ( c & 0b11000000 ) == 0b11000000 ) {
  7619. if( ( c & 0b11100000 ) == 0b11000000 )
  7620. noChars--;
  7621. else if( ( c & 0b11110000 ) == 0b11100000 )
  7622. noChars-=2;
  7623. else if( ( c & 0b11111000 ) == 0b11110000 )
  7624. noChars-=3;
  7625. }
  7626. }
  7627. return noChars;
  7628. }
  7629. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  7630. std::string str;
  7631. str.reserve( lhs.size() + rhs.size() );
  7632. str += lhs;
  7633. str += rhs;
  7634. return str;
  7635. }
  7636. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  7637. return std::string( lhs ) + std::string( rhs );
  7638. }
  7639. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  7640. return std::string( lhs ) + std::string( rhs );
  7641. }
  7642. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  7643. return os << str.c_str();
  7644. }
  7645. } // namespace Catch
  7646. #if defined(__clang__)
  7647. # pragma clang diagnostic pop
  7648. #endif
  7649. // end catch_stringref.cpp
  7650. // start catch_tag_alias.cpp
  7651. namespace Catch {
  7652. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  7653. }
  7654. // end catch_tag_alias.cpp
  7655. // start catch_tag_alias_autoregistrar.cpp
  7656. namespace Catch {
  7657. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  7658. try {
  7659. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  7660. } catch (...) {
  7661. // Do not throw when constructing global objects, instead register the exception to be processed later
  7662. getMutableRegistryHub().registerStartupException();
  7663. }
  7664. }
  7665. }
  7666. // end catch_tag_alias_autoregistrar.cpp
  7667. // start catch_tag_alias_registry.cpp
  7668. #include <sstream>
  7669. namespace Catch {
  7670. TagAliasRegistry::~TagAliasRegistry() {}
  7671. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  7672. auto it = m_registry.find( alias );
  7673. if( it != m_registry.end() )
  7674. return &(it->second);
  7675. else
  7676. return nullptr;
  7677. }
  7678. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  7679. std::string expandedTestSpec = unexpandedTestSpec;
  7680. for( auto const& registryKvp : m_registry ) {
  7681. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  7682. if( pos != std::string::npos ) {
  7683. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  7684. registryKvp.second.tag +
  7685. expandedTestSpec.substr( pos + registryKvp.first.size() );
  7686. }
  7687. }
  7688. return expandedTestSpec;
  7689. }
  7690. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  7691. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  7692. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  7693. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  7694. "error: tag alias, '" << alias << "' already registered.\n"
  7695. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  7696. << "\tRedefined at: " << lineInfo );
  7697. }
  7698. ITagAliasRegistry::~ITagAliasRegistry() {}
  7699. ITagAliasRegistry const& ITagAliasRegistry::get() {
  7700. return getRegistryHub().getTagAliasRegistry();
  7701. }
  7702. } // end namespace Catch
  7703. // end catch_tag_alias_registry.cpp
  7704. // start catch_test_case_info.cpp
  7705. #include <cctype>
  7706. #include <exception>
  7707. #include <algorithm>
  7708. #include <sstream>
  7709. namespace Catch {
  7710. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  7711. if( startsWith( tag, '.' ) ||
  7712. tag == "!hide" )
  7713. return TestCaseInfo::IsHidden;
  7714. else if( tag == "!throws" )
  7715. return TestCaseInfo::Throws;
  7716. else if( tag == "!shouldfail" )
  7717. return TestCaseInfo::ShouldFail;
  7718. else if( tag == "!mayfail" )
  7719. return TestCaseInfo::MayFail;
  7720. else if( tag == "!nonportable" )
  7721. return TestCaseInfo::NonPortable;
  7722. else if( tag == "!benchmark" )
  7723. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  7724. else
  7725. return TestCaseInfo::None;
  7726. }
  7727. bool isReservedTag( std::string const& tag ) {
  7728. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( tag[0] );
  7729. }
  7730. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  7731. CATCH_ENFORCE( !isReservedTag(tag),
  7732. "Tag name: [" << tag << "] is not allowed.\n"
  7733. << "Tag names starting with non alpha-numeric characters are reserved\n"
  7734. << _lineInfo );
  7735. }
  7736. TestCase makeTestCase( ITestInvoker* _testCase,
  7737. std::string const& _className,
  7738. std::string const& _name,
  7739. std::string const& _descOrTags,
  7740. SourceLineInfo const& _lineInfo )
  7741. {
  7742. bool isHidden = false;
  7743. // Parse out tags
  7744. std::vector<std::string> tags;
  7745. std::string desc, tag;
  7746. bool inTag = false;
  7747. for (char c : _descOrTags) {
  7748. if( !inTag ) {
  7749. if( c == '[' )
  7750. inTag = true;
  7751. else
  7752. desc += c;
  7753. }
  7754. else {
  7755. if( c == ']' ) {
  7756. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  7757. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  7758. isHidden = true;
  7759. else if( prop == TestCaseInfo::None )
  7760. enforceNotReservedTag( tag, _lineInfo );
  7761. tags.push_back( tag );
  7762. tag.clear();
  7763. inTag = false;
  7764. }
  7765. else
  7766. tag += c;
  7767. }
  7768. }
  7769. if( isHidden ) {
  7770. tags.push_back( "." );
  7771. }
  7772. TestCaseInfo info( _name, _className, desc, tags, _lineInfo );
  7773. return TestCase( _testCase, info );
  7774. }
  7775. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  7776. std::sort(begin(tags), end(tags));
  7777. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  7778. testCaseInfo.lcaseTags.clear();
  7779. for( auto const& tag : tags ) {
  7780. std::string lcaseTag = toLower( tag );
  7781. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  7782. testCaseInfo.lcaseTags.push_back( lcaseTag );
  7783. }
  7784. testCaseInfo.tags = std::move(tags);
  7785. }
  7786. TestCaseInfo::TestCaseInfo( std::string const& _name,
  7787. std::string const& _className,
  7788. std::string const& _description,
  7789. std::vector<std::string> const& _tags,
  7790. SourceLineInfo const& _lineInfo )
  7791. : name( _name ),
  7792. className( _className ),
  7793. description( _description ),
  7794. lineInfo( _lineInfo ),
  7795. properties( None )
  7796. {
  7797. setTags( *this, _tags );
  7798. }
  7799. bool TestCaseInfo::isHidden() const {
  7800. return ( properties & IsHidden ) != 0;
  7801. }
  7802. bool TestCaseInfo::throws() const {
  7803. return ( properties & Throws ) != 0;
  7804. }
  7805. bool TestCaseInfo::okToFail() const {
  7806. return ( properties & (ShouldFail | MayFail ) ) != 0;
  7807. }
  7808. bool TestCaseInfo::expectedToFail() const {
  7809. return ( properties & (ShouldFail ) ) != 0;
  7810. }
  7811. std::string TestCaseInfo::tagsAsString() const {
  7812. std::string ret;
  7813. // '[' and ']' per tag
  7814. std::size_t full_size = 2 * tags.size();
  7815. for (const auto& tag : tags) {
  7816. full_size += tag.size();
  7817. }
  7818. ret.reserve(full_size);
  7819. for (const auto& tag : tags) {
  7820. ret.push_back('[');
  7821. ret.append(tag);
  7822. ret.push_back(']');
  7823. }
  7824. return ret;
  7825. }
  7826. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo const& info ) : TestCaseInfo( info ), test( testCase ) {}
  7827. TestCase TestCase::withName( std::string const& _newName ) const {
  7828. TestCase other( *this );
  7829. other.name = _newName;
  7830. return other;
  7831. }
  7832. void TestCase::invoke() const {
  7833. test->invoke();
  7834. }
  7835. bool TestCase::operator == ( TestCase const& other ) const {
  7836. return test.get() == other.test.get() &&
  7837. name == other.name &&
  7838. className == other.className;
  7839. }
  7840. bool TestCase::operator < ( TestCase const& other ) const {
  7841. return name < other.name;
  7842. }
  7843. TestCaseInfo const& TestCase::getTestCaseInfo() const
  7844. {
  7845. return *this;
  7846. }
  7847. } // end namespace Catch
  7848. // end catch_test_case_info.cpp
  7849. // start catch_test_case_registry_impl.cpp
  7850. #include <sstream>
  7851. namespace Catch {
  7852. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  7853. std::vector<TestCase> sorted = unsortedTestCases;
  7854. switch( config.runOrder() ) {
  7855. case RunTests::InLexicographicalOrder:
  7856. std::sort( sorted.begin(), sorted.end() );
  7857. break;
  7858. case RunTests::InRandomOrder:
  7859. seedRng( config );
  7860. RandomNumberGenerator::shuffle( sorted );
  7861. break;
  7862. case RunTests::InDeclarationOrder:
  7863. // already in declaration order
  7864. break;
  7865. }
  7866. return sorted;
  7867. }
  7868. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  7869. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  7870. }
  7871. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  7872. std::set<TestCase> seenFunctions;
  7873. for( auto const& function : functions ) {
  7874. auto prev = seenFunctions.insert( function );
  7875. CATCH_ENFORCE( prev.second,
  7876. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  7877. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  7878. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  7879. }
  7880. }
  7881. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  7882. std::vector<TestCase> filtered;
  7883. filtered.reserve( testCases.size() );
  7884. for( auto const& testCase : testCases )
  7885. if( matchTest( testCase, testSpec, config ) )
  7886. filtered.push_back( testCase );
  7887. return filtered;
  7888. }
  7889. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  7890. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  7891. }
  7892. void TestRegistry::registerTest( TestCase const& testCase ) {
  7893. std::string name = testCase.getTestCaseInfo().name;
  7894. if( name.empty() ) {
  7895. ReusableStringStream rss;
  7896. rss << "Anonymous test case " << ++m_unnamedCount;
  7897. return registerTest( testCase.withName( rss.str() ) );
  7898. }
  7899. m_functions.push_back( testCase );
  7900. }
  7901. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  7902. return m_functions;
  7903. }
  7904. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  7905. if( m_sortedFunctions.empty() )
  7906. enforceNoDuplicateTestCases( m_functions );
  7907. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  7908. m_sortedFunctions = sortTests( config, m_functions );
  7909. m_currentSortOrder = config.runOrder();
  7910. }
  7911. return m_sortedFunctions;
  7912. }
  7913. ///////////////////////////////////////////////////////////////////////////
  7914. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  7915. void TestInvokerAsFunction::invoke() const {
  7916. m_testAsFunction();
  7917. }
  7918. std::string extractClassName( std::string const& classOrQualifiedMethodName ) {
  7919. std::string className = classOrQualifiedMethodName;
  7920. if( startsWith( className, '&' ) )
  7921. {
  7922. std::size_t lastColons = className.rfind( "::" );
  7923. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  7924. if( penultimateColons == std::string::npos )
  7925. penultimateColons = 1;
  7926. className = className.substr( penultimateColons, lastColons-penultimateColons );
  7927. }
  7928. return className;
  7929. }
  7930. } // end namespace Catch
  7931. // end catch_test_case_registry_impl.cpp
  7932. // start catch_test_case_tracker.cpp
  7933. #include <algorithm>
  7934. #include <assert.h>
  7935. #include <stdexcept>
  7936. #include <memory>
  7937. #include <sstream>
  7938. #if defined(__clang__)
  7939. # pragma clang diagnostic push
  7940. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7941. #endif
  7942. namespace Catch {
  7943. namespace TestCaseTracking {
  7944. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  7945. : name( _name ),
  7946. location( _location )
  7947. {}
  7948. ITracker::~ITracker() = default;
  7949. TrackerContext& TrackerContext::instance() {
  7950. static TrackerContext s_instance;
  7951. return s_instance;
  7952. }
  7953. ITracker& TrackerContext::startRun() {
  7954. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  7955. m_currentTracker = nullptr;
  7956. m_runState = Executing;
  7957. return *m_rootTracker;
  7958. }
  7959. void TrackerContext::endRun() {
  7960. m_rootTracker.reset();
  7961. m_currentTracker = nullptr;
  7962. m_runState = NotStarted;
  7963. }
  7964. void TrackerContext::startCycle() {
  7965. m_currentTracker = m_rootTracker.get();
  7966. m_runState = Executing;
  7967. }
  7968. void TrackerContext::completeCycle() {
  7969. m_runState = CompletedCycle;
  7970. }
  7971. bool TrackerContext::completedCycle() const {
  7972. return m_runState == CompletedCycle;
  7973. }
  7974. ITracker& TrackerContext::currentTracker() {
  7975. return *m_currentTracker;
  7976. }
  7977. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  7978. m_currentTracker = tracker;
  7979. }
  7980. TrackerBase::TrackerHasName::TrackerHasName( NameAndLocation const& nameAndLocation ) : m_nameAndLocation( nameAndLocation ) {}
  7981. bool TrackerBase::TrackerHasName::operator ()( ITrackerPtr const& tracker ) const {
  7982. return
  7983. tracker->nameAndLocation().name == m_nameAndLocation.name &&
  7984. tracker->nameAndLocation().location == m_nameAndLocation.location;
  7985. }
  7986. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  7987. : m_nameAndLocation( nameAndLocation ),
  7988. m_ctx( ctx ),
  7989. m_parent( parent )
  7990. {}
  7991. NameAndLocation const& TrackerBase::nameAndLocation() const {
  7992. return m_nameAndLocation;
  7993. }
  7994. bool TrackerBase::isComplete() const {
  7995. return m_runState == CompletedSuccessfully || m_runState == Failed;
  7996. }
  7997. bool TrackerBase::isSuccessfullyCompleted() const {
  7998. return m_runState == CompletedSuccessfully;
  7999. }
  8000. bool TrackerBase::isOpen() const {
  8001. return m_runState != NotStarted && !isComplete();
  8002. }
  8003. bool TrackerBase::hasChildren() const {
  8004. return !m_children.empty();
  8005. }
  8006. void TrackerBase::addChild( ITrackerPtr const& child ) {
  8007. m_children.push_back( child );
  8008. }
  8009. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  8010. auto it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( nameAndLocation ) );
  8011. return( it != m_children.end() )
  8012. ? *it
  8013. : nullptr;
  8014. }
  8015. ITracker& TrackerBase::parent() {
  8016. assert( m_parent ); // Should always be non-null except for root
  8017. return *m_parent;
  8018. }
  8019. void TrackerBase::openChild() {
  8020. if( m_runState != ExecutingChildren ) {
  8021. m_runState = ExecutingChildren;
  8022. if( m_parent )
  8023. m_parent->openChild();
  8024. }
  8025. }
  8026. bool TrackerBase::isSectionTracker() const { return false; }
  8027. bool TrackerBase::isIndexTracker() const { return false; }
  8028. void TrackerBase::open() {
  8029. m_runState = Executing;
  8030. moveToThis();
  8031. if( m_parent )
  8032. m_parent->openChild();
  8033. }
  8034. void TrackerBase::close() {
  8035. // Close any still open children (e.g. generators)
  8036. while( &m_ctx.currentTracker() != this )
  8037. m_ctx.currentTracker().close();
  8038. switch( m_runState ) {
  8039. case NeedsAnotherRun:
  8040. break;
  8041. case Executing:
  8042. m_runState = CompletedSuccessfully;
  8043. break;
  8044. case ExecutingChildren:
  8045. if( m_children.empty() || m_children.back()->isComplete() )
  8046. m_runState = CompletedSuccessfully;
  8047. break;
  8048. case NotStarted:
  8049. case CompletedSuccessfully:
  8050. case Failed:
  8051. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  8052. default:
  8053. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  8054. }
  8055. moveToParent();
  8056. m_ctx.completeCycle();
  8057. }
  8058. void TrackerBase::fail() {
  8059. m_runState = Failed;
  8060. if( m_parent )
  8061. m_parent->markAsNeedingAnotherRun();
  8062. moveToParent();
  8063. m_ctx.completeCycle();
  8064. }
  8065. void TrackerBase::markAsNeedingAnotherRun() {
  8066. m_runState = NeedsAnotherRun;
  8067. }
  8068. void TrackerBase::moveToParent() {
  8069. assert( m_parent );
  8070. m_ctx.setCurrentTracker( m_parent );
  8071. }
  8072. void TrackerBase::moveToThis() {
  8073. m_ctx.setCurrentTracker( this );
  8074. }
  8075. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8076. : TrackerBase( nameAndLocation, ctx, parent )
  8077. {
  8078. if( parent ) {
  8079. while( !parent->isSectionTracker() )
  8080. parent = &parent->parent();
  8081. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  8082. addNextFilters( parentSection.m_filters );
  8083. }
  8084. }
  8085. bool SectionTracker::isSectionTracker() const { return true; }
  8086. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  8087. std::shared_ptr<SectionTracker> section;
  8088. ITracker& currentTracker = ctx.currentTracker();
  8089. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8090. assert( childTracker );
  8091. assert( childTracker->isSectionTracker() );
  8092. section = std::static_pointer_cast<SectionTracker>( childTracker );
  8093. }
  8094. else {
  8095. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  8096. currentTracker.addChild( section );
  8097. }
  8098. if( !ctx.completedCycle() )
  8099. section->tryOpen();
  8100. return *section;
  8101. }
  8102. void SectionTracker::tryOpen() {
  8103. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  8104. open();
  8105. }
  8106. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  8107. if( !filters.empty() ) {
  8108. m_filters.push_back(""); // Root - should never be consulted
  8109. m_filters.push_back(""); // Test Case - not a section filter
  8110. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  8111. }
  8112. }
  8113. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  8114. if( filters.size() > 1 )
  8115. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  8116. }
  8117. IndexTracker::IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size )
  8118. : TrackerBase( nameAndLocation, ctx, parent ),
  8119. m_size( size )
  8120. {}
  8121. bool IndexTracker::isIndexTracker() const { return true; }
  8122. IndexTracker& IndexTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) {
  8123. std::shared_ptr<IndexTracker> tracker;
  8124. ITracker& currentTracker = ctx.currentTracker();
  8125. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8126. assert( childTracker );
  8127. assert( childTracker->isIndexTracker() );
  8128. tracker = std::static_pointer_cast<IndexTracker>( childTracker );
  8129. }
  8130. else {
  8131. tracker = std::make_shared<IndexTracker>( nameAndLocation, ctx, &currentTracker, size );
  8132. currentTracker.addChild( tracker );
  8133. }
  8134. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  8135. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  8136. tracker->moveNext();
  8137. tracker->open();
  8138. }
  8139. return *tracker;
  8140. }
  8141. int IndexTracker::index() const { return m_index; }
  8142. void IndexTracker::moveNext() {
  8143. m_index++;
  8144. m_children.clear();
  8145. }
  8146. void IndexTracker::close() {
  8147. TrackerBase::close();
  8148. if( m_runState == CompletedSuccessfully && m_index < m_size-1 )
  8149. m_runState = Executing;
  8150. }
  8151. } // namespace TestCaseTracking
  8152. using TestCaseTracking::ITracker;
  8153. using TestCaseTracking::TrackerContext;
  8154. using TestCaseTracking::SectionTracker;
  8155. using TestCaseTracking::IndexTracker;
  8156. } // namespace Catch
  8157. #if defined(__clang__)
  8158. # pragma clang diagnostic pop
  8159. #endif
  8160. // end catch_test_case_tracker.cpp
  8161. // start catch_test_registry.cpp
  8162. namespace Catch {
  8163. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  8164. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  8165. }
  8166. NameAndTags::NameAndTags( StringRef name_ , StringRef tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  8167. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  8168. try {
  8169. getMutableRegistryHub()
  8170. .registerTest(
  8171. makeTestCase(
  8172. invoker,
  8173. extractClassName( classOrMethod ),
  8174. nameAndTags.name,
  8175. nameAndTags.tags,
  8176. lineInfo));
  8177. } catch (...) {
  8178. // Do not throw when constructing global objects, instead register the exception to be processed later
  8179. getMutableRegistryHub().registerStartupException();
  8180. }
  8181. }
  8182. AutoReg::~AutoReg() = default;
  8183. }
  8184. // end catch_test_registry.cpp
  8185. // start catch_test_spec.cpp
  8186. #include <algorithm>
  8187. #include <string>
  8188. #include <vector>
  8189. #include <memory>
  8190. namespace Catch {
  8191. TestSpec::Pattern::~Pattern() = default;
  8192. TestSpec::NamePattern::~NamePattern() = default;
  8193. TestSpec::TagPattern::~TagPattern() = default;
  8194. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  8195. TestSpec::NamePattern::NamePattern( std::string const& name )
  8196. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  8197. {}
  8198. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  8199. return m_wildcardPattern.matches( toLower( testCase.name ) );
  8200. }
  8201. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  8202. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  8203. return std::find(begin(testCase.lcaseTags),
  8204. end(testCase.lcaseTags),
  8205. m_tag) != end(testCase.lcaseTags);
  8206. }
  8207. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  8208. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  8209. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  8210. // All patterns in a filter must match for the filter to be a match
  8211. for( auto const& pattern : m_patterns ) {
  8212. if( !pattern->matches( testCase ) )
  8213. return false;
  8214. }
  8215. return true;
  8216. }
  8217. bool TestSpec::hasFilters() const {
  8218. return !m_filters.empty();
  8219. }
  8220. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  8221. // A TestSpec matches if any filter matches
  8222. for( auto const& filter : m_filters )
  8223. if( filter.matches( testCase ) )
  8224. return true;
  8225. return false;
  8226. }
  8227. }
  8228. // end catch_test_spec.cpp
  8229. // start catch_test_spec_parser.cpp
  8230. namespace Catch {
  8231. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  8232. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  8233. m_mode = None;
  8234. m_exclusion = false;
  8235. m_start = std::string::npos;
  8236. m_arg = m_tagAliases->expandAliases( arg );
  8237. m_escapeChars.clear();
  8238. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  8239. visitChar( m_arg[m_pos] );
  8240. if( m_mode == Name )
  8241. addPattern<TestSpec::NamePattern>();
  8242. return *this;
  8243. }
  8244. TestSpec TestSpecParser::testSpec() {
  8245. addFilter();
  8246. return m_testSpec;
  8247. }
  8248. void TestSpecParser::visitChar( char c ) {
  8249. if( m_mode == None ) {
  8250. switch( c ) {
  8251. case ' ': return;
  8252. case '~': m_exclusion = true; return;
  8253. case '[': return startNewMode( Tag, ++m_pos );
  8254. case '"': return startNewMode( QuotedName, ++m_pos );
  8255. case '\\': return escape();
  8256. default: startNewMode( Name, m_pos ); break;
  8257. }
  8258. }
  8259. if( m_mode == Name ) {
  8260. if( c == ',' ) {
  8261. addPattern<TestSpec::NamePattern>();
  8262. addFilter();
  8263. }
  8264. else if( c == '[' ) {
  8265. if( subString() == "exclude:" )
  8266. m_exclusion = true;
  8267. else
  8268. addPattern<TestSpec::NamePattern>();
  8269. startNewMode( Tag, ++m_pos );
  8270. }
  8271. else if( c == '\\' )
  8272. escape();
  8273. }
  8274. else if( m_mode == EscapedName )
  8275. m_mode = Name;
  8276. else if( m_mode == QuotedName && c == '"' )
  8277. addPattern<TestSpec::NamePattern>();
  8278. else if( m_mode == Tag && c == ']' )
  8279. addPattern<TestSpec::TagPattern>();
  8280. }
  8281. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  8282. m_mode = mode;
  8283. m_start = start;
  8284. }
  8285. void TestSpecParser::escape() {
  8286. if( m_mode == None )
  8287. m_start = m_pos;
  8288. m_mode = EscapedName;
  8289. m_escapeChars.push_back( m_pos );
  8290. }
  8291. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  8292. void TestSpecParser::addFilter() {
  8293. if( !m_currentFilter.m_patterns.empty() ) {
  8294. m_testSpec.m_filters.push_back( m_currentFilter );
  8295. m_currentFilter = TestSpec::Filter();
  8296. }
  8297. }
  8298. TestSpec parseTestSpec( std::string const& arg ) {
  8299. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  8300. }
  8301. } // namespace Catch
  8302. // end catch_test_spec_parser.cpp
  8303. // start catch_timer.cpp
  8304. #include <chrono>
  8305. namespace Catch {
  8306. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  8307. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  8308. }
  8309. auto estimateClockResolution() -> uint64_t {
  8310. uint64_t sum = 0;
  8311. static const uint64_t iterations = 1000000;
  8312. for( std::size_t i = 0; i < iterations; ++i ) {
  8313. uint64_t ticks;
  8314. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  8315. do {
  8316. ticks = getCurrentNanosecondsSinceEpoch();
  8317. }
  8318. while( ticks == baseTicks );
  8319. auto delta = ticks - baseTicks;
  8320. sum += delta;
  8321. }
  8322. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  8323. // - and potentially do more iterations if there's a high variance.
  8324. return sum/iterations;
  8325. }
  8326. auto getEstimatedClockResolution() -> uint64_t {
  8327. static auto s_resolution = estimateClockResolution();
  8328. return s_resolution;
  8329. }
  8330. void Timer::start() {
  8331. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  8332. }
  8333. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  8334. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  8335. }
  8336. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  8337. return getElapsedNanoseconds()/1000;
  8338. }
  8339. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  8340. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  8341. }
  8342. auto Timer::getElapsedSeconds() const -> double {
  8343. return getElapsedMicroseconds()/1000000.0;
  8344. }
  8345. } // namespace Catch
  8346. // end catch_timer.cpp
  8347. // start catch_tostring.cpp
  8348. #if defined(__clang__)
  8349. # pragma clang diagnostic push
  8350. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8351. # pragma clang diagnostic ignored "-Wglobal-constructors"
  8352. #endif
  8353. // Enable specific decls locally
  8354. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  8355. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  8356. #endif
  8357. #include <cmath>
  8358. #include <iomanip>
  8359. namespace Catch {
  8360. namespace Detail {
  8361. const std::string unprintableString = "{?}";
  8362. namespace {
  8363. const int hexThreshold = 255;
  8364. struct Endianness {
  8365. enum Arch { Big, Little };
  8366. static Arch which() {
  8367. union _{
  8368. int asInt;
  8369. char asChar[sizeof (int)];
  8370. } u;
  8371. u.asInt = 1;
  8372. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  8373. }
  8374. };
  8375. }
  8376. std::string rawMemoryToString( const void *object, std::size_t size ) {
  8377. // Reverse order for little endian architectures
  8378. int i = 0, end = static_cast<int>( size ), inc = 1;
  8379. if( Endianness::which() == Endianness::Little ) {
  8380. i = end-1;
  8381. end = inc = -1;
  8382. }
  8383. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  8384. ReusableStringStream rss;
  8385. rss << "0x" << std::setfill('0') << std::hex;
  8386. for( ; i != end; i += inc )
  8387. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  8388. return rss.str();
  8389. }
  8390. }
  8391. template<typename T>
  8392. std::string fpToString( T value, int precision ) {
  8393. if (std::isnan(value)) {
  8394. return "nan";
  8395. }
  8396. ReusableStringStream rss;
  8397. rss << std::setprecision( precision )
  8398. << std::fixed
  8399. << value;
  8400. std::string d = rss.str();
  8401. std::size_t i = d.find_last_not_of( '0' );
  8402. if( i != std::string::npos && i != d.size()-1 ) {
  8403. if( d[i] == '.' )
  8404. i++;
  8405. d = d.substr( 0, i+1 );
  8406. }
  8407. return d;
  8408. }
  8409. //// ======================================================= ////
  8410. //
  8411. // Out-of-line defs for full specialization of StringMaker
  8412. //
  8413. //// ======================================================= ////
  8414. std::string StringMaker<std::string>::convert(const std::string& str) {
  8415. if (!getCurrentContext().getConfig()->showInvisibles()) {
  8416. return '"' + str + '"';
  8417. }
  8418. std::string s("\"");
  8419. for (char c : str) {
  8420. switch (c) {
  8421. case '\n':
  8422. s.append("\\n");
  8423. break;
  8424. case '\t':
  8425. s.append("\\t");
  8426. break;
  8427. default:
  8428. s.push_back(c);
  8429. break;
  8430. }
  8431. }
  8432. s.append("\"");
  8433. return s;
  8434. }
  8435. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  8436. std::string s;
  8437. s.reserve(wstr.size());
  8438. for (auto c : wstr) {
  8439. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  8440. }
  8441. return ::Catch::Detail::stringify(s);
  8442. }
  8443. std::string StringMaker<char const*>::convert(char const* str) {
  8444. if (str) {
  8445. return ::Catch::Detail::stringify(std::string{ str });
  8446. } else {
  8447. return{ "{null string}" };
  8448. }
  8449. }
  8450. std::string StringMaker<char*>::convert(char* str) {
  8451. if (str) {
  8452. return ::Catch::Detail::stringify(std::string{ str });
  8453. } else {
  8454. return{ "{null string}" };
  8455. }
  8456. }
  8457. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  8458. if (str) {
  8459. return ::Catch::Detail::stringify(std::wstring{ str });
  8460. } else {
  8461. return{ "{null string}" };
  8462. }
  8463. }
  8464. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  8465. if (str) {
  8466. return ::Catch::Detail::stringify(std::wstring{ str });
  8467. } else {
  8468. return{ "{null string}" };
  8469. }
  8470. }
  8471. std::string StringMaker<int>::convert(int value) {
  8472. return ::Catch::Detail::stringify(static_cast<long long>(value));
  8473. }
  8474. std::string StringMaker<long>::convert(long value) {
  8475. return ::Catch::Detail::stringify(static_cast<long long>(value));
  8476. }
  8477. std::string StringMaker<long long>::convert(long long value) {
  8478. ReusableStringStream rss;
  8479. rss << value;
  8480. if (value > Detail::hexThreshold) {
  8481. rss << " (0x" << std::hex << value << ')';
  8482. }
  8483. return rss.str();
  8484. }
  8485. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  8486. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  8487. }
  8488. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  8489. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  8490. }
  8491. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  8492. ReusableStringStream rss;
  8493. rss << value;
  8494. if (value > Detail::hexThreshold) {
  8495. rss << " (0x" << std::hex << value << ')';
  8496. }
  8497. return rss.str();
  8498. }
  8499. std::string StringMaker<bool>::convert(bool b) {
  8500. return b ? "true" : "false";
  8501. }
  8502. std::string StringMaker<char>::convert(char value) {
  8503. if (value == '\r') {
  8504. return "'\\r'";
  8505. } else if (value == '\f') {
  8506. return "'\\f'";
  8507. } else if (value == '\n') {
  8508. return "'\\n'";
  8509. } else if (value == '\t') {
  8510. return "'\\t'";
  8511. } else if ('\0' <= value && value < ' ') {
  8512. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  8513. } else {
  8514. char chstr[] = "' '";
  8515. chstr[1] = value;
  8516. return chstr;
  8517. }
  8518. }
  8519. std::string StringMaker<signed char>::convert(signed char c) {
  8520. return ::Catch::Detail::stringify(static_cast<char>(c));
  8521. }
  8522. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  8523. return ::Catch::Detail::stringify(static_cast<char>(c));
  8524. }
  8525. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  8526. return "nullptr";
  8527. }
  8528. std::string StringMaker<float>::convert(float value) {
  8529. return fpToString(value, 5) + 'f';
  8530. }
  8531. std::string StringMaker<double>::convert(double value) {
  8532. return fpToString(value, 10);
  8533. }
  8534. std::string ratio_string<std::atto>::symbol() { return "a"; }
  8535. std::string ratio_string<std::femto>::symbol() { return "f"; }
  8536. std::string ratio_string<std::pico>::symbol() { return "p"; }
  8537. std::string ratio_string<std::nano>::symbol() { return "n"; }
  8538. std::string ratio_string<std::micro>::symbol() { return "u"; }
  8539. std::string ratio_string<std::milli>::symbol() { return "m"; }
  8540. } // end namespace Catch
  8541. #if defined(__clang__)
  8542. # pragma clang diagnostic pop
  8543. #endif
  8544. // end catch_tostring.cpp
  8545. // start catch_totals.cpp
  8546. namespace Catch {
  8547. Counts Counts::operator - ( Counts const& other ) const {
  8548. Counts diff;
  8549. diff.passed = passed - other.passed;
  8550. diff.failed = failed - other.failed;
  8551. diff.failedButOk = failedButOk - other.failedButOk;
  8552. return diff;
  8553. }
  8554. Counts& Counts::operator += ( Counts const& other ) {
  8555. passed += other.passed;
  8556. failed += other.failed;
  8557. failedButOk += other.failedButOk;
  8558. return *this;
  8559. }
  8560. std::size_t Counts::total() const {
  8561. return passed + failed + failedButOk;
  8562. }
  8563. bool Counts::allPassed() const {
  8564. return failed == 0 && failedButOk == 0;
  8565. }
  8566. bool Counts::allOk() const {
  8567. return failed == 0;
  8568. }
  8569. Totals Totals::operator - ( Totals const& other ) const {
  8570. Totals diff;
  8571. diff.assertions = assertions - other.assertions;
  8572. diff.testCases = testCases - other.testCases;
  8573. return diff;
  8574. }
  8575. Totals& Totals::operator += ( Totals const& other ) {
  8576. assertions += other.assertions;
  8577. testCases += other.testCases;
  8578. return *this;
  8579. }
  8580. Totals Totals::delta( Totals const& prevTotals ) const {
  8581. Totals diff = *this - prevTotals;
  8582. if( diff.assertions.failed > 0 )
  8583. ++diff.testCases.failed;
  8584. else if( diff.assertions.failedButOk > 0 )
  8585. ++diff.testCases.failedButOk;
  8586. else
  8587. ++diff.testCases.passed;
  8588. return diff;
  8589. }
  8590. }
  8591. // end catch_totals.cpp
  8592. // start catch_version.cpp
  8593. #include <ostream>
  8594. namespace Catch {
  8595. Version::Version
  8596. ( unsigned int _majorVersion,
  8597. unsigned int _minorVersion,
  8598. unsigned int _patchNumber,
  8599. char const * const _branchName,
  8600. unsigned int _buildNumber )
  8601. : majorVersion( _majorVersion ),
  8602. minorVersion( _minorVersion ),
  8603. patchNumber( _patchNumber ),
  8604. branchName( _branchName ),
  8605. buildNumber( _buildNumber )
  8606. {}
  8607. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  8608. os << version.majorVersion << '.'
  8609. << version.minorVersion << '.'
  8610. << version.patchNumber;
  8611. // branchName is never null -> 0th char is \0 if it is empty
  8612. if (version.branchName[0]) {
  8613. os << '-' << version.branchName
  8614. << '.' << version.buildNumber;
  8615. }
  8616. return os;
  8617. }
  8618. Version const& libraryVersion() {
  8619. static Version version( 2, 1, 0, "", 0 );
  8620. return version;
  8621. }
  8622. }
  8623. // end catch_version.cpp
  8624. // start catch_wildcard_pattern.cpp
  8625. #include <sstream>
  8626. namespace Catch {
  8627. WildcardPattern::WildcardPattern( std::string const& pattern,
  8628. CaseSensitive::Choice caseSensitivity )
  8629. : m_caseSensitivity( caseSensitivity ),
  8630. m_pattern( adjustCase( pattern ) )
  8631. {
  8632. if( startsWith( m_pattern, '*' ) ) {
  8633. m_pattern = m_pattern.substr( 1 );
  8634. m_wildcard = WildcardAtStart;
  8635. }
  8636. if( endsWith( m_pattern, '*' ) ) {
  8637. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  8638. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  8639. }
  8640. }
  8641. bool WildcardPattern::matches( std::string const& str ) const {
  8642. switch( m_wildcard ) {
  8643. case NoWildcard:
  8644. return m_pattern == adjustCase( str );
  8645. case WildcardAtStart:
  8646. return endsWith( adjustCase( str ), m_pattern );
  8647. case WildcardAtEnd:
  8648. return startsWith( adjustCase( str ), m_pattern );
  8649. case WildcardAtBothEnds:
  8650. return contains( adjustCase( str ), m_pattern );
  8651. default:
  8652. CATCH_INTERNAL_ERROR( "Unknown enum" );
  8653. }
  8654. }
  8655. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  8656. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  8657. }
  8658. }
  8659. // end catch_wildcard_pattern.cpp
  8660. // start catch_xmlwriter.cpp
  8661. #include <iomanip>
  8662. namespace Catch {
  8663. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  8664. : m_str( str ),
  8665. m_forWhat( forWhat )
  8666. {}
  8667. void XmlEncode::encodeTo( std::ostream& os ) const {
  8668. // Apostrophe escaping not necessary if we always use " to write attributes
  8669. // (see: http://www.w3.org/TR/xml/#syntax)
  8670. for( std::size_t i = 0; i < m_str.size(); ++ i ) {
  8671. char c = m_str[i];
  8672. switch( c ) {
  8673. case '<': os << "&lt;"; break;
  8674. case '&': os << "&amp;"; break;
  8675. case '>':
  8676. // See: http://www.w3.org/TR/xml/#syntax
  8677. if( i > 2 && m_str[i-1] == ']' && m_str[i-2] == ']' )
  8678. os << "&gt;";
  8679. else
  8680. os << c;
  8681. break;
  8682. case '\"':
  8683. if( m_forWhat == ForAttributes )
  8684. os << "&quot;";
  8685. else
  8686. os << c;
  8687. break;
  8688. default:
  8689. // Escape control chars - based on contribution by @espenalb in PR #465 and
  8690. // by @mrpi PR #588
  8691. if ( ( c >= 0 && c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) {
  8692. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  8693. os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  8694. << static_cast<int>( c );
  8695. }
  8696. else
  8697. os << c;
  8698. }
  8699. }
  8700. }
  8701. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  8702. xmlEncode.encodeTo( os );
  8703. return os;
  8704. }
  8705. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  8706. : m_writer( writer )
  8707. {}
  8708. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  8709. : m_writer( other.m_writer ){
  8710. other.m_writer = nullptr;
  8711. }
  8712. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  8713. if ( m_writer ) {
  8714. m_writer->endElement();
  8715. }
  8716. m_writer = other.m_writer;
  8717. other.m_writer = nullptr;
  8718. return *this;
  8719. }
  8720. XmlWriter::ScopedElement::~ScopedElement() {
  8721. if( m_writer )
  8722. m_writer->endElement();
  8723. }
  8724. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  8725. m_writer->writeText( text, indent );
  8726. return *this;
  8727. }
  8728. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  8729. {
  8730. writeDeclaration();
  8731. }
  8732. XmlWriter::~XmlWriter() {
  8733. while( !m_tags.empty() )
  8734. endElement();
  8735. }
  8736. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  8737. ensureTagClosed();
  8738. newlineIfNecessary();
  8739. m_os << m_indent << '<' << name;
  8740. m_tags.push_back( name );
  8741. m_indent += " ";
  8742. m_tagIsOpen = true;
  8743. return *this;
  8744. }
  8745. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  8746. ScopedElement scoped( this );
  8747. startElement( name );
  8748. return scoped;
  8749. }
  8750. XmlWriter& XmlWriter::endElement() {
  8751. newlineIfNecessary();
  8752. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  8753. if( m_tagIsOpen ) {
  8754. m_os << "/>";
  8755. m_tagIsOpen = false;
  8756. }
  8757. else {
  8758. m_os << m_indent << "</" << m_tags.back() << ">";
  8759. }
  8760. m_os << std::endl;
  8761. m_tags.pop_back();
  8762. return *this;
  8763. }
  8764. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  8765. if( !name.empty() && !attribute.empty() )
  8766. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  8767. return *this;
  8768. }
  8769. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  8770. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  8771. return *this;
  8772. }
  8773. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  8774. if( !text.empty() ){
  8775. bool tagWasOpen = m_tagIsOpen;
  8776. ensureTagClosed();
  8777. if( tagWasOpen && indent )
  8778. m_os << m_indent;
  8779. m_os << XmlEncode( text );
  8780. m_needsNewline = true;
  8781. }
  8782. return *this;
  8783. }
  8784. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  8785. ensureTagClosed();
  8786. m_os << m_indent << "<!--" << text << "-->";
  8787. m_needsNewline = true;
  8788. return *this;
  8789. }
  8790. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  8791. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  8792. }
  8793. XmlWriter& XmlWriter::writeBlankLine() {
  8794. ensureTagClosed();
  8795. m_os << '\n';
  8796. return *this;
  8797. }
  8798. void XmlWriter::ensureTagClosed() {
  8799. if( m_tagIsOpen ) {
  8800. m_os << ">" << std::endl;
  8801. m_tagIsOpen = false;
  8802. }
  8803. }
  8804. void XmlWriter::writeDeclaration() {
  8805. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  8806. }
  8807. void XmlWriter::newlineIfNecessary() {
  8808. if( m_needsNewline ) {
  8809. m_os << std::endl;
  8810. m_needsNewline = false;
  8811. }
  8812. }
  8813. }
  8814. // end catch_xmlwriter.cpp
  8815. // start catch_reporter_bases.cpp
  8816. #include <cstring>
  8817. #include <cfloat>
  8818. #include <cstdio>
  8819. #include <assert.h>
  8820. #include <memory>
  8821. namespace Catch {
  8822. void prepareExpandedExpression(AssertionResult& result) {
  8823. result.getExpandedExpression();
  8824. }
  8825. // Because formatting using c++ streams is stateful, drop down to C is required
  8826. // Alternatively we could use stringstream, but its performance is... not good.
  8827. std::string getFormattedDuration( double duration ) {
  8828. // Max exponent + 1 is required to represent the whole part
  8829. // + 1 for decimal point
  8830. // + 3 for the 3 decimal places
  8831. // + 1 for null terminator
  8832. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  8833. char buffer[maxDoubleSize];
  8834. // Save previous errno, to prevent sprintf from overwriting it
  8835. ErrnoGuard guard;
  8836. #ifdef _MSC_VER
  8837. sprintf_s(buffer, "%.3f", duration);
  8838. #else
  8839. sprintf(buffer, "%.3f", duration);
  8840. #endif
  8841. return std::string(buffer);
  8842. }
  8843. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  8844. :StreamingReporterBase(_config) {}
  8845. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  8846. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  8847. return false;
  8848. }
  8849. } // end namespace Catch
  8850. // end catch_reporter_bases.cpp
  8851. // start catch_reporter_compact.cpp
  8852. namespace {
  8853. #ifdef CATCH_PLATFORM_MAC
  8854. const char* failedString() { return "FAILED"; }
  8855. const char* passedString() { return "PASSED"; }
  8856. #else
  8857. const char* failedString() { return "failed"; }
  8858. const char* passedString() { return "passed"; }
  8859. #endif
  8860. // Colour::LightGrey
  8861. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  8862. std::string bothOrAll( std::size_t count ) {
  8863. return count == 1 ? std::string() :
  8864. count == 2 ? "both " : "all " ;
  8865. }
  8866. } // anon namespace
  8867. namespace Catch {
  8868. namespace {
  8869. // Colour, message variants:
  8870. // - white: No tests ran.
  8871. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  8872. // - white: Passed [both/all] N test cases (no assertions).
  8873. // - red: Failed N tests cases, failed M assertions.
  8874. // - green: Passed [both/all] N tests cases with M assertions.
  8875. void printTotals(std::ostream& out, const Totals& totals) {
  8876. if (totals.testCases.total() == 0) {
  8877. out << "No tests ran.";
  8878. } else if (totals.testCases.failed == totals.testCases.total()) {
  8879. Colour colour(Colour::ResultError);
  8880. const std::string qualify_assertions_failed =
  8881. totals.assertions.failed == totals.assertions.total() ?
  8882. bothOrAll(totals.assertions.failed) : std::string();
  8883. out <<
  8884. "Failed " << bothOrAll(totals.testCases.failed)
  8885. << pluralise(totals.testCases.failed, "test case") << ", "
  8886. "failed " << qualify_assertions_failed <<
  8887. pluralise(totals.assertions.failed, "assertion") << '.';
  8888. } else if (totals.assertions.total() == 0) {
  8889. out <<
  8890. "Passed " << bothOrAll(totals.testCases.total())
  8891. << pluralise(totals.testCases.total(), "test case")
  8892. << " (no assertions).";
  8893. } else if (totals.assertions.failed) {
  8894. Colour colour(Colour::ResultError);
  8895. out <<
  8896. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  8897. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  8898. } else {
  8899. Colour colour(Colour::ResultSuccess);
  8900. out <<
  8901. "Passed " << bothOrAll(totals.testCases.passed)
  8902. << pluralise(totals.testCases.passed, "test case") <<
  8903. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  8904. }
  8905. }
  8906. // Implementation of CompactReporter formatting
  8907. class AssertionPrinter {
  8908. public:
  8909. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  8910. AssertionPrinter(AssertionPrinter const&) = delete;
  8911. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  8912. : stream(_stream)
  8913. , result(_stats.assertionResult)
  8914. , messages(_stats.infoMessages)
  8915. , itMessage(_stats.infoMessages.begin())
  8916. , printInfoMessages(_printInfoMessages) {}
  8917. void print() {
  8918. printSourceInfo();
  8919. itMessage = messages.begin();
  8920. switch (result.getResultType()) {
  8921. case ResultWas::Ok:
  8922. printResultType(Colour::ResultSuccess, passedString());
  8923. printOriginalExpression();
  8924. printReconstructedExpression();
  8925. if (!result.hasExpression())
  8926. printRemainingMessages(Colour::None);
  8927. else
  8928. printRemainingMessages();
  8929. break;
  8930. case ResultWas::ExpressionFailed:
  8931. if (result.isOk())
  8932. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  8933. else
  8934. printResultType(Colour::Error, failedString());
  8935. printOriginalExpression();
  8936. printReconstructedExpression();
  8937. printRemainingMessages();
  8938. break;
  8939. case ResultWas::ThrewException:
  8940. printResultType(Colour::Error, failedString());
  8941. printIssue("unexpected exception with message:");
  8942. printMessage();
  8943. printExpressionWas();
  8944. printRemainingMessages();
  8945. break;
  8946. case ResultWas::FatalErrorCondition:
  8947. printResultType(Colour::Error, failedString());
  8948. printIssue("fatal error condition with message:");
  8949. printMessage();
  8950. printExpressionWas();
  8951. printRemainingMessages();
  8952. break;
  8953. case ResultWas::DidntThrowException:
  8954. printResultType(Colour::Error, failedString());
  8955. printIssue("expected exception, got none");
  8956. printExpressionWas();
  8957. printRemainingMessages();
  8958. break;
  8959. case ResultWas::Info:
  8960. printResultType(Colour::None, "info");
  8961. printMessage();
  8962. printRemainingMessages();
  8963. break;
  8964. case ResultWas::Warning:
  8965. printResultType(Colour::None, "warning");
  8966. printMessage();
  8967. printRemainingMessages();
  8968. break;
  8969. case ResultWas::ExplicitFailure:
  8970. printResultType(Colour::Error, failedString());
  8971. printIssue("explicitly");
  8972. printRemainingMessages(Colour::None);
  8973. break;
  8974. // These cases are here to prevent compiler warnings
  8975. case ResultWas::Unknown:
  8976. case ResultWas::FailureBit:
  8977. case ResultWas::Exception:
  8978. printResultType(Colour::Error, "** internal error **");
  8979. break;
  8980. }
  8981. }
  8982. private:
  8983. void printSourceInfo() const {
  8984. Colour colourGuard(Colour::FileName);
  8985. stream << result.getSourceInfo() << ':';
  8986. }
  8987. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  8988. if (!passOrFail.empty()) {
  8989. {
  8990. Colour colourGuard(colour);
  8991. stream << ' ' << passOrFail;
  8992. }
  8993. stream << ':';
  8994. }
  8995. }
  8996. void printIssue(std::string const& issue) const {
  8997. stream << ' ' << issue;
  8998. }
  8999. void printExpressionWas() {
  9000. if (result.hasExpression()) {
  9001. stream << ';';
  9002. {
  9003. Colour colour(dimColour());
  9004. stream << " expression was:";
  9005. }
  9006. printOriginalExpression();
  9007. }
  9008. }
  9009. void printOriginalExpression() const {
  9010. if (result.hasExpression()) {
  9011. stream << ' ' << result.getExpression();
  9012. }
  9013. }
  9014. void printReconstructedExpression() const {
  9015. if (result.hasExpandedExpression()) {
  9016. {
  9017. Colour colour(dimColour());
  9018. stream << " for: ";
  9019. }
  9020. stream << result.getExpandedExpression();
  9021. }
  9022. }
  9023. void printMessage() {
  9024. if (itMessage != messages.end()) {
  9025. stream << " '" << itMessage->message << '\'';
  9026. ++itMessage;
  9027. }
  9028. }
  9029. void printRemainingMessages(Colour::Code colour = dimColour()) {
  9030. if (itMessage == messages.end())
  9031. return;
  9032. // using messages.end() directly yields (or auto) compilation error:
  9033. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  9034. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  9035. {
  9036. Colour colourGuard(colour);
  9037. stream << " with " << pluralise(N, "message") << ':';
  9038. }
  9039. for (; itMessage != itEnd; ) {
  9040. // If this assertion is a warning ignore any INFO messages
  9041. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  9042. stream << " '" << itMessage->message << '\'';
  9043. if (++itMessage != itEnd) {
  9044. Colour colourGuard(dimColour());
  9045. stream << " and";
  9046. }
  9047. }
  9048. }
  9049. }
  9050. private:
  9051. std::ostream& stream;
  9052. AssertionResult const& result;
  9053. std::vector<MessageInfo> messages;
  9054. std::vector<MessageInfo>::const_iterator itMessage;
  9055. bool printInfoMessages;
  9056. };
  9057. } // anon namespace
  9058. std::string CompactReporter::getDescription() {
  9059. return "Reports test results on a single line, suitable for IDEs";
  9060. }
  9061. ReporterPreferences CompactReporter::getPreferences() const {
  9062. ReporterPreferences prefs;
  9063. prefs.shouldRedirectStdOut = false;
  9064. return prefs;
  9065. }
  9066. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  9067. stream << "No test cases matched '" << spec << '\'' << std::endl;
  9068. }
  9069. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  9070. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  9071. AssertionResult const& result = _assertionStats.assertionResult;
  9072. bool printInfoMessages = true;
  9073. // Drop out if result was successful and we're not printing those
  9074. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  9075. if( result.getResultType() != ResultWas::Warning )
  9076. return false;
  9077. printInfoMessages = false;
  9078. }
  9079. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  9080. printer.print();
  9081. stream << std::endl;
  9082. return true;
  9083. }
  9084. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  9085. if (m_config->showDurations() == ShowDurations::Always) {
  9086. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  9087. }
  9088. }
  9089. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  9090. printTotals( stream, _testRunStats.totals );
  9091. stream << '\n' << std::endl;
  9092. StreamingReporterBase::testRunEnded( _testRunStats );
  9093. }
  9094. CompactReporter::~CompactReporter() {}
  9095. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  9096. } // end namespace Catch
  9097. // end catch_reporter_compact.cpp
  9098. // start catch_reporter_console.cpp
  9099. #include <cfloat>
  9100. #include <cstdio>
  9101. #if defined(_MSC_VER)
  9102. #pragma warning(push)
  9103. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  9104. // Note that 4062 (not all labels are handled
  9105. // and default is missing) is enabled
  9106. #endif
  9107. namespace Catch {
  9108. namespace {
  9109. // Formatter impl for ConsoleReporter
  9110. class ConsoleAssertionPrinter {
  9111. public:
  9112. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  9113. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  9114. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  9115. : stream(_stream),
  9116. stats(_stats),
  9117. result(_stats.assertionResult),
  9118. colour(Colour::None),
  9119. message(result.getMessage()),
  9120. messages(_stats.infoMessages),
  9121. printInfoMessages(_printInfoMessages) {
  9122. switch (result.getResultType()) {
  9123. case ResultWas::Ok:
  9124. colour = Colour::Success;
  9125. passOrFail = "PASSED";
  9126. //if( result.hasMessage() )
  9127. if (_stats.infoMessages.size() == 1)
  9128. messageLabel = "with message";
  9129. if (_stats.infoMessages.size() > 1)
  9130. messageLabel = "with messages";
  9131. break;
  9132. case ResultWas::ExpressionFailed:
  9133. if (result.isOk()) {
  9134. colour = Colour::Success;
  9135. passOrFail = "FAILED - but was ok";
  9136. } else {
  9137. colour = Colour::Error;
  9138. passOrFail = "FAILED";
  9139. }
  9140. if (_stats.infoMessages.size() == 1)
  9141. messageLabel = "with message";
  9142. if (_stats.infoMessages.size() > 1)
  9143. messageLabel = "with messages";
  9144. break;
  9145. case ResultWas::ThrewException:
  9146. colour = Colour::Error;
  9147. passOrFail = "FAILED";
  9148. messageLabel = "due to unexpected exception with ";
  9149. if (_stats.infoMessages.size() == 1)
  9150. messageLabel += "message";
  9151. if (_stats.infoMessages.size() > 1)
  9152. messageLabel += "messages";
  9153. break;
  9154. case ResultWas::FatalErrorCondition:
  9155. colour = Colour::Error;
  9156. passOrFail = "FAILED";
  9157. messageLabel = "due to a fatal error condition";
  9158. break;
  9159. case ResultWas::DidntThrowException:
  9160. colour = Colour::Error;
  9161. passOrFail = "FAILED";
  9162. messageLabel = "because no exception was thrown where one was expected";
  9163. break;
  9164. case ResultWas::Info:
  9165. messageLabel = "info";
  9166. break;
  9167. case ResultWas::Warning:
  9168. messageLabel = "warning";
  9169. break;
  9170. case ResultWas::ExplicitFailure:
  9171. passOrFail = "FAILED";
  9172. colour = Colour::Error;
  9173. if (_stats.infoMessages.size() == 1)
  9174. messageLabel = "explicitly with message";
  9175. if (_stats.infoMessages.size() > 1)
  9176. messageLabel = "explicitly with messages";
  9177. break;
  9178. // These cases are here to prevent compiler warnings
  9179. case ResultWas::Unknown:
  9180. case ResultWas::FailureBit:
  9181. case ResultWas::Exception:
  9182. passOrFail = "** internal error **";
  9183. colour = Colour::Error;
  9184. break;
  9185. }
  9186. }
  9187. void print() const {
  9188. printSourceInfo();
  9189. if (stats.totals.assertions.total() > 0) {
  9190. if (result.isOk())
  9191. stream << '\n';
  9192. printResultType();
  9193. printOriginalExpression();
  9194. printReconstructedExpression();
  9195. } else {
  9196. stream << '\n';
  9197. }
  9198. printMessage();
  9199. }
  9200. private:
  9201. void printResultType() const {
  9202. if (!passOrFail.empty()) {
  9203. Colour colourGuard(colour);
  9204. stream << passOrFail << ":\n";
  9205. }
  9206. }
  9207. void printOriginalExpression() const {
  9208. if (result.hasExpression()) {
  9209. Colour colourGuard(Colour::OriginalExpression);
  9210. stream << " ";
  9211. stream << result.getExpressionInMacro();
  9212. stream << '\n';
  9213. }
  9214. }
  9215. void printReconstructedExpression() const {
  9216. if (result.hasExpandedExpression()) {
  9217. stream << "with expansion:\n";
  9218. Colour colourGuard(Colour::ReconstructedExpression);
  9219. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  9220. }
  9221. }
  9222. void printMessage() const {
  9223. if (!messageLabel.empty())
  9224. stream << messageLabel << ':' << '\n';
  9225. for (auto const& msg : messages) {
  9226. // If this assertion is a warning ignore any INFO messages
  9227. if (printInfoMessages || msg.type != ResultWas::Info)
  9228. stream << Column(msg.message).indent(2) << '\n';
  9229. }
  9230. }
  9231. void printSourceInfo() const {
  9232. Colour colourGuard(Colour::FileName);
  9233. stream << result.getSourceInfo() << ": ";
  9234. }
  9235. std::ostream& stream;
  9236. AssertionStats const& stats;
  9237. AssertionResult const& result;
  9238. Colour::Code colour;
  9239. std::string passOrFail;
  9240. std::string messageLabel;
  9241. std::string message;
  9242. std::vector<MessageInfo> messages;
  9243. bool printInfoMessages;
  9244. };
  9245. std::size_t makeRatio(std::size_t number, std::size_t total) {
  9246. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  9247. return (ratio == 0 && number > 0) ? 1 : ratio;
  9248. }
  9249. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  9250. if (i > j && i > k)
  9251. return i;
  9252. else if (j > k)
  9253. return j;
  9254. else
  9255. return k;
  9256. }
  9257. struct ColumnInfo {
  9258. enum Justification { Left, Right };
  9259. std::string name;
  9260. int width;
  9261. Justification justification;
  9262. };
  9263. struct ColumnBreak {};
  9264. struct RowBreak {};
  9265. class Duration {
  9266. enum class Unit {
  9267. Auto,
  9268. Nanoseconds,
  9269. Microseconds,
  9270. Milliseconds,
  9271. Seconds,
  9272. Minutes
  9273. };
  9274. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  9275. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  9276. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  9277. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  9278. uint64_t m_inNanoseconds;
  9279. Unit m_units;
  9280. public:
  9281. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  9282. : m_inNanoseconds(inNanoseconds),
  9283. m_units(units) {
  9284. if (m_units == Unit::Auto) {
  9285. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  9286. m_units = Unit::Nanoseconds;
  9287. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  9288. m_units = Unit::Microseconds;
  9289. else if (m_inNanoseconds < s_nanosecondsInASecond)
  9290. m_units = Unit::Milliseconds;
  9291. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  9292. m_units = Unit::Seconds;
  9293. else
  9294. m_units = Unit::Minutes;
  9295. }
  9296. }
  9297. auto value() const -> double {
  9298. switch (m_units) {
  9299. case Unit::Microseconds:
  9300. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  9301. case Unit::Milliseconds:
  9302. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  9303. case Unit::Seconds:
  9304. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  9305. case Unit::Minutes:
  9306. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  9307. default:
  9308. return static_cast<double>(m_inNanoseconds);
  9309. }
  9310. }
  9311. auto unitsAsString() const -> std::string {
  9312. switch (m_units) {
  9313. case Unit::Nanoseconds:
  9314. return "ns";
  9315. case Unit::Microseconds:
  9316. return "µs";
  9317. case Unit::Milliseconds:
  9318. return "ms";
  9319. case Unit::Seconds:
  9320. return "s";
  9321. case Unit::Minutes:
  9322. return "m";
  9323. default:
  9324. return "** internal error **";
  9325. }
  9326. }
  9327. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  9328. return os << duration.value() << " " << duration.unitsAsString();
  9329. }
  9330. };
  9331. } // end anon namespace
  9332. class TablePrinter {
  9333. std::ostream& m_os;
  9334. std::vector<ColumnInfo> m_columnInfos;
  9335. std::ostringstream m_oss;
  9336. int m_currentColumn = -1;
  9337. bool m_isOpen = false;
  9338. public:
  9339. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  9340. : m_os( os ),
  9341. m_columnInfos( std::move( columnInfos ) ) {}
  9342. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  9343. return m_columnInfos;
  9344. }
  9345. void open() {
  9346. if (!m_isOpen) {
  9347. m_isOpen = true;
  9348. *this << RowBreak();
  9349. for (auto const& info : m_columnInfos)
  9350. *this << info.name << ColumnBreak();
  9351. *this << RowBreak();
  9352. m_os << Catch::getLineOfChars<'-'>() << "\n";
  9353. }
  9354. }
  9355. void close() {
  9356. if (m_isOpen) {
  9357. *this << RowBreak();
  9358. m_os << std::endl;
  9359. m_isOpen = false;
  9360. }
  9361. }
  9362. template<typename T>
  9363. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  9364. tp.m_oss << value;
  9365. return tp;
  9366. }
  9367. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  9368. auto colStr = tp.m_oss.str();
  9369. // This takes account of utf8 encodings
  9370. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  9371. tp.m_oss.str("");
  9372. tp.open();
  9373. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  9374. tp.m_currentColumn = -1;
  9375. tp.m_os << "\n";
  9376. }
  9377. tp.m_currentColumn++;
  9378. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  9379. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  9380. ? std::string(colInfo.width - (strSize + 2), ' ')
  9381. : std::string();
  9382. if (colInfo.justification == ColumnInfo::Left)
  9383. tp.m_os << colStr << padding << " ";
  9384. else
  9385. tp.m_os << padding << colStr << " ";
  9386. return tp;
  9387. }
  9388. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  9389. if (tp.m_currentColumn > 0) {
  9390. tp.m_os << "\n";
  9391. tp.m_currentColumn = -1;
  9392. }
  9393. return tp;
  9394. }
  9395. };
  9396. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  9397. : StreamingReporterBase(config),
  9398. m_tablePrinter(new TablePrinter(config.stream(),
  9399. {
  9400. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  9401. { "iters", 8, ColumnInfo::Right },
  9402. { "elapsed ns", 14, ColumnInfo::Right },
  9403. { "average", 14, ColumnInfo::Right }
  9404. })) {}
  9405. ConsoleReporter::~ConsoleReporter() = default;
  9406. std::string ConsoleReporter::getDescription() {
  9407. return "Reports test results as plain lines of text";
  9408. }
  9409. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  9410. stream << "No test cases matched '" << spec << '\'' << std::endl;
  9411. }
  9412. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  9413. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  9414. AssertionResult const& result = _assertionStats.assertionResult;
  9415. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  9416. // Drop out if result was successful but we're not printing them.
  9417. if (!includeResults && result.getResultType() != ResultWas::Warning)
  9418. return false;
  9419. lazyPrint();
  9420. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  9421. printer.print();
  9422. stream << std::endl;
  9423. return true;
  9424. }
  9425. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  9426. m_headerPrinted = false;
  9427. StreamingReporterBase::sectionStarting(_sectionInfo);
  9428. }
  9429. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  9430. m_tablePrinter->close();
  9431. if (_sectionStats.missingAssertions) {
  9432. lazyPrint();
  9433. Colour colour(Colour::ResultError);
  9434. if (m_sectionStack.size() > 1)
  9435. stream << "\nNo assertions in section";
  9436. else
  9437. stream << "\nNo assertions in test case";
  9438. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  9439. }
  9440. if (m_config->showDurations() == ShowDurations::Always) {
  9441. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  9442. }
  9443. if (m_headerPrinted) {
  9444. m_headerPrinted = false;
  9445. }
  9446. StreamingReporterBase::sectionEnded(_sectionStats);
  9447. }
  9448. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  9449. lazyPrintWithoutClosingBenchmarkTable();
  9450. auto nameCol = Column( info.name ).width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) );
  9451. bool firstLine = true;
  9452. for (auto line : nameCol) {
  9453. if (!firstLine)
  9454. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  9455. else
  9456. firstLine = false;
  9457. (*m_tablePrinter) << line << ColumnBreak();
  9458. }
  9459. }
  9460. void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) {
  9461. Duration average(stats.elapsedTimeInNanoseconds / stats.iterations);
  9462. (*m_tablePrinter)
  9463. << stats.iterations << ColumnBreak()
  9464. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  9465. << average << ColumnBreak();
  9466. }
  9467. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  9468. m_tablePrinter->close();
  9469. StreamingReporterBase::testCaseEnded(_testCaseStats);
  9470. m_headerPrinted = false;
  9471. }
  9472. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  9473. if (currentGroupInfo.used) {
  9474. printSummaryDivider();
  9475. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  9476. printTotals(_testGroupStats.totals);
  9477. stream << '\n' << std::endl;
  9478. }
  9479. StreamingReporterBase::testGroupEnded(_testGroupStats);
  9480. }
  9481. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  9482. printTotalsDivider(_testRunStats.totals);
  9483. printTotals(_testRunStats.totals);
  9484. stream << std::endl;
  9485. StreamingReporterBase::testRunEnded(_testRunStats);
  9486. }
  9487. void ConsoleReporter::lazyPrint() {
  9488. m_tablePrinter->close();
  9489. lazyPrintWithoutClosingBenchmarkTable();
  9490. }
  9491. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  9492. if (!currentTestRunInfo.used)
  9493. lazyPrintRunInfo();
  9494. if (!currentGroupInfo.used)
  9495. lazyPrintGroupInfo();
  9496. if (!m_headerPrinted) {
  9497. printTestCaseAndSectionHeader();
  9498. m_headerPrinted = true;
  9499. }
  9500. }
  9501. void ConsoleReporter::lazyPrintRunInfo() {
  9502. stream << '\n' << getLineOfChars<'~'>() << '\n';
  9503. Colour colour(Colour::SecondaryText);
  9504. stream << currentTestRunInfo->name
  9505. << " is a Catch v" << libraryVersion() << " host application.\n"
  9506. << "Run with -? for options\n\n";
  9507. if (m_config->rngSeed() != 0)
  9508. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  9509. currentTestRunInfo.used = true;
  9510. }
  9511. void ConsoleReporter::lazyPrintGroupInfo() {
  9512. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  9513. printClosedHeader("Group: " + currentGroupInfo->name);
  9514. currentGroupInfo.used = true;
  9515. }
  9516. }
  9517. void ConsoleReporter::printTestCaseAndSectionHeader() {
  9518. assert(!m_sectionStack.empty());
  9519. printOpenHeader(currentTestCaseInfo->name);
  9520. if (m_sectionStack.size() > 1) {
  9521. Colour colourGuard(Colour::Headers);
  9522. auto
  9523. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  9524. itEnd = m_sectionStack.end();
  9525. for (; it != itEnd; ++it)
  9526. printHeaderString(it->name, 2);
  9527. }
  9528. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  9529. if (!lineInfo.empty()) {
  9530. stream << getLineOfChars<'-'>() << '\n';
  9531. Colour colourGuard(Colour::FileName);
  9532. stream << lineInfo << '\n';
  9533. }
  9534. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  9535. }
  9536. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  9537. printOpenHeader(_name);
  9538. stream << getLineOfChars<'.'>() << '\n';
  9539. }
  9540. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  9541. stream << getLineOfChars<'-'>() << '\n';
  9542. {
  9543. Colour colourGuard(Colour::Headers);
  9544. printHeaderString(_name);
  9545. }
  9546. }
  9547. // if string has a : in first line will set indent to follow it on
  9548. // subsequent lines
  9549. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  9550. std::size_t i = _string.find(": ");
  9551. if (i != std::string::npos)
  9552. i += 2;
  9553. else
  9554. i = 0;
  9555. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  9556. }
  9557. struct SummaryColumn {
  9558. SummaryColumn( std::string _label, Colour::Code _colour )
  9559. : label( std::move( _label ) ),
  9560. colour( _colour ) {}
  9561. SummaryColumn addRow( std::size_t count ) {
  9562. ReusableStringStream rss;
  9563. rss << count;
  9564. std::string row = rss.str();
  9565. for (auto& oldRow : rows) {
  9566. while (oldRow.size() < row.size())
  9567. oldRow = ' ' + oldRow;
  9568. while (oldRow.size() > row.size())
  9569. row = ' ' + row;
  9570. }
  9571. rows.push_back(row);
  9572. return *this;
  9573. }
  9574. std::string label;
  9575. Colour::Code colour;
  9576. std::vector<std::string> rows;
  9577. };
  9578. void ConsoleReporter::printTotals( Totals const& totals ) {
  9579. if (totals.testCases.total() == 0) {
  9580. stream << Colour(Colour::Warning) << "No tests ran\n";
  9581. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  9582. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  9583. stream << " ("
  9584. << pluralise(totals.assertions.passed, "assertion") << " in "
  9585. << pluralise(totals.testCases.passed, "test case") << ')'
  9586. << '\n';
  9587. } else {
  9588. std::vector<SummaryColumn> columns;
  9589. columns.push_back(SummaryColumn("", Colour::None)
  9590. .addRow(totals.testCases.total())
  9591. .addRow(totals.assertions.total()));
  9592. columns.push_back(SummaryColumn("passed", Colour::Success)
  9593. .addRow(totals.testCases.passed)
  9594. .addRow(totals.assertions.passed));
  9595. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  9596. .addRow(totals.testCases.failed)
  9597. .addRow(totals.assertions.failed));
  9598. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  9599. .addRow(totals.testCases.failedButOk)
  9600. .addRow(totals.assertions.failedButOk));
  9601. printSummaryRow("test cases", columns, 0);
  9602. printSummaryRow("assertions", columns, 1);
  9603. }
  9604. }
  9605. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  9606. for (auto col : cols) {
  9607. std::string value = col.rows[row];
  9608. if (col.label.empty()) {
  9609. stream << label << ": ";
  9610. if (value != "0")
  9611. stream << value;
  9612. else
  9613. stream << Colour(Colour::Warning) << "- none -";
  9614. } else if (value != "0") {
  9615. stream << Colour(Colour::LightGrey) << " | ";
  9616. stream << Colour(col.colour)
  9617. << value << ' ' << col.label;
  9618. }
  9619. }
  9620. stream << '\n';
  9621. }
  9622. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  9623. if (totals.testCases.total() > 0) {
  9624. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  9625. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  9626. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  9627. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  9628. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  9629. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  9630. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  9631. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  9632. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  9633. if (totals.testCases.allPassed())
  9634. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  9635. else
  9636. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  9637. } else {
  9638. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  9639. }
  9640. stream << '\n';
  9641. }
  9642. void ConsoleReporter::printSummaryDivider() {
  9643. stream << getLineOfChars<'-'>() << '\n';
  9644. }
  9645. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  9646. } // end namespace Catch
  9647. #if defined(_MSC_VER)
  9648. #pragma warning(pop)
  9649. #endif
  9650. // end catch_reporter_console.cpp
  9651. // start catch_reporter_junit.cpp
  9652. #include <assert.h>
  9653. #include <sstream>
  9654. #include <ctime>
  9655. #include <algorithm>
  9656. namespace Catch {
  9657. namespace {
  9658. std::string getCurrentTimestamp() {
  9659. // Beware, this is not reentrant because of backward compatibility issues
  9660. // Also, UTC only, again because of backward compatibility (%z is C++11)
  9661. time_t rawtime;
  9662. std::time(&rawtime);
  9663. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  9664. #ifdef _MSC_VER
  9665. std::tm timeInfo = {};
  9666. gmtime_s(&timeInfo, &rawtime);
  9667. #else
  9668. std::tm* timeInfo;
  9669. timeInfo = std::gmtime(&rawtime);
  9670. #endif
  9671. char timeStamp[timeStampSize];
  9672. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  9673. #ifdef _MSC_VER
  9674. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  9675. #else
  9676. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  9677. #endif
  9678. return std::string(timeStamp);
  9679. }
  9680. std::string fileNameTag(const std::vector<std::string> &tags) {
  9681. auto it = std::find_if(begin(tags),
  9682. end(tags),
  9683. [] (std::string const& tag) {return tag.front() == '#'; });
  9684. if (it != tags.end())
  9685. return it->substr(1);
  9686. return std::string();
  9687. }
  9688. } // anonymous namespace
  9689. JunitReporter::JunitReporter( ReporterConfig const& _config )
  9690. : CumulativeReporterBase( _config ),
  9691. xml( _config.stream() )
  9692. {
  9693. m_reporterPrefs.shouldRedirectStdOut = true;
  9694. }
  9695. JunitReporter::~JunitReporter() {};
  9696. std::string JunitReporter::getDescription() {
  9697. return "Reports test results in an XML format that looks like Ant's junitreport target";
  9698. }
  9699. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  9700. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  9701. CumulativeReporterBase::testRunStarting( runInfo );
  9702. xml.startElement( "testsuites" );
  9703. }
  9704. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  9705. suiteTimer.start();
  9706. stdOutForSuite.clear();
  9707. stdErrForSuite.clear();
  9708. unexpectedExceptions = 0;
  9709. CumulativeReporterBase::testGroupStarting( groupInfo );
  9710. }
  9711. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  9712. m_okToFail = testCaseInfo.okToFail();
  9713. }
  9714. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  9715. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  9716. unexpectedExceptions++;
  9717. return CumulativeReporterBase::assertionEnded( assertionStats );
  9718. }
  9719. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  9720. stdOutForSuite += testCaseStats.stdOut;
  9721. stdErrForSuite += testCaseStats.stdErr;
  9722. CumulativeReporterBase::testCaseEnded( testCaseStats );
  9723. }
  9724. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  9725. double suiteTime = suiteTimer.getElapsedSeconds();
  9726. CumulativeReporterBase::testGroupEnded( testGroupStats );
  9727. writeGroup( *m_testGroups.back(), suiteTime );
  9728. }
  9729. void JunitReporter::testRunEndedCumulative() {
  9730. xml.endElement();
  9731. }
  9732. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  9733. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  9734. TestGroupStats const& stats = groupNode.value;
  9735. xml.writeAttribute( "name", stats.groupInfo.name );
  9736. xml.writeAttribute( "errors", unexpectedExceptions );
  9737. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  9738. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  9739. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  9740. if( m_config->showDurations() == ShowDurations::Never )
  9741. xml.writeAttribute( "time", "" );
  9742. else
  9743. xml.writeAttribute( "time", suiteTime );
  9744. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  9745. // Write test cases
  9746. for( auto const& child : groupNode.children )
  9747. writeTestCase( *child );
  9748. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  9749. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  9750. }
  9751. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  9752. TestCaseStats const& stats = testCaseNode.value;
  9753. // All test cases have exactly one section - which represents the
  9754. // test case itself. That section may have 0-n nested sections
  9755. assert( testCaseNode.children.size() == 1 );
  9756. SectionNode const& rootSection = *testCaseNode.children.front();
  9757. std::string className = stats.testInfo.className;
  9758. if( className.empty() ) {
  9759. className = fileNameTag(stats.testInfo.tags);
  9760. if ( className.empty() )
  9761. className = "global";
  9762. }
  9763. if ( !m_config->name().empty() )
  9764. className = m_config->name() + "." + className;
  9765. writeSection( className, "", rootSection );
  9766. }
  9767. void JunitReporter::writeSection( std::string const& className,
  9768. std::string const& rootName,
  9769. SectionNode const& sectionNode ) {
  9770. std::string name = trim( sectionNode.stats.sectionInfo.name );
  9771. if( !rootName.empty() )
  9772. name = rootName + '/' + name;
  9773. if( !sectionNode.assertions.empty() ||
  9774. !sectionNode.stdOut.empty() ||
  9775. !sectionNode.stdErr.empty() ) {
  9776. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  9777. if( className.empty() ) {
  9778. xml.writeAttribute( "classname", name );
  9779. xml.writeAttribute( "name", "root" );
  9780. }
  9781. else {
  9782. xml.writeAttribute( "classname", className );
  9783. xml.writeAttribute( "name", name );
  9784. }
  9785. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  9786. writeAssertions( sectionNode );
  9787. if( !sectionNode.stdOut.empty() )
  9788. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  9789. if( !sectionNode.stdErr.empty() )
  9790. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  9791. }
  9792. for( auto const& childNode : sectionNode.childSections )
  9793. if( className.empty() )
  9794. writeSection( name, "", *childNode );
  9795. else
  9796. writeSection( className, name, *childNode );
  9797. }
  9798. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  9799. for( auto const& assertion : sectionNode.assertions )
  9800. writeAssertion( assertion );
  9801. }
  9802. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  9803. AssertionResult const& result = stats.assertionResult;
  9804. if( !result.isOk() ) {
  9805. std::string elementName;
  9806. switch( result.getResultType() ) {
  9807. case ResultWas::ThrewException:
  9808. case ResultWas::FatalErrorCondition:
  9809. elementName = "error";
  9810. break;
  9811. case ResultWas::ExplicitFailure:
  9812. elementName = "failure";
  9813. break;
  9814. case ResultWas::ExpressionFailed:
  9815. elementName = "failure";
  9816. break;
  9817. case ResultWas::DidntThrowException:
  9818. elementName = "failure";
  9819. break;
  9820. // We should never see these here:
  9821. case ResultWas::Info:
  9822. case ResultWas::Warning:
  9823. case ResultWas::Ok:
  9824. case ResultWas::Unknown:
  9825. case ResultWas::FailureBit:
  9826. case ResultWas::Exception:
  9827. elementName = "internalError";
  9828. break;
  9829. }
  9830. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  9831. xml.writeAttribute( "message", result.getExpandedExpression() );
  9832. xml.writeAttribute( "type", result.getTestMacroName() );
  9833. ReusableStringStream rss;
  9834. if( !result.getMessage().empty() )
  9835. rss << result.getMessage() << '\n';
  9836. for( auto const& msg : stats.infoMessages )
  9837. if( msg.type == ResultWas::Info )
  9838. rss << msg.message << '\n';
  9839. rss << "at " << result.getSourceInfo();
  9840. xml.writeText( rss.str(), false );
  9841. }
  9842. }
  9843. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  9844. } // end namespace Catch
  9845. // end catch_reporter_junit.cpp
  9846. // start catch_reporter_multi.cpp
  9847. namespace Catch {
  9848. void MultipleReporters::add( IStreamingReporterPtr&& reporter ) {
  9849. m_reporters.push_back( std::move( reporter ) );
  9850. }
  9851. ReporterPreferences MultipleReporters::getPreferences() const {
  9852. return m_reporters[0]->getPreferences();
  9853. }
  9854. std::set<Verbosity> MultipleReporters::getSupportedVerbosities() {
  9855. return std::set<Verbosity>{ };
  9856. }
  9857. void MultipleReporters::noMatchingTestCases( std::string const& spec ) {
  9858. for( auto const& reporter : m_reporters )
  9859. reporter->noMatchingTestCases( spec );
  9860. }
  9861. void MultipleReporters::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  9862. for( auto const& reporter : m_reporters )
  9863. reporter->benchmarkStarting( benchmarkInfo );
  9864. }
  9865. void MultipleReporters::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
  9866. for( auto const& reporter : m_reporters )
  9867. reporter->benchmarkEnded( benchmarkStats );
  9868. }
  9869. void MultipleReporters::testRunStarting( TestRunInfo const& testRunInfo ) {
  9870. for( auto const& reporter : m_reporters )
  9871. reporter->testRunStarting( testRunInfo );
  9872. }
  9873. void MultipleReporters::testGroupStarting( GroupInfo const& groupInfo ) {
  9874. for( auto const& reporter : m_reporters )
  9875. reporter->testGroupStarting( groupInfo );
  9876. }
  9877. void MultipleReporters::testCaseStarting( TestCaseInfo const& testInfo ) {
  9878. for( auto const& reporter : m_reporters )
  9879. reporter->testCaseStarting( testInfo );
  9880. }
  9881. void MultipleReporters::sectionStarting( SectionInfo const& sectionInfo ) {
  9882. for( auto const& reporter : m_reporters )
  9883. reporter->sectionStarting( sectionInfo );
  9884. }
  9885. void MultipleReporters::assertionStarting( AssertionInfo const& assertionInfo ) {
  9886. for( auto const& reporter : m_reporters )
  9887. reporter->assertionStarting( assertionInfo );
  9888. }
  9889. // The return value indicates if the messages buffer should be cleared:
  9890. bool MultipleReporters::assertionEnded( AssertionStats const& assertionStats ) {
  9891. bool clearBuffer = false;
  9892. for( auto const& reporter : m_reporters )
  9893. clearBuffer |= reporter->assertionEnded( assertionStats );
  9894. return clearBuffer;
  9895. }
  9896. void MultipleReporters::sectionEnded( SectionStats const& sectionStats ) {
  9897. for( auto const& reporter : m_reporters )
  9898. reporter->sectionEnded( sectionStats );
  9899. }
  9900. void MultipleReporters::testCaseEnded( TestCaseStats const& testCaseStats ) {
  9901. for( auto const& reporter : m_reporters )
  9902. reporter->testCaseEnded( testCaseStats );
  9903. }
  9904. void MultipleReporters::testGroupEnded( TestGroupStats const& testGroupStats ) {
  9905. for( auto const& reporter : m_reporters )
  9906. reporter->testGroupEnded( testGroupStats );
  9907. }
  9908. void MultipleReporters::testRunEnded( TestRunStats const& testRunStats ) {
  9909. for( auto const& reporter : m_reporters )
  9910. reporter->testRunEnded( testRunStats );
  9911. }
  9912. void MultipleReporters::skipTest( TestCaseInfo const& testInfo ) {
  9913. for( auto const& reporter : m_reporters )
  9914. reporter->skipTest( testInfo );
  9915. }
  9916. bool MultipleReporters::isMulti() const {
  9917. return true;
  9918. }
  9919. } // end namespace Catch
  9920. // end catch_reporter_multi.cpp
  9921. // start catch_reporter_xml.cpp
  9922. #if defined(_MSC_VER)
  9923. #pragma warning(push)
  9924. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  9925. // Note that 4062 (not all labels are handled
  9926. // and default is missing) is enabled
  9927. #endif
  9928. namespace Catch {
  9929. XmlReporter::XmlReporter( ReporterConfig const& _config )
  9930. : StreamingReporterBase( _config ),
  9931. m_xml(_config.stream())
  9932. {
  9933. m_reporterPrefs.shouldRedirectStdOut = true;
  9934. }
  9935. XmlReporter::~XmlReporter() = default;
  9936. std::string XmlReporter::getDescription() {
  9937. return "Reports test results as an XML document";
  9938. }
  9939. std::string XmlReporter::getStylesheetRef() const {
  9940. return std::string();
  9941. }
  9942. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  9943. m_xml
  9944. .writeAttribute( "filename", sourceInfo.file )
  9945. .writeAttribute( "line", sourceInfo.line );
  9946. }
  9947. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  9948. StreamingReporterBase::noMatchingTestCases( s );
  9949. }
  9950. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  9951. StreamingReporterBase::testRunStarting( testInfo );
  9952. std::string stylesheetRef = getStylesheetRef();
  9953. if( !stylesheetRef.empty() )
  9954. m_xml.writeStylesheetRef( stylesheetRef );
  9955. m_xml.startElement( "Catch" );
  9956. if( !m_config->name().empty() )
  9957. m_xml.writeAttribute( "name", m_config->name() );
  9958. }
  9959. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  9960. StreamingReporterBase::testGroupStarting( groupInfo );
  9961. m_xml.startElement( "Group" )
  9962. .writeAttribute( "name", groupInfo.name );
  9963. }
  9964. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  9965. StreamingReporterBase::testCaseStarting(testInfo);
  9966. m_xml.startElement( "TestCase" )
  9967. .writeAttribute( "name", trim( testInfo.name ) )
  9968. .writeAttribute( "description", testInfo.description )
  9969. .writeAttribute( "tags", testInfo.tagsAsString() );
  9970. writeSourceInfo( testInfo.lineInfo );
  9971. if ( m_config->showDurations() == ShowDurations::Always )
  9972. m_testCaseTimer.start();
  9973. m_xml.ensureTagClosed();
  9974. }
  9975. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  9976. StreamingReporterBase::sectionStarting( sectionInfo );
  9977. if( m_sectionDepth++ > 0 ) {
  9978. m_xml.startElement( "Section" )
  9979. .writeAttribute( "name", trim( sectionInfo.name ) )
  9980. .writeAttribute( "description", sectionInfo.description );
  9981. writeSourceInfo( sectionInfo.lineInfo );
  9982. m_xml.ensureTagClosed();
  9983. }
  9984. }
  9985. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  9986. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  9987. AssertionResult const& result = assertionStats.assertionResult;
  9988. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  9989. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  9990. // Print any info messages in <Info> tags.
  9991. for( auto const& msg : assertionStats.infoMessages ) {
  9992. if( msg.type == ResultWas::Info && includeResults ) {
  9993. m_xml.scopedElement( "Info" )
  9994. .writeText( msg.message );
  9995. } else if ( msg.type == ResultWas::Warning ) {
  9996. m_xml.scopedElement( "Warning" )
  9997. .writeText( msg.message );
  9998. }
  9999. }
  10000. }
  10001. // Drop out if result was successful but we're not printing them.
  10002. if( !includeResults && result.getResultType() != ResultWas::Warning )
  10003. return true;
  10004. // Print the expression if there is one.
  10005. if( result.hasExpression() ) {
  10006. m_xml.startElement( "Expression" )
  10007. .writeAttribute( "success", result.succeeded() )
  10008. .writeAttribute( "type", result.getTestMacroName() );
  10009. writeSourceInfo( result.getSourceInfo() );
  10010. m_xml.scopedElement( "Original" )
  10011. .writeText( result.getExpression() );
  10012. m_xml.scopedElement( "Expanded" )
  10013. .writeText( result.getExpandedExpression() );
  10014. }
  10015. // And... Print a result applicable to each result type.
  10016. switch( result.getResultType() ) {
  10017. case ResultWas::ThrewException:
  10018. m_xml.startElement( "Exception" );
  10019. writeSourceInfo( result.getSourceInfo() );
  10020. m_xml.writeText( result.getMessage() );
  10021. m_xml.endElement();
  10022. break;
  10023. case ResultWas::FatalErrorCondition:
  10024. m_xml.startElement( "FatalErrorCondition" );
  10025. writeSourceInfo( result.getSourceInfo() );
  10026. m_xml.writeText( result.getMessage() );
  10027. m_xml.endElement();
  10028. break;
  10029. case ResultWas::Info:
  10030. m_xml.scopedElement( "Info" )
  10031. .writeText( result.getMessage() );
  10032. break;
  10033. case ResultWas::Warning:
  10034. // Warning will already have been written
  10035. break;
  10036. case ResultWas::ExplicitFailure:
  10037. m_xml.startElement( "Failure" );
  10038. writeSourceInfo( result.getSourceInfo() );
  10039. m_xml.writeText( result.getMessage() );
  10040. m_xml.endElement();
  10041. break;
  10042. default:
  10043. break;
  10044. }
  10045. if( result.hasExpression() )
  10046. m_xml.endElement();
  10047. return true;
  10048. }
  10049. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  10050. StreamingReporterBase::sectionEnded( sectionStats );
  10051. if( --m_sectionDepth > 0 ) {
  10052. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  10053. e.writeAttribute( "successes", sectionStats.assertions.passed );
  10054. e.writeAttribute( "failures", sectionStats.assertions.failed );
  10055. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  10056. if ( m_config->showDurations() == ShowDurations::Always )
  10057. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  10058. m_xml.endElement();
  10059. }
  10060. }
  10061. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10062. StreamingReporterBase::testCaseEnded( testCaseStats );
  10063. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  10064. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  10065. if ( m_config->showDurations() == ShowDurations::Always )
  10066. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  10067. if( !testCaseStats.stdOut.empty() )
  10068. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  10069. if( !testCaseStats.stdErr.empty() )
  10070. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  10071. m_xml.endElement();
  10072. }
  10073. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10074. StreamingReporterBase::testGroupEnded( testGroupStats );
  10075. // TODO: Check testGroupStats.aborting and act accordingly.
  10076. m_xml.scopedElement( "OverallResults" )
  10077. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  10078. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  10079. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  10080. m_xml.endElement();
  10081. }
  10082. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  10083. StreamingReporterBase::testRunEnded( testRunStats );
  10084. m_xml.scopedElement( "OverallResults" )
  10085. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  10086. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  10087. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  10088. m_xml.endElement();
  10089. }
  10090. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  10091. } // end namespace Catch
  10092. #if defined(_MSC_VER)
  10093. #pragma warning(pop)
  10094. #endif
  10095. // end catch_reporter_xml.cpp
  10096. namespace Catch {
  10097. LeakDetector leakDetector;
  10098. }
  10099. #ifdef __clang__
  10100. #pragma clang diagnostic pop
  10101. #endif
  10102. // end catch_impl.hpp
  10103. #endif
  10104. #ifdef CATCH_CONFIG_MAIN
  10105. // start catch_default_main.hpp
  10106. #ifndef __OBJC__
  10107. #if defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  10108. // Standard C/C++ Win32 Unicode wmain entry point
  10109. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  10110. #else
  10111. // Standard C/C++ main entry point
  10112. int main (int argc, char * argv[]) {
  10113. #endif
  10114. return Catch::Session().run( argc, argv );
  10115. }
  10116. #else // __OBJC__
  10117. // Objective-C entry point
  10118. int main (int argc, char * const argv[]) {
  10119. #if !CATCH_ARC_ENABLED
  10120. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  10121. #endif
  10122. Catch::registerTestMethods();
  10123. int result = Catch::Session().run( argc, (char**)argv );
  10124. #if !CATCH_ARC_ENABLED
  10125. [pool drain];
  10126. #endif
  10127. return result;
  10128. }
  10129. #endif // __OBJC__
  10130. // end catch_default_main.hpp
  10131. #endif
  10132. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  10133. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  10134. # undef CLARA_CONFIG_MAIN
  10135. #endif
  10136. #if !defined(CATCH_CONFIG_DISABLE)
  10137. //////
  10138. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  10139. #ifdef CATCH_CONFIG_PREFIX_ALL
  10140. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10141. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10142. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", __VA_ARGS__ )
  10143. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  10144. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  10145. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10146. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  10147. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  10148. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10149. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10150. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10151. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10152. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10153. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  10154. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", __VA_ARGS__ )
  10155. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  10156. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10157. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10158. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10159. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10160. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10161. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10162. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  10163. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  10164. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10165. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  10166. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  10167. #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  10168. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  10169. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  10170. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  10171. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  10172. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  10173. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10174. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10175. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10176. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  10177. // "BDD-style" convenience wrappers
  10178. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  10179. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  10180. #define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( "Given: ") + desc )
  10181. #define CATCH_WHEN( desc ) CATCH_SECTION( std::string( " When: ") + desc )
  10182. #define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  10183. #define CATCH_THEN( desc ) CATCH_SECTION( std::string( " Then: ") + desc )
  10184. #define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  10185. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  10186. #else
  10187. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10188. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10189. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10190. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  10191. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  10192. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10193. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  10194. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10195. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10196. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10197. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10198. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10199. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10200. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  10201. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10202. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  10203. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10204. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10205. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10206. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10207. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10208. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10209. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  10210. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  10211. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10212. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  10213. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  10214. #define CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  10215. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  10216. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  10217. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  10218. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  10219. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  10220. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10221. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10222. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10223. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  10224. #endif
  10225. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  10226. // "BDD-style" convenience wrappers
  10227. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  10228. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  10229. #define GIVEN( desc ) SECTION( std::string(" Given: ") + desc )
  10230. #define WHEN( desc ) SECTION( std::string(" When: ") + desc )
  10231. #define AND_WHEN( desc ) SECTION( std::string("And when: ") + desc )
  10232. #define THEN( desc ) SECTION( std::string(" Then: ") + desc )
  10233. #define AND_THEN( desc ) SECTION( std::string(" And: ") + desc )
  10234. using Catch::Detail::Approx;
  10235. #else
  10236. //////
  10237. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  10238. #ifdef CATCH_CONFIG_PREFIX_ALL
  10239. #define CATCH_REQUIRE( ... ) (void)(0)
  10240. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  10241. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  10242. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  10243. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  10244. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10245. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10246. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  10247. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  10248. #define CATCH_CHECK( ... ) (void)(0)
  10249. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  10250. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  10251. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  10252. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  10253. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  10254. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  10255. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  10256. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10257. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10258. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10259. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  10260. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10261. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  10262. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  10263. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10264. #define CATCH_INFO( msg ) (void)(0)
  10265. #define CATCH_WARN( msg ) (void)(0)
  10266. #define CATCH_CAPTURE( msg ) (void)(0)
  10267. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10268. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10269. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  10270. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  10271. #define CATCH_SECTION( ... )
  10272. #define CATCH_FAIL( ... ) (void)(0)
  10273. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  10274. #define CATCH_SUCCEED( ... ) (void)(0)
  10275. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10276. // "BDD-style" convenience wrappers
  10277. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10278. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  10279. #define CATCH_GIVEN( desc )
  10280. #define CATCH_WHEN( desc )
  10281. #define CATCH_AND_WHEN( desc )
  10282. #define CATCH_THEN( desc )
  10283. #define CATCH_AND_THEN( desc )
  10284. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  10285. #else
  10286. #define REQUIRE( ... ) (void)(0)
  10287. #define REQUIRE_FALSE( ... ) (void)(0)
  10288. #define REQUIRE_THROWS( ... ) (void)(0)
  10289. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  10290. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  10291. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10292. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10293. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10294. #define REQUIRE_NOTHROW( ... ) (void)(0)
  10295. #define CHECK( ... ) (void)(0)
  10296. #define CHECK_FALSE( ... ) (void)(0)
  10297. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  10298. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  10299. #define CHECK_NOFAIL( ... ) (void)(0)
  10300. #define CHECK_THROWS( ... ) (void)(0)
  10301. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  10302. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  10303. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10304. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10305. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10306. #define CHECK_NOTHROW( ... ) (void)(0)
  10307. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10308. #define CHECK_THAT( arg, matcher ) (void)(0)
  10309. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  10310. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10311. #define INFO( msg ) (void)(0)
  10312. #define WARN( msg ) (void)(0)
  10313. #define CAPTURE( msg ) (void)(0)
  10314. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10315. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10316. #define METHOD_AS_TEST_CASE( method, ... )
  10317. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  10318. #define SECTION( ... )
  10319. #define FAIL( ... ) (void)(0)
  10320. #define FAIL_CHECK( ... ) (void)(0)
  10321. #define SUCCEED( ... ) (void)(0)
  10322. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10323. #endif
  10324. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  10325. // "BDD-style" convenience wrappers
  10326. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  10327. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  10328. #define GIVEN( desc )
  10329. #define WHEN( desc )
  10330. #define AND_WHEN( desc )
  10331. #define THEN( desc )
  10332. #define AND_THEN( desc )
  10333. using Catch::Detail::Approx;
  10334. #endif
  10335. #endif // ! CATCH_CONFIG_IMPL_ONLY
  10336. // start catch_reenable_warnings.h
  10337. #ifdef __clang__
  10338. # ifdef __ICC // icpc defines the __clang__ macro
  10339. # pragma warning(pop)
  10340. # else
  10341. # pragma clang diagnostic pop
  10342. # endif
  10343. #elif defined __GNUC__
  10344. # pragma GCC diagnostic pop
  10345. #endif
  10346. // end catch_reenable_warnings.h
  10347. // end catch.hpp
  10348. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED