Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

12797 lines
425KB

  1. /*
  2. * Catch v2.1.2
  3. * Generated: 2018-02-09 17:05:21.506253
  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. #define CATCH_VERSION_MAJOR 2
  15. #define CATCH_VERSION_MINOR 1
  16. #define CATCH_VERSION_PATCH 2
  17. #ifdef __clang__
  18. # pragma clang system_header
  19. #elif defined __GNUC__
  20. # pragma GCC system_header
  21. #endif
  22. // start catch_suppress_warnings.h
  23. #ifdef __clang__
  24. # ifdef __ICC // icpc defines the __clang__ macro
  25. # pragma warning(push)
  26. # pragma warning(disable: 161 1682)
  27. # else // __ICC
  28. # pragma clang diagnostic ignored "-Wunused-variable"
  29. # pragma clang diagnostic push
  30. # pragma clang diagnostic ignored "-Wpadded"
  31. # pragma clang diagnostic ignored "-Wswitch-enum"
  32. # pragma clang diagnostic ignored "-Wcovered-switch-default"
  33. # endif
  34. #elif defined __GNUC__
  35. # pragma GCC diagnostic ignored "-Wunused-variable"
  36. # pragma GCC diagnostic ignored "-Wparentheses"
  37. # pragma GCC diagnostic push
  38. # pragma GCC diagnostic ignored "-Wpadded"
  39. #endif
  40. // end catch_suppress_warnings.h
  41. #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
  42. # define CATCH_IMPL
  43. # define CATCH_CONFIG_ALL_PARTS
  44. #endif
  45. // In the impl file, we want to have access to all parts of the headers
  46. // Can also be used to sanely support PCHs
  47. #if defined(CATCH_CONFIG_ALL_PARTS)
  48. # define CATCH_CONFIG_EXTERNAL_INTERFACES
  49. # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
  50. # undef CATCH_CONFIG_DISABLE_MATCHERS
  51. # endif
  52. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  53. #endif
  54. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  55. // start catch_platform.h
  56. #ifdef __APPLE__
  57. # include <TargetConditionals.h>
  58. # if TARGET_OS_OSX == 1
  59. # define CATCH_PLATFORM_MAC
  60. # elif TARGET_OS_IPHONE == 1
  61. # define CATCH_PLATFORM_IPHONE
  62. # endif
  63. #elif defined(linux) || defined(__linux) || defined(__linux__)
  64. # define CATCH_PLATFORM_LINUX
  65. #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER)
  66. # define CATCH_PLATFORM_WINDOWS
  67. #endif
  68. // end catch_platform.h
  69. #ifdef CATCH_IMPL
  70. # ifndef CLARA_CONFIG_MAIN
  71. # define CLARA_CONFIG_MAIN_NOT_DEFINED
  72. # define CLARA_CONFIG_MAIN
  73. # endif
  74. #endif
  75. // start catch_user_interfaces.h
  76. namespace Catch {
  77. unsigned int rngSeed();
  78. }
  79. // end catch_user_interfaces.h
  80. // start catch_tag_alias_autoregistrar.h
  81. // start catch_common.h
  82. // start catch_compiler_capabilities.h
  83. // Detect a number of compiler features - by compiler
  84. // The following features are defined:
  85. //
  86. // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
  87. // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
  88. // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
  89. // ****************
  90. // Note to maintainers: if new toggles are added please document them
  91. // in configuration.md, too
  92. // ****************
  93. // In general each macro has a _NO_<feature name> form
  94. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  95. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  96. // can be combined, en-mass, with the _NO_ forms later.
  97. #ifdef __cplusplus
  98. # if __cplusplus >= 201402L
  99. # define CATCH_CPP14_OR_GREATER
  100. # endif
  101. # if __cplusplus >= 201703L
  102. # define CATCH_CPP17_OR_GREATER
  103. # endif
  104. #endif
  105. #if defined(CATCH_CPP17_OR_GREATER)
  106. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  107. #endif
  108. #ifdef __clang__
  109. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  110. _Pragma( "clang diagnostic push" ) \
  111. _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
  112. _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
  113. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  114. _Pragma( "clang diagnostic pop" )
  115. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  116. _Pragma( "clang diagnostic push" ) \
  117. _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
  118. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  119. _Pragma( "clang diagnostic pop" )
  120. #endif // __clang__
  121. ////////////////////////////////////////////////////////////////////////////////
  122. // We know some environments not to support full POSIX signals
  123. #if defined(__CYGWIN__) || defined(__QNX__)
  124. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  125. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  126. # endif
  127. #endif
  128. #ifdef __OS400__
  129. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  130. # define CATCH_CONFIG_COLOUR_NONE
  131. #endif
  132. ////////////////////////////////////////////////////////////////////////////////
  133. // Cygwin
  134. #ifdef __CYGWIN__
  135. // Required for some versions of Cygwin to declare gettimeofday
  136. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  137. # define _BSD_SOURCE
  138. #endif // __CYGWIN__
  139. ////////////////////////////////////////////////////////////////////////////////
  140. // Visual C++
  141. #ifdef _MSC_VER
  142. # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
  143. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  144. # endif
  145. // Universal Windows platform does not support SEH
  146. // Or console colours (or console at all...)
  147. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  148. # define CATCH_CONFIG_COLOUR_NONE
  149. # else
  150. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  151. # endif
  152. #endif // _MSC_VER
  153. ////////////////////////////////////////////////////////////////////////////////
  154. // Use of __COUNTER__ is suppressed during code analysis in
  155. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  156. // handled by it.
  157. // Otherwise all supported compilers support COUNTER macro,
  158. // but user still might want to turn it off
  159. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  160. #define CATCH_INTERNAL_CONFIG_COUNTER
  161. #endif
  162. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  163. # define CATCH_CONFIG_COUNTER
  164. #endif
  165. #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH)
  166. # define CATCH_CONFIG_WINDOWS_SEH
  167. #endif
  168. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  169. #if !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
  170. # define CATCH_CONFIG_POSIX_SIGNALS
  171. #endif
  172. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_INTERNAL_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  173. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  174. #endif
  175. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  176. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  177. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  178. #endif
  179. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  180. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  181. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  182. #endif
  183. // end catch_compiler_capabilities.h
  184. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  185. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  186. #ifdef CATCH_CONFIG_COUNTER
  187. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  188. #else
  189. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  190. #endif
  191. #include <iosfwd>
  192. #include <string>
  193. #include <cstdint>
  194. namespace Catch {
  195. struct CaseSensitive { enum Choice {
  196. Yes,
  197. No
  198. }; };
  199. class NonCopyable {
  200. NonCopyable( NonCopyable const& ) = delete;
  201. NonCopyable( NonCopyable && ) = delete;
  202. NonCopyable& operator = ( NonCopyable const& ) = delete;
  203. NonCopyable& operator = ( NonCopyable && ) = delete;
  204. protected:
  205. NonCopyable();
  206. virtual ~NonCopyable();
  207. };
  208. struct SourceLineInfo {
  209. SourceLineInfo() = delete;
  210. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  211. : file( _file ),
  212. line( _line )
  213. {}
  214. SourceLineInfo( SourceLineInfo const& other ) = default;
  215. SourceLineInfo( SourceLineInfo && ) = default;
  216. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  217. SourceLineInfo& operator = ( SourceLineInfo && ) = default;
  218. bool empty() const noexcept;
  219. bool operator == ( SourceLineInfo const& other ) const noexcept;
  220. bool operator < ( SourceLineInfo const& other ) const noexcept;
  221. char const* file;
  222. std::size_t line;
  223. };
  224. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  225. // Use this in variadic streaming macros to allow
  226. // >> +StreamEndStop
  227. // as well as
  228. // >> stuff +StreamEndStop
  229. struct StreamEndStop {
  230. std::string operator+() const;
  231. };
  232. template<typename T>
  233. T const& operator + ( T const& value, StreamEndStop ) {
  234. return value;
  235. }
  236. }
  237. #define CATCH_INTERNAL_LINEINFO \
  238. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  239. // end catch_common.h
  240. namespace Catch {
  241. struct RegistrarForTagAliases {
  242. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  243. };
  244. } // end namespace Catch
  245. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  246. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  247. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  248. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  249. // end catch_tag_alias_autoregistrar.h
  250. // start catch_test_registry.h
  251. // start catch_interfaces_testcase.h
  252. #include <vector>
  253. #include <memory>
  254. namespace Catch {
  255. class TestSpec;
  256. struct ITestInvoker {
  257. virtual void invoke () const = 0;
  258. virtual ~ITestInvoker();
  259. };
  260. using ITestCasePtr = std::shared_ptr<ITestInvoker>;
  261. class TestCase;
  262. struct IConfig;
  263. struct ITestCaseRegistry {
  264. virtual ~ITestCaseRegistry();
  265. virtual std::vector<TestCase> const& getAllTests() const = 0;
  266. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  267. };
  268. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  269. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  270. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  271. }
  272. // end catch_interfaces_testcase.h
  273. // start catch_stringref.h
  274. #include <cstddef>
  275. #include <string>
  276. #include <iosfwd>
  277. namespace Catch {
  278. class StringData;
  279. /// A non-owning string class (similar to the forthcoming std::string_view)
  280. /// Note that, because a StringRef may be a substring of another string,
  281. /// it may not be null terminated. c_str() must return a null terminated
  282. /// string, however, and so the StringRef will internally take ownership
  283. /// (taking a copy), if necessary. In theory this ownership is not externally
  284. /// visible - but it does mean (substring) StringRefs should not be shared between
  285. /// threads.
  286. class StringRef {
  287. public:
  288. using size_type = std::size_t;
  289. private:
  290. friend struct StringRefTestAccess;
  291. char const* m_start;
  292. size_type m_size;
  293. char* m_data = nullptr;
  294. void takeOwnership();
  295. static constexpr char const* const s_empty = "";
  296. public: // construction/ assignment
  297. StringRef() noexcept
  298. : StringRef( s_empty, 0 )
  299. {}
  300. StringRef( StringRef const& other ) noexcept
  301. : m_start( other.m_start ),
  302. m_size( other.m_size )
  303. {}
  304. StringRef( StringRef&& other ) noexcept
  305. : m_start( other.m_start ),
  306. m_size( other.m_size ),
  307. m_data( other.m_data )
  308. {
  309. other.m_data = nullptr;
  310. }
  311. StringRef( char const* rawChars ) noexcept;
  312. StringRef( char const* rawChars, size_type size ) noexcept
  313. : m_start( rawChars ),
  314. m_size( size )
  315. {}
  316. StringRef( std::string const& stdString ) noexcept
  317. : m_start( stdString.c_str() ),
  318. m_size( stdString.size() )
  319. {}
  320. ~StringRef() noexcept {
  321. delete[] m_data;
  322. }
  323. auto operator = ( StringRef const &other ) noexcept -> StringRef& {
  324. delete[] m_data;
  325. m_data = nullptr;
  326. m_start = other.m_start;
  327. m_size = other.m_size;
  328. return *this;
  329. }
  330. operator std::string() const;
  331. void swap( StringRef& other ) noexcept;
  332. public: // operators
  333. auto operator == ( StringRef const& other ) const noexcept -> bool;
  334. auto operator != ( StringRef const& other ) const noexcept -> bool;
  335. auto operator[] ( size_type index ) const noexcept -> char;
  336. public: // named queries
  337. auto empty() const noexcept -> bool {
  338. return m_size == 0;
  339. }
  340. auto size() const noexcept -> size_type {
  341. return m_size;
  342. }
  343. auto numberOfCharacters() const noexcept -> size_type;
  344. auto c_str() const -> char const*;
  345. public: // substrings and searches
  346. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  347. private: // ownership queries - may not be consistent between calls
  348. auto isOwned() const noexcept -> bool;
  349. auto isSubstring() const noexcept -> bool;
  350. auto data() const noexcept -> char const*;
  351. };
  352. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  353. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  354. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  355. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  356. inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  357. return StringRef( rawChars, size );
  358. }
  359. } // namespace Catch
  360. // end catch_stringref.h
  361. namespace Catch {
  362. template<typename C>
  363. class TestInvokerAsMethod : public ITestInvoker {
  364. void (C::*m_testAsMethod)();
  365. public:
  366. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  367. void invoke() const override {
  368. C obj;
  369. (obj.*m_testAsMethod)();
  370. }
  371. };
  372. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  373. template<typename C>
  374. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  375. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  376. }
  377. struct NameAndTags {
  378. NameAndTags( StringRef name_ = StringRef(), StringRef tags_ = StringRef() ) noexcept;
  379. StringRef name;
  380. StringRef tags;
  381. };
  382. struct AutoReg : NonCopyable {
  383. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  384. ~AutoReg();
  385. };
  386. } // end namespace Catch
  387. #if defined(CATCH_CONFIG_DISABLE)
  388. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  389. static void TestName()
  390. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  391. namespace{ \
  392. struct TestName : ClassName { \
  393. void test(); \
  394. }; \
  395. } \
  396. void TestName::test()
  397. #endif
  398. ///////////////////////////////////////////////////////////////////////////////
  399. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  400. static void TestName(); \
  401. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  402. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  403. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  404. static void TestName()
  405. #define INTERNAL_CATCH_TESTCASE( ... ) \
  406. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  407. ///////////////////////////////////////////////////////////////////////////////
  408. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  409. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  410. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  411. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  412. ///////////////////////////////////////////////////////////////////////////////
  413. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  414. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  415. namespace{ \
  416. struct TestName : ClassName{ \
  417. void test(); \
  418. }; \
  419. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  420. } \
  421. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  422. void TestName::test()
  423. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  424. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  425. ///////////////////////////////////////////////////////////////////////////////
  426. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  427. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  428. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  429. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  430. // end catch_test_registry.h
  431. // start catch_capture.hpp
  432. // start catch_assertionhandler.h
  433. // start catch_assertioninfo.h
  434. // start catch_result_type.h
  435. namespace Catch {
  436. // ResultWas::OfType enum
  437. struct ResultWas { enum OfType {
  438. Unknown = -1,
  439. Ok = 0,
  440. Info = 1,
  441. Warning = 2,
  442. FailureBit = 0x10,
  443. ExpressionFailed = FailureBit | 1,
  444. ExplicitFailure = FailureBit | 2,
  445. Exception = 0x100 | FailureBit,
  446. ThrewException = Exception | 1,
  447. DidntThrowException = Exception | 2,
  448. FatalErrorCondition = 0x200 | FailureBit
  449. }; };
  450. bool isOk( ResultWas::OfType resultType );
  451. bool isJustInfo( int flags );
  452. // ResultDisposition::Flags enum
  453. struct ResultDisposition { enum Flags {
  454. Normal = 0x01,
  455. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  456. FalseTest = 0x04, // Prefix expression with !
  457. SuppressFail = 0x08 // Failures are reported but do not fail the test
  458. }; };
  459. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  460. bool shouldContinueOnFailure( int flags );
  461. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  462. bool shouldSuppressFailure( int flags );
  463. } // end namespace Catch
  464. // end catch_result_type.h
  465. namespace Catch {
  466. struct AssertionInfo
  467. {
  468. StringRef macroName;
  469. SourceLineInfo lineInfo;
  470. StringRef capturedExpression;
  471. ResultDisposition::Flags resultDisposition;
  472. // We want to delete this constructor but a compiler bug in 4.8 means
  473. // the struct is then treated as non-aggregate
  474. //AssertionInfo() = delete;
  475. };
  476. } // end namespace Catch
  477. // end catch_assertioninfo.h
  478. // start catch_decomposer.h
  479. // start catch_tostring.h
  480. #include <vector>
  481. #include <cstddef>
  482. #include <type_traits>
  483. #include <string>
  484. // start catch_stream.h
  485. #include <iosfwd>
  486. #include <cstddef>
  487. #include <ostream>
  488. namespace Catch {
  489. std::ostream& cout();
  490. std::ostream& cerr();
  491. std::ostream& clog();
  492. class StringRef;
  493. struct IStream {
  494. virtual ~IStream();
  495. virtual std::ostream& stream() const = 0;
  496. };
  497. auto makeStream( StringRef const &filename ) -> IStream const*;
  498. class ReusableStringStream {
  499. std::size_t m_index;
  500. std::ostream* m_oss;
  501. public:
  502. ReusableStringStream();
  503. ~ReusableStringStream();
  504. auto str() const -> std::string;
  505. template<typename T>
  506. auto operator << ( T const& value ) -> ReusableStringStream& {
  507. *m_oss << value;
  508. return *this;
  509. }
  510. auto get() -> std::ostream& { return *m_oss; }
  511. static void cleanup();
  512. };
  513. }
  514. // end catch_stream.h
  515. #ifdef __OBJC__
  516. // start catch_objc_arc.hpp
  517. #import <Foundation/Foundation.h>
  518. #ifdef __has_feature
  519. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  520. #else
  521. #define CATCH_ARC_ENABLED 0
  522. #endif
  523. void arcSafeRelease( NSObject* obj );
  524. id performOptionalSelector( id obj, SEL sel );
  525. #if !CATCH_ARC_ENABLED
  526. inline void arcSafeRelease( NSObject* obj ) {
  527. [obj release];
  528. }
  529. inline id performOptionalSelector( id obj, SEL sel ) {
  530. if( [obj respondsToSelector: sel] )
  531. return [obj performSelector: sel];
  532. return nil;
  533. }
  534. #define CATCH_UNSAFE_UNRETAINED
  535. #define CATCH_ARC_STRONG
  536. #else
  537. inline void arcSafeRelease( NSObject* ){}
  538. inline id performOptionalSelector( id obj, SEL sel ) {
  539. #ifdef __clang__
  540. #pragma clang diagnostic push
  541. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  542. #endif
  543. if( [obj respondsToSelector: sel] )
  544. return [obj performSelector: sel];
  545. #ifdef __clang__
  546. #pragma clang diagnostic pop
  547. #endif
  548. return nil;
  549. }
  550. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  551. #define CATCH_ARC_STRONG __strong
  552. #endif
  553. // end catch_objc_arc.hpp
  554. #endif
  555. #ifdef _MSC_VER
  556. #pragma warning(push)
  557. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  558. #endif
  559. // We need a dummy global operator<< so we can bring it into Catch namespace later
  560. struct Catch_global_namespace_dummy {};
  561. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  562. namespace Catch {
  563. // Bring in operator<< from global namespace into Catch namespace
  564. using ::operator<<;
  565. namespace Detail {
  566. extern const std::string unprintableString;
  567. std::string rawMemoryToString( const void *object, std::size_t size );
  568. template<typename T>
  569. std::string rawMemoryToString( const T& object ) {
  570. return rawMemoryToString( &object, sizeof(object) );
  571. }
  572. template<typename T>
  573. class IsStreamInsertable {
  574. template<typename SS, typename TT>
  575. static auto test(int)
  576. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  577. template<typename, typename>
  578. static auto test(...)->std::false_type;
  579. public:
  580. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  581. };
  582. template<typename E>
  583. std::string convertUnknownEnumToString( E e );
  584. template<typename T>
  585. typename std::enable_if<!std::is_enum<T>::value, std::string>::type convertUnstreamable( T const& ) {
  586. return Detail::unprintableString;
  587. }
  588. template<typename T>
  589. typename std::enable_if<std::is_enum<T>::value, std::string>::type convertUnstreamable( T const& value ) {
  590. return convertUnknownEnumToString( value );
  591. }
  592. } // namespace Detail
  593. // If we decide for C++14, change these to enable_if_ts
  594. template <typename T, typename = void>
  595. struct StringMaker {
  596. template <typename Fake = T>
  597. static
  598. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  599. convert(const Fake& value) {
  600. ReusableStringStream rss;
  601. rss << value;
  602. return rss.str();
  603. }
  604. template <typename Fake = T>
  605. static
  606. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  607. convert( const Fake& value ) {
  608. return Detail::convertUnstreamable( value );
  609. }
  610. };
  611. namespace Detail {
  612. // This function dispatches all stringification requests inside of Catch.
  613. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  614. template <typename T>
  615. std::string stringify(const T& e) {
  616. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  617. }
  618. template<typename E>
  619. std::string convertUnknownEnumToString( E e ) {
  620. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  621. }
  622. } // namespace Detail
  623. // Some predefined specializations
  624. template<>
  625. struct StringMaker<std::string> {
  626. static std::string convert(const std::string& str);
  627. };
  628. template<>
  629. struct StringMaker<std::wstring> {
  630. static std::string convert(const std::wstring& wstr);
  631. };
  632. template<>
  633. struct StringMaker<char const *> {
  634. static std::string convert(char const * str);
  635. };
  636. template<>
  637. struct StringMaker<char *> {
  638. static std::string convert(char * str);
  639. };
  640. template<>
  641. struct StringMaker<wchar_t const *> {
  642. static std::string convert(wchar_t const * str);
  643. };
  644. template<>
  645. struct StringMaker<wchar_t *> {
  646. static std::string convert(wchar_t * str);
  647. };
  648. template<int SZ>
  649. struct StringMaker<char[SZ]> {
  650. static std::string convert(const char* str) {
  651. return ::Catch::Detail::stringify(std::string{ str });
  652. }
  653. };
  654. template<int SZ>
  655. struct StringMaker<signed char[SZ]> {
  656. static std::string convert(const char* str) {
  657. return ::Catch::Detail::stringify(std::string{ str });
  658. }
  659. };
  660. template<int SZ>
  661. struct StringMaker<unsigned char[SZ]> {
  662. static std::string convert(const char* str) {
  663. return ::Catch::Detail::stringify(std::string{ str });
  664. }
  665. };
  666. template<>
  667. struct StringMaker<int> {
  668. static std::string convert(int value);
  669. };
  670. template<>
  671. struct StringMaker<long> {
  672. static std::string convert(long value);
  673. };
  674. template<>
  675. struct StringMaker<long long> {
  676. static std::string convert(long long value);
  677. };
  678. template<>
  679. struct StringMaker<unsigned int> {
  680. static std::string convert(unsigned int value);
  681. };
  682. template<>
  683. struct StringMaker<unsigned long> {
  684. static std::string convert(unsigned long value);
  685. };
  686. template<>
  687. struct StringMaker<unsigned long long> {
  688. static std::string convert(unsigned long long value);
  689. };
  690. template<>
  691. struct StringMaker<bool> {
  692. static std::string convert(bool b);
  693. };
  694. template<>
  695. struct StringMaker<char> {
  696. static std::string convert(char c);
  697. };
  698. template<>
  699. struct StringMaker<signed char> {
  700. static std::string convert(signed char c);
  701. };
  702. template<>
  703. struct StringMaker<unsigned char> {
  704. static std::string convert(unsigned char c);
  705. };
  706. template<>
  707. struct StringMaker<std::nullptr_t> {
  708. static std::string convert(std::nullptr_t);
  709. };
  710. template<>
  711. struct StringMaker<float> {
  712. static std::string convert(float value);
  713. };
  714. template<>
  715. struct StringMaker<double> {
  716. static std::string convert(double value);
  717. };
  718. template <typename T>
  719. struct StringMaker<T*> {
  720. template <typename U>
  721. static std::string convert(U* p) {
  722. if (p) {
  723. return ::Catch::Detail::rawMemoryToString(p);
  724. } else {
  725. return "nullptr";
  726. }
  727. }
  728. };
  729. template <typename R, typename C>
  730. struct StringMaker<R C::*> {
  731. static std::string convert(R C::* p) {
  732. if (p) {
  733. return ::Catch::Detail::rawMemoryToString(p);
  734. } else {
  735. return "nullptr";
  736. }
  737. }
  738. };
  739. namespace Detail {
  740. template<typename InputIterator>
  741. std::string rangeToString(InputIterator first, InputIterator last) {
  742. ReusableStringStream rss;
  743. rss << "{ ";
  744. if (first != last) {
  745. rss << ::Catch::Detail::stringify(*first);
  746. for (++first; first != last; ++first)
  747. rss << ", " << ::Catch::Detail::stringify(*first);
  748. }
  749. rss << " }";
  750. return rss.str();
  751. }
  752. }
  753. #ifdef __OBJC__
  754. template<>
  755. struct StringMaker<NSString*> {
  756. static std::string convert(NSString * nsstring) {
  757. if (!nsstring)
  758. return "nil";
  759. return std::string("@") + [nsstring UTF8String];
  760. }
  761. };
  762. template<>
  763. struct StringMaker<NSObject*> {
  764. static std::string convert(NSObject* nsObject) {
  765. return ::Catch::Detail::stringify([nsObject description]);
  766. }
  767. };
  768. namespace Detail {
  769. inline std::string stringify( NSString* nsstring ) {
  770. return StringMaker<NSString*>::convert( nsstring );
  771. }
  772. } // namespace Detail
  773. #endif // __OBJC__
  774. } // namespace Catch
  775. //////////////////////////////////////////////////////
  776. // Separate std-lib types stringification, so it can be selectively enabled
  777. // This means that we do not bring in
  778. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  779. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  780. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  781. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  782. #endif
  783. // Separate std::pair specialization
  784. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  785. #include <utility>
  786. namespace Catch {
  787. template<typename T1, typename T2>
  788. struct StringMaker<std::pair<T1, T2> > {
  789. static std::string convert(const std::pair<T1, T2>& pair) {
  790. ReusableStringStream rss;
  791. rss << "{ "
  792. << ::Catch::Detail::stringify(pair.first)
  793. << ", "
  794. << ::Catch::Detail::stringify(pair.second)
  795. << " }";
  796. return rss.str();
  797. }
  798. };
  799. }
  800. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  801. // Separate std::tuple specialization
  802. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  803. #include <tuple>
  804. namespace Catch {
  805. namespace Detail {
  806. template<
  807. typename Tuple,
  808. std::size_t N = 0,
  809. bool = (N < std::tuple_size<Tuple>::value)
  810. >
  811. struct TupleElementPrinter {
  812. static void print(const Tuple& tuple, std::ostream& os) {
  813. os << (N ? ", " : " ")
  814. << ::Catch::Detail::stringify(std::get<N>(tuple));
  815. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  816. }
  817. };
  818. template<
  819. typename Tuple,
  820. std::size_t N
  821. >
  822. struct TupleElementPrinter<Tuple, N, false> {
  823. static void print(const Tuple&, std::ostream&) {}
  824. };
  825. }
  826. template<typename ...Types>
  827. struct StringMaker<std::tuple<Types...>> {
  828. static std::string convert(const std::tuple<Types...>& tuple) {
  829. ReusableStringStream rss;
  830. rss << '{';
  831. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  832. rss << " }";
  833. return rss.str();
  834. }
  835. };
  836. }
  837. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  838. namespace Catch {
  839. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  840. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  841. using std::begin;
  842. using std::end;
  843. not_this_one begin( ... );
  844. not_this_one end( ... );
  845. template <typename T>
  846. struct is_range {
  847. static const bool value =
  848. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  849. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  850. };
  851. template<typename Range>
  852. std::string rangeToString( Range const& range ) {
  853. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  854. }
  855. // Handle vector<bool> specially
  856. template<typename Allocator>
  857. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  858. ReusableStringStream rss;
  859. rss << "{ ";
  860. bool first = true;
  861. for( bool b : v ) {
  862. if( first )
  863. first = false;
  864. else
  865. rss << ", ";
  866. rss << ::Catch::Detail::stringify( b );
  867. }
  868. rss << " }";
  869. return rss.str();
  870. }
  871. template<typename R>
  872. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  873. static std::string convert( R const& range ) {
  874. return rangeToString( range );
  875. }
  876. };
  877. template <typename T, int SZ>
  878. struct StringMaker<T[SZ]> {
  879. static std::string convert(T const(&arr)[SZ]) {
  880. return rangeToString(arr);
  881. }
  882. };
  883. } // namespace Catch
  884. // Separate std::chrono::duration specialization
  885. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  886. #include <ctime>
  887. #include <ratio>
  888. #include <chrono>
  889. namespace Catch {
  890. template <class Ratio>
  891. struct ratio_string {
  892. static std::string symbol();
  893. };
  894. template <class Ratio>
  895. std::string ratio_string<Ratio>::symbol() {
  896. Catch::ReusableStringStream rss;
  897. rss << '[' << Ratio::num << '/'
  898. << Ratio::den << ']';
  899. return rss.str();
  900. }
  901. template <>
  902. struct ratio_string<std::atto> {
  903. static std::string symbol();
  904. };
  905. template <>
  906. struct ratio_string<std::femto> {
  907. static std::string symbol();
  908. };
  909. template <>
  910. struct ratio_string<std::pico> {
  911. static std::string symbol();
  912. };
  913. template <>
  914. struct ratio_string<std::nano> {
  915. static std::string symbol();
  916. };
  917. template <>
  918. struct ratio_string<std::micro> {
  919. static std::string symbol();
  920. };
  921. template <>
  922. struct ratio_string<std::milli> {
  923. static std::string symbol();
  924. };
  925. ////////////
  926. // std::chrono::duration specializations
  927. template<typename Value, typename Ratio>
  928. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  929. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  930. ReusableStringStream rss;
  931. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  932. return rss.str();
  933. }
  934. };
  935. template<typename Value>
  936. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  937. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  938. ReusableStringStream rss;
  939. rss << duration.count() << " s";
  940. return rss.str();
  941. }
  942. };
  943. template<typename Value>
  944. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  945. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  946. ReusableStringStream rss;
  947. rss << duration.count() << " m";
  948. return rss.str();
  949. }
  950. };
  951. template<typename Value>
  952. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  953. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  954. ReusableStringStream rss;
  955. rss << duration.count() << " h";
  956. return rss.str();
  957. }
  958. };
  959. ////////////
  960. // std::chrono::time_point specialization
  961. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  962. template<typename Clock, typename Duration>
  963. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  964. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  965. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  966. }
  967. };
  968. // std::chrono::time_point<system_clock> specialization
  969. template<typename Duration>
  970. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  971. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  972. auto converted = std::chrono::system_clock::to_time_t(time_point);
  973. #ifdef _MSC_VER
  974. std::tm timeInfo = {};
  975. gmtime_s(&timeInfo, &converted);
  976. #else
  977. std::tm* timeInfo = std::gmtime(&converted);
  978. #endif
  979. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  980. char timeStamp[timeStampSize];
  981. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  982. #ifdef _MSC_VER
  983. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  984. #else
  985. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  986. #endif
  987. return std::string(timeStamp);
  988. }
  989. };
  990. }
  991. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  992. #ifdef _MSC_VER
  993. #pragma warning(pop)
  994. #endif
  995. // end catch_tostring.h
  996. #include <iosfwd>
  997. #ifdef _MSC_VER
  998. #pragma warning(push)
  999. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1000. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1001. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1002. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1003. #endif
  1004. namespace Catch {
  1005. struct ITransientExpression {
  1006. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1007. auto getResult() const -> bool { return m_result; }
  1008. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1009. ITransientExpression( bool isBinaryExpression, bool result )
  1010. : m_isBinaryExpression( isBinaryExpression ),
  1011. m_result( result )
  1012. {}
  1013. // We don't actually need a virtual destructor, but many static analysers
  1014. // complain if it's not here :-(
  1015. virtual ~ITransientExpression();
  1016. bool m_isBinaryExpression;
  1017. bool m_result;
  1018. };
  1019. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1020. template<typename LhsT, typename RhsT>
  1021. class BinaryExpr : public ITransientExpression {
  1022. LhsT m_lhs;
  1023. StringRef m_op;
  1024. RhsT m_rhs;
  1025. void streamReconstructedExpression( std::ostream &os ) const override {
  1026. formatReconstructedExpression
  1027. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1028. }
  1029. public:
  1030. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1031. : ITransientExpression{ true, comparisonResult },
  1032. m_lhs( lhs ),
  1033. m_op( op ),
  1034. m_rhs( rhs )
  1035. {}
  1036. };
  1037. template<typename LhsT>
  1038. class UnaryExpr : public ITransientExpression {
  1039. LhsT m_lhs;
  1040. void streamReconstructedExpression( std::ostream &os ) const override {
  1041. os << Catch::Detail::stringify( m_lhs );
  1042. }
  1043. public:
  1044. explicit UnaryExpr( LhsT lhs )
  1045. : ITransientExpression{ false, lhs ? true : false },
  1046. m_lhs( lhs )
  1047. {}
  1048. };
  1049. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1050. template<typename LhsT, typename RhsT>
  1051. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1052. template<typename T>
  1053. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1054. template<typename T>
  1055. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1056. template<typename T>
  1057. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1058. template<typename T>
  1059. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1060. template<typename LhsT, typename RhsT>
  1061. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1062. template<typename T>
  1063. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1064. template<typename T>
  1065. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1066. template<typename T>
  1067. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1068. template<typename T>
  1069. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1070. template<typename LhsT>
  1071. class ExprLhs {
  1072. LhsT m_lhs;
  1073. public:
  1074. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1075. template<typename RhsT>
  1076. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1077. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1078. }
  1079. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1080. return { m_lhs == rhs, m_lhs, "==", rhs };
  1081. }
  1082. template<typename RhsT>
  1083. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1084. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1085. }
  1086. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1087. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1088. }
  1089. template<typename RhsT>
  1090. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1091. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1092. }
  1093. template<typename RhsT>
  1094. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1095. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  1096. }
  1097. template<typename RhsT>
  1098. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1099. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  1100. }
  1101. template<typename RhsT>
  1102. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1103. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  1104. }
  1105. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  1106. return UnaryExpr<LhsT>{ m_lhs };
  1107. }
  1108. };
  1109. void handleExpression( ITransientExpression const& expr );
  1110. template<typename T>
  1111. void handleExpression( ExprLhs<T> const& expr ) {
  1112. handleExpression( expr.makeUnaryExpr() );
  1113. }
  1114. struct Decomposer {
  1115. template<typename T>
  1116. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  1117. return ExprLhs<T const&>{ lhs };
  1118. }
  1119. auto operator <=( bool value ) -> ExprLhs<bool> {
  1120. return ExprLhs<bool>{ value };
  1121. }
  1122. };
  1123. } // end namespace Catch
  1124. #ifdef _MSC_VER
  1125. #pragma warning(pop)
  1126. #endif
  1127. // end catch_decomposer.h
  1128. // start catch_interfaces_capture.h
  1129. #include <string>
  1130. namespace Catch {
  1131. class AssertionResult;
  1132. struct AssertionInfo;
  1133. struct SectionInfo;
  1134. struct SectionEndInfo;
  1135. struct MessageInfo;
  1136. struct Counts;
  1137. struct BenchmarkInfo;
  1138. struct BenchmarkStats;
  1139. struct AssertionReaction;
  1140. struct ITransientExpression;
  1141. struct IResultCapture {
  1142. virtual ~IResultCapture();
  1143. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  1144. Counts& assertions ) = 0;
  1145. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  1146. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  1147. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  1148. virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;
  1149. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  1150. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  1151. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  1152. virtual void handleExpr
  1153. ( AssertionInfo const& info,
  1154. ITransientExpression const& expr,
  1155. AssertionReaction& reaction ) = 0;
  1156. virtual void handleMessage
  1157. ( AssertionInfo const& info,
  1158. ResultWas::OfType resultType,
  1159. StringRef const& message,
  1160. AssertionReaction& reaction ) = 0;
  1161. virtual void handleUnexpectedExceptionNotThrown
  1162. ( AssertionInfo const& info,
  1163. AssertionReaction& reaction ) = 0;
  1164. virtual void handleUnexpectedInflightException
  1165. ( AssertionInfo const& info,
  1166. std::string const& message,
  1167. AssertionReaction& reaction ) = 0;
  1168. virtual void handleIncomplete
  1169. ( AssertionInfo const& info ) = 0;
  1170. virtual void handleNonExpr
  1171. ( AssertionInfo const &info,
  1172. ResultWas::OfType resultType,
  1173. AssertionReaction &reaction ) = 0;
  1174. virtual bool lastAssertionPassed() = 0;
  1175. virtual void assertionPassed() = 0;
  1176. // Deprecated, do not use:
  1177. virtual std::string getCurrentTestName() const = 0;
  1178. virtual const AssertionResult* getLastResult() const = 0;
  1179. virtual void exceptionEarlyReported() = 0;
  1180. };
  1181. IResultCapture& getResultCapture();
  1182. }
  1183. // end catch_interfaces_capture.h
  1184. namespace Catch {
  1185. struct TestFailureException{};
  1186. struct AssertionResultData;
  1187. struct IResultCapture;
  1188. class RunContext;
  1189. class LazyExpression {
  1190. friend class AssertionHandler;
  1191. friend struct AssertionStats;
  1192. friend class RunContext;
  1193. ITransientExpression const* m_transientExpression = nullptr;
  1194. bool m_isNegated;
  1195. public:
  1196. LazyExpression( bool isNegated );
  1197. LazyExpression( LazyExpression const& other );
  1198. LazyExpression& operator = ( LazyExpression const& ) = delete;
  1199. explicit operator bool() const;
  1200. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  1201. };
  1202. struct AssertionReaction {
  1203. bool shouldDebugBreak = false;
  1204. bool shouldThrow = false;
  1205. };
  1206. class AssertionHandler {
  1207. AssertionInfo m_assertionInfo;
  1208. AssertionReaction m_reaction;
  1209. bool m_completed = false;
  1210. IResultCapture& m_resultCapture;
  1211. public:
  1212. AssertionHandler
  1213. ( StringRef macroName,
  1214. SourceLineInfo const& lineInfo,
  1215. StringRef capturedExpression,
  1216. ResultDisposition::Flags resultDisposition );
  1217. ~AssertionHandler() {
  1218. if ( !m_completed ) {
  1219. m_resultCapture.handleIncomplete( m_assertionInfo );
  1220. }
  1221. }
  1222. template<typename T>
  1223. void handleExpr( ExprLhs<T> const& expr ) {
  1224. handleExpr( expr.makeUnaryExpr() );
  1225. }
  1226. void handleExpr( ITransientExpression const& expr );
  1227. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  1228. void handleExceptionThrownAsExpected();
  1229. void handleUnexpectedExceptionNotThrown();
  1230. void handleExceptionNotThrownAsExpected();
  1231. void handleThrowingCallSkipped();
  1232. void handleUnexpectedInflightException();
  1233. void complete();
  1234. void setCompleted();
  1235. // query
  1236. auto allowThrows() const -> bool;
  1237. };
  1238. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString );
  1239. } // namespace Catch
  1240. // end catch_assertionhandler.h
  1241. // start catch_message.h
  1242. #include <string>
  1243. namespace Catch {
  1244. struct MessageInfo {
  1245. MessageInfo( std::string const& _macroName,
  1246. SourceLineInfo const& _lineInfo,
  1247. ResultWas::OfType _type );
  1248. std::string macroName;
  1249. std::string message;
  1250. SourceLineInfo lineInfo;
  1251. ResultWas::OfType type;
  1252. unsigned int sequence;
  1253. bool operator == ( MessageInfo const& other ) const;
  1254. bool operator < ( MessageInfo const& other ) const;
  1255. private:
  1256. static unsigned int globalCount;
  1257. };
  1258. struct MessageStream {
  1259. template<typename T>
  1260. MessageStream& operator << ( T const& value ) {
  1261. m_stream << value;
  1262. return *this;
  1263. }
  1264. ReusableStringStream m_stream;
  1265. };
  1266. struct MessageBuilder : MessageStream {
  1267. MessageBuilder( std::string const& macroName,
  1268. SourceLineInfo const& lineInfo,
  1269. ResultWas::OfType type );
  1270. template<typename T>
  1271. MessageBuilder& operator << ( T const& value ) {
  1272. m_stream << value;
  1273. return *this;
  1274. }
  1275. MessageInfo m_info;
  1276. };
  1277. class ScopedMessage {
  1278. public:
  1279. explicit ScopedMessage( MessageBuilder const& builder );
  1280. ~ScopedMessage();
  1281. MessageInfo m_info;
  1282. };
  1283. } // end namespace Catch
  1284. // end catch_message.h
  1285. #if !defined(CATCH_CONFIG_DISABLE)
  1286. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  1287. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  1288. #else
  1289. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  1290. #endif
  1291. #if defined(CATCH_CONFIG_FAST_COMPILE)
  1292. ///////////////////////////////////////////////////////////////////////////////
  1293. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  1294. // macros.
  1295. #define INTERNAL_CATCH_TRY
  1296. #define INTERNAL_CATCH_CATCH( capturer )
  1297. #else // CATCH_CONFIG_FAST_COMPILE
  1298. #define INTERNAL_CATCH_TRY try
  1299. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  1300. #endif
  1301. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  1302. ///////////////////////////////////////////////////////////////////////////////
  1303. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  1304. do { \
  1305. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1306. INTERNAL_CATCH_TRY { \
  1307. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  1308. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  1309. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  1310. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1311. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1312. } 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
  1313. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  1314. ///////////////////////////////////////////////////////////////////////////////
  1315. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  1316. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1317. if( Catch::getResultCapture().lastAssertionPassed() )
  1318. ///////////////////////////////////////////////////////////////////////////////
  1319. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  1320. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1321. if( !Catch::getResultCapture().lastAssertionPassed() )
  1322. ///////////////////////////////////////////////////////////////////////////////
  1323. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  1324. do { \
  1325. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1326. try { \
  1327. static_cast<void>(__VA_ARGS__); \
  1328. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  1329. } \
  1330. catch( ... ) { \
  1331. catchAssertionHandler.handleUnexpectedInflightException(); \
  1332. } \
  1333. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1334. } while( false )
  1335. ///////////////////////////////////////////////////////////////////////////////
  1336. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  1337. do { \
  1338. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  1339. if( catchAssertionHandler.allowThrows() ) \
  1340. try { \
  1341. static_cast<void>(__VA_ARGS__); \
  1342. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1343. } \
  1344. catch( ... ) { \
  1345. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1346. } \
  1347. else \
  1348. catchAssertionHandler.handleThrowingCallSkipped(); \
  1349. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1350. } while( false )
  1351. ///////////////////////////////////////////////////////////////////////////////
  1352. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  1353. do { \
  1354. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  1355. if( catchAssertionHandler.allowThrows() ) \
  1356. try { \
  1357. static_cast<void>(expr); \
  1358. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1359. } \
  1360. catch( exceptionType const& ) { \
  1361. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1362. } \
  1363. catch( ... ) { \
  1364. catchAssertionHandler.handleUnexpectedInflightException(); \
  1365. } \
  1366. else \
  1367. catchAssertionHandler.handleThrowingCallSkipped(); \
  1368. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1369. } while( false )
  1370. ///////////////////////////////////////////////////////////////////////////////
  1371. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  1372. do { \
  1373. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
  1374. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  1375. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1376. } while( false )
  1377. ///////////////////////////////////////////////////////////////////////////////
  1378. #define INTERNAL_CATCH_INFO( macroName, log ) \
  1379. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  1380. ///////////////////////////////////////////////////////////////////////////////
  1381. // Although this is matcher-based, it can be used with just a string
  1382. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  1383. do { \
  1384. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1385. if( catchAssertionHandler.allowThrows() ) \
  1386. try { \
  1387. static_cast<void>(__VA_ARGS__); \
  1388. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1389. } \
  1390. catch( ... ) { \
  1391. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher ); \
  1392. } \
  1393. else \
  1394. catchAssertionHandler.handleThrowingCallSkipped(); \
  1395. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1396. } while( false )
  1397. #endif // CATCH_CONFIG_DISABLE
  1398. // end catch_capture.hpp
  1399. // start catch_section.h
  1400. // start catch_section_info.h
  1401. // start catch_totals.h
  1402. #include <cstddef>
  1403. namespace Catch {
  1404. struct Counts {
  1405. Counts operator - ( Counts const& other ) const;
  1406. Counts& operator += ( Counts const& other );
  1407. std::size_t total() const;
  1408. bool allPassed() const;
  1409. bool allOk() const;
  1410. std::size_t passed = 0;
  1411. std::size_t failed = 0;
  1412. std::size_t failedButOk = 0;
  1413. };
  1414. struct Totals {
  1415. Totals operator - ( Totals const& other ) const;
  1416. Totals& operator += ( Totals const& other );
  1417. Totals delta( Totals const& prevTotals ) const;
  1418. Counts assertions;
  1419. Counts testCases;
  1420. };
  1421. }
  1422. // end catch_totals.h
  1423. #include <string>
  1424. namespace Catch {
  1425. struct SectionInfo {
  1426. SectionInfo
  1427. ( SourceLineInfo const& _lineInfo,
  1428. std::string const& _name,
  1429. std::string const& _description = std::string() );
  1430. std::string name;
  1431. std::string description;
  1432. SourceLineInfo lineInfo;
  1433. };
  1434. struct SectionEndInfo {
  1435. SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds );
  1436. SectionInfo sectionInfo;
  1437. Counts prevAssertions;
  1438. double durationInSeconds;
  1439. };
  1440. } // end namespace Catch
  1441. // end catch_section_info.h
  1442. // start catch_timer.h
  1443. #include <cstdint>
  1444. namespace Catch {
  1445. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  1446. auto getEstimatedClockResolution() -> uint64_t;
  1447. class Timer {
  1448. uint64_t m_nanoseconds = 0;
  1449. public:
  1450. void start();
  1451. auto getElapsedNanoseconds() const -> uint64_t;
  1452. auto getElapsedMicroseconds() const -> uint64_t;
  1453. auto getElapsedMilliseconds() const -> unsigned int;
  1454. auto getElapsedSeconds() const -> double;
  1455. };
  1456. } // namespace Catch
  1457. // end catch_timer.h
  1458. #include <string>
  1459. namespace Catch {
  1460. class Section : NonCopyable {
  1461. public:
  1462. Section( SectionInfo const& info );
  1463. ~Section();
  1464. // This indicates whether the section should be executed or not
  1465. explicit operator bool() const;
  1466. private:
  1467. SectionInfo m_info;
  1468. std::string m_name;
  1469. Counts m_assertions;
  1470. bool m_sectionIncluded;
  1471. Timer m_timer;
  1472. };
  1473. } // end namespace Catch
  1474. #define INTERNAL_CATCH_SECTION( ... ) \
  1475. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) )
  1476. // end catch_section.h
  1477. // start catch_benchmark.h
  1478. #include <cstdint>
  1479. #include <string>
  1480. namespace Catch {
  1481. class BenchmarkLooper {
  1482. std::string m_name;
  1483. std::size_t m_count = 0;
  1484. std::size_t m_iterationsToRun = 1;
  1485. uint64_t m_resolution;
  1486. Timer m_timer;
  1487. static auto getResolution() -> uint64_t;
  1488. public:
  1489. // Keep most of this inline as it's on the code path that is being timed
  1490. BenchmarkLooper( StringRef name )
  1491. : m_name( name ),
  1492. m_resolution( getResolution() )
  1493. {
  1494. reportStart();
  1495. m_timer.start();
  1496. }
  1497. explicit operator bool() {
  1498. if( m_count < m_iterationsToRun )
  1499. return true;
  1500. return needsMoreIterations();
  1501. }
  1502. void increment() {
  1503. ++m_count;
  1504. }
  1505. void reportStart();
  1506. auto needsMoreIterations() -> bool;
  1507. };
  1508. } // end namespace Catch
  1509. #define BENCHMARK( name ) \
  1510. for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )
  1511. // end catch_benchmark.h
  1512. // start catch_interfaces_exception.h
  1513. // start catch_interfaces_registry_hub.h
  1514. #include <string>
  1515. #include <memory>
  1516. namespace Catch {
  1517. class TestCase;
  1518. struct ITestCaseRegistry;
  1519. struct IExceptionTranslatorRegistry;
  1520. struct IExceptionTranslator;
  1521. struct IReporterRegistry;
  1522. struct IReporterFactory;
  1523. struct ITagAliasRegistry;
  1524. class StartupExceptionRegistry;
  1525. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  1526. struct IRegistryHub {
  1527. virtual ~IRegistryHub();
  1528. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  1529. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  1530. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  1531. virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0;
  1532. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  1533. };
  1534. struct IMutableRegistryHub {
  1535. virtual ~IMutableRegistryHub();
  1536. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  1537. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  1538. virtual void registerTest( TestCase const& testInfo ) = 0;
  1539. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  1540. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  1541. virtual void registerStartupException() noexcept = 0;
  1542. };
  1543. IRegistryHub& getRegistryHub();
  1544. IMutableRegistryHub& getMutableRegistryHub();
  1545. void cleanUp();
  1546. std::string translateActiveException();
  1547. }
  1548. // end catch_interfaces_registry_hub.h
  1549. #if defined(CATCH_CONFIG_DISABLE)
  1550. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  1551. static std::string translatorName( signature )
  1552. #endif
  1553. #include <exception>
  1554. #include <string>
  1555. #include <vector>
  1556. namespace Catch {
  1557. using exceptionTranslateFunction = std::string(*)();
  1558. struct IExceptionTranslator;
  1559. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  1560. struct IExceptionTranslator {
  1561. virtual ~IExceptionTranslator();
  1562. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  1563. };
  1564. struct IExceptionTranslatorRegistry {
  1565. virtual ~IExceptionTranslatorRegistry();
  1566. virtual std::string translateActiveException() const = 0;
  1567. };
  1568. class ExceptionTranslatorRegistrar {
  1569. template<typename T>
  1570. class ExceptionTranslator : public IExceptionTranslator {
  1571. public:
  1572. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  1573. : m_translateFunction( translateFunction )
  1574. {}
  1575. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  1576. try {
  1577. if( it == itEnd )
  1578. std::rethrow_exception(std::current_exception());
  1579. else
  1580. return (*it)->translate( it+1, itEnd );
  1581. }
  1582. catch( T& ex ) {
  1583. return m_translateFunction( ex );
  1584. }
  1585. }
  1586. protected:
  1587. std::string(*m_translateFunction)( T& );
  1588. };
  1589. public:
  1590. template<typename T>
  1591. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  1592. getMutableRegistryHub().registerTranslator
  1593. ( new ExceptionTranslator<T>( translateFunction ) );
  1594. }
  1595. };
  1596. }
  1597. ///////////////////////////////////////////////////////////////////////////////
  1598. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  1599. static std::string translatorName( signature ); \
  1600. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1601. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  1602. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1603. static std::string translatorName( signature )
  1604. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  1605. // end catch_interfaces_exception.h
  1606. // start catch_approx.h
  1607. #include <type_traits>
  1608. #include <stdexcept>
  1609. namespace Catch {
  1610. namespace Detail {
  1611. class Approx {
  1612. private:
  1613. bool equalityComparisonImpl(double other) const;
  1614. public:
  1615. explicit Approx ( double value );
  1616. static Approx custom();
  1617. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1618. Approx operator()( T const& value ) {
  1619. Approx approx( static_cast<double>(value) );
  1620. approx.epsilon( m_epsilon );
  1621. approx.margin( m_margin );
  1622. approx.scale( m_scale );
  1623. return approx;
  1624. }
  1625. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1626. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  1627. {}
  1628. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1629. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  1630. auto lhs_v = static_cast<double>(lhs);
  1631. return rhs.equalityComparisonImpl(lhs_v);
  1632. }
  1633. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1634. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  1635. return operator==( rhs, lhs );
  1636. }
  1637. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1638. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  1639. return !operator==( lhs, rhs );
  1640. }
  1641. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1642. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  1643. return !operator==( rhs, lhs );
  1644. }
  1645. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1646. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  1647. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  1648. }
  1649. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1650. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  1651. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  1652. }
  1653. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1654. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  1655. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  1656. }
  1657. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1658. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  1659. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  1660. }
  1661. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1662. Approx& epsilon( T const& newEpsilon ) {
  1663. double epsilonAsDouble = static_cast<double>(newEpsilon);
  1664. if( epsilonAsDouble < 0 || epsilonAsDouble > 1.0 ) {
  1665. throw std::domain_error
  1666. ( "Invalid Approx::epsilon: " +
  1667. Catch::Detail::stringify( epsilonAsDouble ) +
  1668. ", Approx::epsilon has to be between 0 and 1" );
  1669. }
  1670. m_epsilon = epsilonAsDouble;
  1671. return *this;
  1672. }
  1673. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1674. Approx& margin( T const& newMargin ) {
  1675. double marginAsDouble = static_cast<double>(newMargin);
  1676. if( marginAsDouble < 0 ) {
  1677. throw std::domain_error
  1678. ( "Invalid Approx::margin: " +
  1679. Catch::Detail::stringify( marginAsDouble ) +
  1680. ", Approx::Margin has to be non-negative." );
  1681. }
  1682. m_margin = marginAsDouble;
  1683. return *this;
  1684. }
  1685. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1686. Approx& scale( T const& newScale ) {
  1687. m_scale = static_cast<double>(newScale);
  1688. return *this;
  1689. }
  1690. std::string toString() const;
  1691. private:
  1692. double m_epsilon;
  1693. double m_margin;
  1694. double m_scale;
  1695. double m_value;
  1696. };
  1697. }
  1698. template<>
  1699. struct StringMaker<Catch::Detail::Approx> {
  1700. static std::string convert(Catch::Detail::Approx const& value);
  1701. };
  1702. } // end namespace Catch
  1703. // end catch_approx.h
  1704. // start catch_string_manip.h
  1705. #include <string>
  1706. #include <iosfwd>
  1707. namespace Catch {
  1708. bool startsWith( std::string const& s, std::string const& prefix );
  1709. bool startsWith( std::string const& s, char prefix );
  1710. bool endsWith( std::string const& s, std::string const& suffix );
  1711. bool endsWith( std::string const& s, char suffix );
  1712. bool contains( std::string const& s, std::string const& infix );
  1713. void toLowerInPlace( std::string& s );
  1714. std::string toLower( std::string const& s );
  1715. std::string trim( std::string const& str );
  1716. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  1717. struct pluralise {
  1718. pluralise( std::size_t count, std::string const& label );
  1719. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  1720. std::size_t m_count;
  1721. std::string m_label;
  1722. };
  1723. }
  1724. // end catch_string_manip.h
  1725. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  1726. // start catch_capture_matchers.h
  1727. // start catch_matchers.h
  1728. #include <string>
  1729. #include <vector>
  1730. namespace Catch {
  1731. namespace Matchers {
  1732. namespace Impl {
  1733. template<typename ArgT> struct MatchAllOf;
  1734. template<typename ArgT> struct MatchAnyOf;
  1735. template<typename ArgT> struct MatchNotOf;
  1736. class MatcherUntypedBase {
  1737. public:
  1738. MatcherUntypedBase() = default;
  1739. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  1740. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  1741. std::string toString() const;
  1742. protected:
  1743. virtual ~MatcherUntypedBase();
  1744. virtual std::string describe() const = 0;
  1745. mutable std::string m_cachedToString;
  1746. };
  1747. template<typename ObjectT>
  1748. struct MatcherMethod {
  1749. virtual bool match( ObjectT const& arg ) const = 0;
  1750. };
  1751. template<typename PtrT>
  1752. struct MatcherMethod<PtrT*> {
  1753. virtual bool match( PtrT* arg ) const = 0;
  1754. };
  1755. template<typename T>
  1756. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  1757. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  1758. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  1759. MatchNotOf<T> operator ! () const;
  1760. };
  1761. template<typename ArgT>
  1762. struct MatchAllOf : MatcherBase<ArgT> {
  1763. bool match( ArgT const& arg ) const override {
  1764. for( auto matcher : m_matchers ) {
  1765. if (!matcher->match(arg))
  1766. return false;
  1767. }
  1768. return true;
  1769. }
  1770. std::string describe() const override {
  1771. std::string description;
  1772. description.reserve( 4 + m_matchers.size()*32 );
  1773. description += "( ";
  1774. bool first = true;
  1775. for( auto matcher : m_matchers ) {
  1776. if( first )
  1777. first = false;
  1778. else
  1779. description += " and ";
  1780. description += matcher->toString();
  1781. }
  1782. description += " )";
  1783. return description;
  1784. }
  1785. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  1786. m_matchers.push_back( &other );
  1787. return *this;
  1788. }
  1789. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1790. };
  1791. template<typename ArgT>
  1792. struct MatchAnyOf : MatcherBase<ArgT> {
  1793. bool match( ArgT const& arg ) const override {
  1794. for( auto matcher : m_matchers ) {
  1795. if (matcher->match(arg))
  1796. return true;
  1797. }
  1798. return false;
  1799. }
  1800. std::string describe() const override {
  1801. std::string description;
  1802. description.reserve( 4 + m_matchers.size()*32 );
  1803. description += "( ";
  1804. bool first = true;
  1805. for( auto matcher : m_matchers ) {
  1806. if( first )
  1807. first = false;
  1808. else
  1809. description += " or ";
  1810. description += matcher->toString();
  1811. }
  1812. description += " )";
  1813. return description;
  1814. }
  1815. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  1816. m_matchers.push_back( &other );
  1817. return *this;
  1818. }
  1819. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1820. };
  1821. template<typename ArgT>
  1822. struct MatchNotOf : MatcherBase<ArgT> {
  1823. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  1824. bool match( ArgT const& arg ) const override {
  1825. return !m_underlyingMatcher.match( arg );
  1826. }
  1827. std::string describe() const override {
  1828. return "not " + m_underlyingMatcher.toString();
  1829. }
  1830. MatcherBase<ArgT> const& m_underlyingMatcher;
  1831. };
  1832. template<typename T>
  1833. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  1834. return MatchAllOf<T>() && *this && other;
  1835. }
  1836. template<typename T>
  1837. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  1838. return MatchAnyOf<T>() || *this || other;
  1839. }
  1840. template<typename T>
  1841. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  1842. return MatchNotOf<T>( *this );
  1843. }
  1844. } // namespace Impl
  1845. } // namespace Matchers
  1846. using namespace Matchers;
  1847. using Matchers::Impl::MatcherBase;
  1848. } // namespace Catch
  1849. // end catch_matchers.h
  1850. // start catch_matchers_floating.h
  1851. #include <type_traits>
  1852. #include <cmath>
  1853. namespace Catch {
  1854. namespace Matchers {
  1855. namespace Floating {
  1856. enum class FloatingPointKind : uint8_t;
  1857. struct WithinAbsMatcher : MatcherBase<double> {
  1858. WithinAbsMatcher(double target, double margin);
  1859. bool match(double const& matchee) const override;
  1860. std::string describe() const override;
  1861. private:
  1862. double m_target;
  1863. double m_margin;
  1864. };
  1865. struct WithinUlpsMatcher : MatcherBase<double> {
  1866. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  1867. bool match(double const& matchee) const override;
  1868. std::string describe() const override;
  1869. private:
  1870. double m_target;
  1871. int m_ulps;
  1872. FloatingPointKind m_type;
  1873. };
  1874. } // namespace Floating
  1875. // The following functions create the actual matcher objects.
  1876. // This allows the types to be inferred
  1877. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  1878. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  1879. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  1880. } // namespace Matchers
  1881. } // namespace Catch
  1882. // end catch_matchers_floating.h
  1883. // start catch_matchers_string.h
  1884. #include <string>
  1885. namespace Catch {
  1886. namespace Matchers {
  1887. namespace StdString {
  1888. struct CasedString
  1889. {
  1890. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  1891. std::string adjustString( std::string const& str ) const;
  1892. std::string caseSensitivitySuffix() const;
  1893. CaseSensitive::Choice m_caseSensitivity;
  1894. std::string m_str;
  1895. };
  1896. struct StringMatcherBase : MatcherBase<std::string> {
  1897. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  1898. std::string describe() const override;
  1899. CasedString m_comparator;
  1900. std::string m_operation;
  1901. };
  1902. struct EqualsMatcher : StringMatcherBase {
  1903. EqualsMatcher( CasedString const& comparator );
  1904. bool match( std::string const& source ) const override;
  1905. };
  1906. struct ContainsMatcher : StringMatcherBase {
  1907. ContainsMatcher( CasedString const& comparator );
  1908. bool match( std::string const& source ) const override;
  1909. };
  1910. struct StartsWithMatcher : StringMatcherBase {
  1911. StartsWithMatcher( CasedString const& comparator );
  1912. bool match( std::string const& source ) const override;
  1913. };
  1914. struct EndsWithMatcher : StringMatcherBase {
  1915. EndsWithMatcher( CasedString const& comparator );
  1916. bool match( std::string const& source ) const override;
  1917. };
  1918. struct RegexMatcher : MatcherBase<std::string> {
  1919. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  1920. bool match( std::string const& matchee ) const override;
  1921. std::string describe() const override;
  1922. private:
  1923. std::string m_regex;
  1924. CaseSensitive::Choice m_caseSensitivity;
  1925. };
  1926. } // namespace StdString
  1927. // The following functions create the actual matcher objects.
  1928. // This allows the types to be inferred
  1929. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1930. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1931. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1932. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1933. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1934. } // namespace Matchers
  1935. } // namespace Catch
  1936. // end catch_matchers_string.h
  1937. // start catch_matchers_vector.h
  1938. #include <algorithm>
  1939. namespace Catch {
  1940. namespace Matchers {
  1941. namespace Vector {
  1942. namespace Detail {
  1943. template <typename InputIterator, typename T>
  1944. size_t count(InputIterator first, InputIterator last, T const& item) {
  1945. size_t cnt = 0;
  1946. for (; first != last; ++first) {
  1947. if (*first == item) {
  1948. ++cnt;
  1949. }
  1950. }
  1951. return cnt;
  1952. }
  1953. template <typename InputIterator, typename T>
  1954. bool contains(InputIterator first, InputIterator last, T const& item) {
  1955. for (; first != last; ++first) {
  1956. if (*first == item) {
  1957. return true;
  1958. }
  1959. }
  1960. return false;
  1961. }
  1962. }
  1963. template<typename T>
  1964. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  1965. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  1966. bool match(std::vector<T> const &v) const override {
  1967. for (auto const& el : v) {
  1968. if (el == m_comparator) {
  1969. return true;
  1970. }
  1971. }
  1972. return false;
  1973. }
  1974. std::string describe() const override {
  1975. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  1976. }
  1977. T const& m_comparator;
  1978. };
  1979. template<typename T>
  1980. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  1981. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  1982. bool match(std::vector<T> const &v) const override {
  1983. // !TBD: see note in EqualsMatcher
  1984. if (m_comparator.size() > v.size())
  1985. return false;
  1986. for (auto const& comparator : m_comparator) {
  1987. auto present = false;
  1988. for (const auto& el : v) {
  1989. if (el == comparator) {
  1990. present = true;
  1991. break;
  1992. }
  1993. }
  1994. if (!present) {
  1995. return false;
  1996. }
  1997. }
  1998. return true;
  1999. }
  2000. std::string describe() const override {
  2001. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2002. }
  2003. std::vector<T> const& m_comparator;
  2004. };
  2005. template<typename T>
  2006. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  2007. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2008. bool match(std::vector<T> const &v) const override {
  2009. // !TBD: This currently works if all elements can be compared using !=
  2010. // - a more general approach would be via a compare template that defaults
  2011. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  2012. // - then just call that directly
  2013. if (m_comparator.size() != v.size())
  2014. return false;
  2015. for (std::size_t i = 0; i < v.size(); ++i)
  2016. if (m_comparator[i] != v[i])
  2017. return false;
  2018. return true;
  2019. }
  2020. std::string describe() const override {
  2021. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2022. }
  2023. std::vector<T> const& m_comparator;
  2024. };
  2025. template<typename T>
  2026. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2027. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2028. bool match(std::vector<T> const& vec) const override {
  2029. // Note: This is a reimplementation of std::is_permutation,
  2030. // because I don't want to include <algorithm> inside the common path
  2031. if (m_target.size() != vec.size()) {
  2032. return false;
  2033. }
  2034. auto lfirst = m_target.begin(), llast = m_target.end();
  2035. auto rfirst = vec.begin(), rlast = vec.end();
  2036. // Cut common prefix to optimize checking of permuted parts
  2037. while (lfirst != llast && *lfirst != *rfirst) {
  2038. ++lfirst; ++rfirst;
  2039. }
  2040. if (lfirst == llast) {
  2041. return true;
  2042. }
  2043. for (auto mid = lfirst; mid != llast; ++mid) {
  2044. // Skip already counted items
  2045. if (Detail::contains(lfirst, mid, *mid)) {
  2046. continue;
  2047. }
  2048. size_t num_vec = Detail::count(rfirst, rlast, *mid);
  2049. if (num_vec == 0 || Detail::count(lfirst, llast, *mid) != num_vec) {
  2050. return false;
  2051. }
  2052. }
  2053. return true;
  2054. }
  2055. std::string describe() const override {
  2056. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  2057. }
  2058. private:
  2059. std::vector<T> const& m_target;
  2060. };
  2061. } // namespace Vector
  2062. // The following functions create the actual matcher objects.
  2063. // This allows the types to be inferred
  2064. template<typename T>
  2065. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  2066. return Vector::ContainsMatcher<T>( comparator );
  2067. }
  2068. template<typename T>
  2069. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  2070. return Vector::ContainsElementMatcher<T>( comparator );
  2071. }
  2072. template<typename T>
  2073. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  2074. return Vector::EqualsMatcher<T>( comparator );
  2075. }
  2076. template<typename T>
  2077. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  2078. return Vector::UnorderedEqualsMatcher<T>(target);
  2079. }
  2080. } // namespace Matchers
  2081. } // namespace Catch
  2082. // end catch_matchers_vector.h
  2083. namespace Catch {
  2084. template<typename ArgT, typename MatcherT>
  2085. class MatchExpr : public ITransientExpression {
  2086. ArgT const& m_arg;
  2087. MatcherT m_matcher;
  2088. StringRef m_matcherString;
  2089. public:
  2090. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString )
  2091. : ITransientExpression{ true, matcher.match( arg ) },
  2092. m_arg( arg ),
  2093. m_matcher( matcher ),
  2094. m_matcherString( matcherString )
  2095. {}
  2096. void streamReconstructedExpression( std::ostream &os ) const override {
  2097. auto matcherAsString = m_matcher.toString();
  2098. os << Catch::Detail::stringify( m_arg ) << ' ';
  2099. if( matcherAsString == Detail::unprintableString )
  2100. os << m_matcherString;
  2101. else
  2102. os << matcherAsString;
  2103. }
  2104. };
  2105. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  2106. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString );
  2107. template<typename ArgT, typename MatcherT>
  2108. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString ) -> MatchExpr<ArgT, MatcherT> {
  2109. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  2110. }
  2111. } // namespace Catch
  2112. ///////////////////////////////////////////////////////////////////////////////
  2113. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  2114. do { \
  2115. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2116. INTERNAL_CATCH_TRY { \
  2117. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher ) ); \
  2118. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2119. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2120. } while( false )
  2121. ///////////////////////////////////////////////////////////////////////////////
  2122. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  2123. do { \
  2124. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2125. if( catchAssertionHandler.allowThrows() ) \
  2126. try { \
  2127. static_cast<void>(__VA_ARGS__ ); \
  2128. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2129. } \
  2130. catch( exceptionType const& ex ) { \
  2131. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher ) ); \
  2132. } \
  2133. catch( ... ) { \
  2134. catchAssertionHandler.handleUnexpectedInflightException(); \
  2135. } \
  2136. else \
  2137. catchAssertionHandler.handleThrowingCallSkipped(); \
  2138. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2139. } while( false )
  2140. // end catch_capture_matchers.h
  2141. #endif
  2142. // These files are included here so the single_include script doesn't put them
  2143. // in the conditionally compiled sections
  2144. // start catch_test_case_info.h
  2145. #include <string>
  2146. #include <vector>
  2147. #include <memory>
  2148. #ifdef __clang__
  2149. #pragma clang diagnostic push
  2150. #pragma clang diagnostic ignored "-Wpadded"
  2151. #endif
  2152. namespace Catch {
  2153. struct ITestInvoker;
  2154. struct TestCaseInfo {
  2155. enum SpecialProperties{
  2156. None = 0,
  2157. IsHidden = 1 << 1,
  2158. ShouldFail = 1 << 2,
  2159. MayFail = 1 << 3,
  2160. Throws = 1 << 4,
  2161. NonPortable = 1 << 5,
  2162. Benchmark = 1 << 6
  2163. };
  2164. TestCaseInfo( std::string const& _name,
  2165. std::string const& _className,
  2166. std::string const& _description,
  2167. std::vector<std::string> const& _tags,
  2168. SourceLineInfo const& _lineInfo );
  2169. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  2170. bool isHidden() const;
  2171. bool throws() const;
  2172. bool okToFail() const;
  2173. bool expectedToFail() const;
  2174. std::string tagsAsString() const;
  2175. std::string name;
  2176. std::string className;
  2177. std::string description;
  2178. std::vector<std::string> tags;
  2179. std::vector<std::string> lcaseTags;
  2180. SourceLineInfo lineInfo;
  2181. SpecialProperties properties;
  2182. };
  2183. class TestCase : public TestCaseInfo {
  2184. public:
  2185. TestCase( ITestInvoker* testCase, TestCaseInfo const& info );
  2186. TestCase withName( std::string const& _newName ) const;
  2187. void invoke() const;
  2188. TestCaseInfo const& getTestCaseInfo() const;
  2189. bool operator == ( TestCase const& other ) const;
  2190. bool operator < ( TestCase const& other ) const;
  2191. private:
  2192. std::shared_ptr<ITestInvoker> test;
  2193. };
  2194. TestCase makeTestCase( ITestInvoker* testCase,
  2195. std::string const& className,
  2196. std::string const& name,
  2197. std::string const& description,
  2198. SourceLineInfo const& lineInfo );
  2199. }
  2200. #ifdef __clang__
  2201. #pragma clang diagnostic pop
  2202. #endif
  2203. // end catch_test_case_info.h
  2204. // start catch_interfaces_runner.h
  2205. namespace Catch {
  2206. struct IRunner {
  2207. virtual ~IRunner();
  2208. virtual bool aborting() const = 0;
  2209. };
  2210. }
  2211. // end catch_interfaces_runner.h
  2212. #ifdef __OBJC__
  2213. // start catch_objc.hpp
  2214. #import <objc/runtime.h>
  2215. #include <string>
  2216. // NB. Any general catch headers included here must be included
  2217. // in catch.hpp first to make sure they are included by the single
  2218. // header for non obj-usage
  2219. ///////////////////////////////////////////////////////////////////////////////
  2220. // This protocol is really only here for (self) documenting purposes, since
  2221. // all its methods are optional.
  2222. @protocol OcFixture
  2223. @optional
  2224. -(void) setUp;
  2225. -(void) tearDown;
  2226. @end
  2227. namespace Catch {
  2228. class OcMethod : public ITestInvoker {
  2229. public:
  2230. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  2231. virtual void invoke() const {
  2232. id obj = [[m_cls alloc] init];
  2233. performOptionalSelector( obj, @selector(setUp) );
  2234. performOptionalSelector( obj, m_sel );
  2235. performOptionalSelector( obj, @selector(tearDown) );
  2236. arcSafeRelease( obj );
  2237. }
  2238. private:
  2239. virtual ~OcMethod() {}
  2240. Class m_cls;
  2241. SEL m_sel;
  2242. };
  2243. namespace Detail{
  2244. inline std::string getAnnotation( Class cls,
  2245. std::string const& annotationName,
  2246. std::string const& testCaseName ) {
  2247. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  2248. SEL sel = NSSelectorFromString( selStr );
  2249. arcSafeRelease( selStr );
  2250. id value = performOptionalSelector( cls, sel );
  2251. if( value )
  2252. return [(NSString*)value UTF8String];
  2253. return "";
  2254. }
  2255. }
  2256. inline std::size_t registerTestMethods() {
  2257. std::size_t noTestMethods = 0;
  2258. int noClasses = objc_getClassList( nullptr, 0 );
  2259. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  2260. objc_getClassList( classes, noClasses );
  2261. for( int c = 0; c < noClasses; c++ ) {
  2262. Class cls = classes[c];
  2263. {
  2264. u_int count;
  2265. Method* methods = class_copyMethodList( cls, &count );
  2266. for( u_int m = 0; m < count ; m++ ) {
  2267. SEL selector = method_getName(methods[m]);
  2268. std::string methodName = sel_getName(selector);
  2269. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  2270. std::string testCaseName = methodName.substr( 15 );
  2271. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  2272. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  2273. const char* className = class_getName( cls );
  2274. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo("",0) ) );
  2275. noTestMethods++;
  2276. }
  2277. }
  2278. free(methods);
  2279. }
  2280. }
  2281. return noTestMethods;
  2282. }
  2283. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  2284. namespace Matchers {
  2285. namespace Impl {
  2286. namespace NSStringMatchers {
  2287. struct StringHolder : MatcherBase<NSString*>{
  2288. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  2289. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  2290. StringHolder() {
  2291. arcSafeRelease( m_substr );
  2292. }
  2293. bool match( NSString* arg ) const override {
  2294. return false;
  2295. }
  2296. NSString* CATCH_ARC_STRONG m_substr;
  2297. };
  2298. struct Equals : StringHolder {
  2299. Equals( NSString* substr ) : StringHolder( substr ){}
  2300. bool match( NSString* str ) const override {
  2301. return (str != nil || m_substr == nil ) &&
  2302. [str isEqualToString:m_substr];
  2303. }
  2304. std::string describe() const override {
  2305. return "equals string: " + Catch::Detail::stringify( m_substr );
  2306. }
  2307. };
  2308. struct Contains : StringHolder {
  2309. Contains( NSString* substr ) : StringHolder( substr ){}
  2310. bool match( NSString* str ) const {
  2311. return (str != nil || m_substr == nil ) &&
  2312. [str rangeOfString:m_substr].location != NSNotFound;
  2313. }
  2314. std::string describe() const override {
  2315. return "contains string: " + Catch::Detail::stringify( m_substr );
  2316. }
  2317. };
  2318. struct StartsWith : StringHolder {
  2319. StartsWith( NSString* substr ) : StringHolder( substr ){}
  2320. bool match( NSString* str ) const override {
  2321. return (str != nil || m_substr == nil ) &&
  2322. [str rangeOfString:m_substr].location == 0;
  2323. }
  2324. std::string describe() const override {
  2325. return "starts with: " + Catch::Detail::stringify( m_substr );
  2326. }
  2327. };
  2328. struct EndsWith : StringHolder {
  2329. EndsWith( NSString* substr ) : StringHolder( substr ){}
  2330. bool match( NSString* str ) const override {
  2331. return (str != nil || m_substr == nil ) &&
  2332. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  2333. }
  2334. std::string describe() const override {
  2335. return "ends with: " + Catch::Detail::stringify( m_substr );
  2336. }
  2337. };
  2338. } // namespace NSStringMatchers
  2339. } // namespace Impl
  2340. inline Impl::NSStringMatchers::Equals
  2341. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  2342. inline Impl::NSStringMatchers::Contains
  2343. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  2344. inline Impl::NSStringMatchers::StartsWith
  2345. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  2346. inline Impl::NSStringMatchers::EndsWith
  2347. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  2348. } // namespace Matchers
  2349. using namespace Matchers;
  2350. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  2351. } // namespace Catch
  2352. ///////////////////////////////////////////////////////////////////////////////
  2353. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  2354. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  2355. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  2356. { \
  2357. return @ name; \
  2358. } \
  2359. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  2360. { \
  2361. return @ desc; \
  2362. } \
  2363. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  2364. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  2365. // end catch_objc.hpp
  2366. #endif
  2367. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  2368. // start catch_external_interfaces.h
  2369. // start catch_reporter_bases.hpp
  2370. // start catch_interfaces_reporter.h
  2371. // start catch_config.hpp
  2372. // start catch_test_spec_parser.h
  2373. #ifdef __clang__
  2374. #pragma clang diagnostic push
  2375. #pragma clang diagnostic ignored "-Wpadded"
  2376. #endif
  2377. // start catch_test_spec.h
  2378. #ifdef __clang__
  2379. #pragma clang diagnostic push
  2380. #pragma clang diagnostic ignored "-Wpadded"
  2381. #endif
  2382. // start catch_wildcard_pattern.h
  2383. namespace Catch
  2384. {
  2385. class WildcardPattern {
  2386. enum WildcardPosition {
  2387. NoWildcard = 0,
  2388. WildcardAtStart = 1,
  2389. WildcardAtEnd = 2,
  2390. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  2391. };
  2392. public:
  2393. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  2394. virtual ~WildcardPattern() = default;
  2395. virtual bool matches( std::string const& str ) const;
  2396. private:
  2397. std::string adjustCase( std::string const& str ) const;
  2398. CaseSensitive::Choice m_caseSensitivity;
  2399. WildcardPosition m_wildcard = NoWildcard;
  2400. std::string m_pattern;
  2401. };
  2402. }
  2403. // end catch_wildcard_pattern.h
  2404. #include <string>
  2405. #include <vector>
  2406. #include <memory>
  2407. namespace Catch {
  2408. class TestSpec {
  2409. struct Pattern {
  2410. virtual ~Pattern();
  2411. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  2412. };
  2413. using PatternPtr = std::shared_ptr<Pattern>;
  2414. class NamePattern : public Pattern {
  2415. public:
  2416. NamePattern( std::string const& name );
  2417. virtual ~NamePattern();
  2418. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2419. private:
  2420. WildcardPattern m_wildcardPattern;
  2421. };
  2422. class TagPattern : public Pattern {
  2423. public:
  2424. TagPattern( std::string const& tag );
  2425. virtual ~TagPattern();
  2426. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2427. private:
  2428. std::string m_tag;
  2429. };
  2430. class ExcludedPattern : public Pattern {
  2431. public:
  2432. ExcludedPattern( PatternPtr const& underlyingPattern );
  2433. virtual ~ExcludedPattern();
  2434. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2435. private:
  2436. PatternPtr m_underlyingPattern;
  2437. };
  2438. struct Filter {
  2439. std::vector<PatternPtr> m_patterns;
  2440. bool matches( TestCaseInfo const& testCase ) const;
  2441. };
  2442. public:
  2443. bool hasFilters() const;
  2444. bool matches( TestCaseInfo const& testCase ) const;
  2445. private:
  2446. std::vector<Filter> m_filters;
  2447. friend class TestSpecParser;
  2448. };
  2449. }
  2450. #ifdef __clang__
  2451. #pragma clang diagnostic pop
  2452. #endif
  2453. // end catch_test_spec.h
  2454. // start catch_interfaces_tag_alias_registry.h
  2455. #include <string>
  2456. namespace Catch {
  2457. struct TagAlias;
  2458. struct ITagAliasRegistry {
  2459. virtual ~ITagAliasRegistry();
  2460. // Nullptr if not present
  2461. virtual TagAlias const* find( std::string const& alias ) const = 0;
  2462. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  2463. static ITagAliasRegistry const& get();
  2464. };
  2465. } // end namespace Catch
  2466. // end catch_interfaces_tag_alias_registry.h
  2467. namespace Catch {
  2468. class TestSpecParser {
  2469. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  2470. Mode m_mode = None;
  2471. bool m_exclusion = false;
  2472. std::size_t m_start = std::string::npos, m_pos = 0;
  2473. std::string m_arg;
  2474. std::vector<std::size_t> m_escapeChars;
  2475. TestSpec::Filter m_currentFilter;
  2476. TestSpec m_testSpec;
  2477. ITagAliasRegistry const* m_tagAliases = nullptr;
  2478. public:
  2479. TestSpecParser( ITagAliasRegistry const& tagAliases );
  2480. TestSpecParser& parse( std::string const& arg );
  2481. TestSpec testSpec();
  2482. private:
  2483. void visitChar( char c );
  2484. void startNewMode( Mode mode, std::size_t start );
  2485. void escape();
  2486. std::string subString() const;
  2487. template<typename T>
  2488. void addPattern() {
  2489. std::string token = subString();
  2490. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  2491. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  2492. m_escapeChars.clear();
  2493. if( startsWith( token, "exclude:" ) ) {
  2494. m_exclusion = true;
  2495. token = token.substr( 8 );
  2496. }
  2497. if( !token.empty() ) {
  2498. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  2499. if( m_exclusion )
  2500. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  2501. m_currentFilter.m_patterns.push_back( pattern );
  2502. }
  2503. m_exclusion = false;
  2504. m_mode = None;
  2505. }
  2506. void addFilter();
  2507. };
  2508. TestSpec parseTestSpec( std::string const& arg );
  2509. } // namespace Catch
  2510. #ifdef __clang__
  2511. #pragma clang diagnostic pop
  2512. #endif
  2513. // end catch_test_spec_parser.h
  2514. // start catch_interfaces_config.h
  2515. #include <iosfwd>
  2516. #include <string>
  2517. #include <vector>
  2518. #include <memory>
  2519. namespace Catch {
  2520. enum class Verbosity {
  2521. Quiet = 0,
  2522. Normal,
  2523. High
  2524. };
  2525. struct WarnAbout { enum What {
  2526. Nothing = 0x00,
  2527. NoAssertions = 0x01
  2528. }; };
  2529. struct ShowDurations { enum OrNot {
  2530. DefaultForReporter,
  2531. Always,
  2532. Never
  2533. }; };
  2534. struct RunTests { enum InWhatOrder {
  2535. InDeclarationOrder,
  2536. InLexicographicalOrder,
  2537. InRandomOrder
  2538. }; };
  2539. struct UseColour { enum YesOrNo {
  2540. Auto,
  2541. Yes,
  2542. No
  2543. }; };
  2544. struct WaitForKeypress { enum When {
  2545. Never,
  2546. BeforeStart = 1,
  2547. BeforeExit = 2,
  2548. BeforeStartAndExit = BeforeStart | BeforeExit
  2549. }; };
  2550. class TestSpec;
  2551. struct IConfig : NonCopyable {
  2552. virtual ~IConfig();
  2553. virtual bool allowThrows() const = 0;
  2554. virtual std::ostream& stream() const = 0;
  2555. virtual std::string name() const = 0;
  2556. virtual bool includeSuccessfulResults() const = 0;
  2557. virtual bool shouldDebugBreak() const = 0;
  2558. virtual bool warnAboutMissingAssertions() const = 0;
  2559. virtual int abortAfter() const = 0;
  2560. virtual bool showInvisibles() const = 0;
  2561. virtual ShowDurations::OrNot showDurations() const = 0;
  2562. virtual TestSpec const& testSpec() const = 0;
  2563. virtual RunTests::InWhatOrder runOrder() const = 0;
  2564. virtual unsigned int rngSeed() const = 0;
  2565. virtual int benchmarkResolutionMultiple() const = 0;
  2566. virtual UseColour::YesOrNo useColour() const = 0;
  2567. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  2568. virtual Verbosity verbosity() const = 0;
  2569. };
  2570. using IConfigPtr = std::shared_ptr<IConfig const>;
  2571. }
  2572. // end catch_interfaces_config.h
  2573. // Libstdc++ doesn't like incomplete classes for unique_ptr
  2574. #include <memory>
  2575. #include <vector>
  2576. #include <string>
  2577. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  2578. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  2579. #endif
  2580. namespace Catch {
  2581. struct IStream;
  2582. struct ConfigData {
  2583. bool listTests = false;
  2584. bool listTags = false;
  2585. bool listReporters = false;
  2586. bool listTestNamesOnly = false;
  2587. bool showSuccessfulTests = false;
  2588. bool shouldDebugBreak = false;
  2589. bool noThrow = false;
  2590. bool showHelp = false;
  2591. bool showInvisibles = false;
  2592. bool filenamesAsTags = false;
  2593. bool libIdentify = false;
  2594. int abortAfter = -1;
  2595. unsigned int rngSeed = 0;
  2596. int benchmarkResolutionMultiple = 100;
  2597. Verbosity verbosity = Verbosity::Normal;
  2598. WarnAbout::What warnings = WarnAbout::Nothing;
  2599. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  2600. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  2601. UseColour::YesOrNo useColour = UseColour::Auto;
  2602. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  2603. std::string outputFilename;
  2604. std::string name;
  2605. std::string processName;
  2606. std::vector<std::string> reporterNames;
  2607. std::vector<std::string> testsOrTags;
  2608. std::vector<std::string> sectionsToRun;
  2609. };
  2610. class Config : public IConfig {
  2611. public:
  2612. Config() = default;
  2613. Config( ConfigData const& data );
  2614. virtual ~Config() = default;
  2615. std::string const& getFilename() const;
  2616. bool listTests() const;
  2617. bool listTestNamesOnly() const;
  2618. bool listTags() const;
  2619. bool listReporters() const;
  2620. std::string getProcessName() const;
  2621. std::vector<std::string> const& getReporterNames() const;
  2622. std::vector<std::string> const& getSectionsToRun() const override;
  2623. virtual TestSpec const& testSpec() const override;
  2624. bool showHelp() const;
  2625. // IConfig interface
  2626. bool allowThrows() const override;
  2627. std::ostream& stream() const override;
  2628. std::string name() const override;
  2629. bool includeSuccessfulResults() const override;
  2630. bool warnAboutMissingAssertions() const override;
  2631. ShowDurations::OrNot showDurations() const override;
  2632. RunTests::InWhatOrder runOrder() const override;
  2633. unsigned int rngSeed() const override;
  2634. int benchmarkResolutionMultiple() const override;
  2635. UseColour::YesOrNo useColour() const override;
  2636. bool shouldDebugBreak() const override;
  2637. int abortAfter() const override;
  2638. bool showInvisibles() const override;
  2639. Verbosity verbosity() const override;
  2640. private:
  2641. IStream const* openStream();
  2642. ConfigData m_data;
  2643. std::unique_ptr<IStream const> m_stream;
  2644. TestSpec m_testSpec;
  2645. };
  2646. } // end namespace Catch
  2647. // end catch_config.hpp
  2648. // start catch_assertionresult.h
  2649. #include <string>
  2650. namespace Catch {
  2651. struct AssertionResultData
  2652. {
  2653. AssertionResultData() = delete;
  2654. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  2655. std::string message;
  2656. mutable std::string reconstructedExpression;
  2657. LazyExpression lazyExpression;
  2658. ResultWas::OfType resultType;
  2659. std::string reconstructExpression() const;
  2660. };
  2661. class AssertionResult {
  2662. public:
  2663. AssertionResult() = delete;
  2664. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  2665. bool isOk() const;
  2666. bool succeeded() const;
  2667. ResultWas::OfType getResultType() const;
  2668. bool hasExpression() const;
  2669. bool hasMessage() const;
  2670. std::string getExpression() const;
  2671. std::string getExpressionInMacro() const;
  2672. bool hasExpandedExpression() const;
  2673. std::string getExpandedExpression() const;
  2674. std::string getMessage() const;
  2675. SourceLineInfo getSourceInfo() const;
  2676. StringRef getTestMacroName() const;
  2677. //protected:
  2678. AssertionInfo m_info;
  2679. AssertionResultData m_resultData;
  2680. };
  2681. } // end namespace Catch
  2682. // end catch_assertionresult.h
  2683. // start catch_option.hpp
  2684. namespace Catch {
  2685. // An optional type
  2686. template<typename T>
  2687. class Option {
  2688. public:
  2689. Option() : nullableValue( nullptr ) {}
  2690. Option( T const& _value )
  2691. : nullableValue( new( storage ) T( _value ) )
  2692. {}
  2693. Option( Option const& _other )
  2694. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  2695. {}
  2696. ~Option() {
  2697. reset();
  2698. }
  2699. Option& operator= ( Option const& _other ) {
  2700. if( &_other != this ) {
  2701. reset();
  2702. if( _other )
  2703. nullableValue = new( storage ) T( *_other );
  2704. }
  2705. return *this;
  2706. }
  2707. Option& operator = ( T const& _value ) {
  2708. reset();
  2709. nullableValue = new( storage ) T( _value );
  2710. return *this;
  2711. }
  2712. void reset() {
  2713. if( nullableValue )
  2714. nullableValue->~T();
  2715. nullableValue = nullptr;
  2716. }
  2717. T& operator*() { return *nullableValue; }
  2718. T const& operator*() const { return *nullableValue; }
  2719. T* operator->() { return nullableValue; }
  2720. const T* operator->() const { return nullableValue; }
  2721. T valueOr( T const& defaultValue ) const {
  2722. return nullableValue ? *nullableValue : defaultValue;
  2723. }
  2724. bool some() const { return nullableValue != nullptr; }
  2725. bool none() const { return nullableValue == nullptr; }
  2726. bool operator !() const { return nullableValue == nullptr; }
  2727. explicit operator bool() const {
  2728. return some();
  2729. }
  2730. private:
  2731. T *nullableValue;
  2732. alignas(alignof(T)) char storage[sizeof(T)];
  2733. };
  2734. } // end namespace Catch
  2735. // end catch_option.hpp
  2736. #include <string>
  2737. #include <iosfwd>
  2738. #include <map>
  2739. #include <set>
  2740. #include <memory>
  2741. namespace Catch {
  2742. struct ReporterConfig {
  2743. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  2744. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  2745. std::ostream& stream() const;
  2746. IConfigPtr fullConfig() const;
  2747. private:
  2748. std::ostream* m_stream;
  2749. IConfigPtr m_fullConfig;
  2750. };
  2751. struct ReporterPreferences {
  2752. bool shouldRedirectStdOut = false;
  2753. };
  2754. template<typename T>
  2755. struct LazyStat : Option<T> {
  2756. LazyStat& operator=( T const& _value ) {
  2757. Option<T>::operator=( _value );
  2758. used = false;
  2759. return *this;
  2760. }
  2761. void reset() {
  2762. Option<T>::reset();
  2763. used = false;
  2764. }
  2765. bool used = false;
  2766. };
  2767. struct TestRunInfo {
  2768. TestRunInfo( std::string const& _name );
  2769. std::string name;
  2770. };
  2771. struct GroupInfo {
  2772. GroupInfo( std::string const& _name,
  2773. std::size_t _groupIndex,
  2774. std::size_t _groupsCount );
  2775. std::string name;
  2776. std::size_t groupIndex;
  2777. std::size_t groupsCounts;
  2778. };
  2779. struct AssertionStats {
  2780. AssertionStats( AssertionResult const& _assertionResult,
  2781. std::vector<MessageInfo> const& _infoMessages,
  2782. Totals const& _totals );
  2783. AssertionStats( AssertionStats const& ) = default;
  2784. AssertionStats( AssertionStats && ) = default;
  2785. AssertionStats& operator = ( AssertionStats const& ) = default;
  2786. AssertionStats& operator = ( AssertionStats && ) = default;
  2787. virtual ~AssertionStats();
  2788. AssertionResult assertionResult;
  2789. std::vector<MessageInfo> infoMessages;
  2790. Totals totals;
  2791. };
  2792. struct SectionStats {
  2793. SectionStats( SectionInfo const& _sectionInfo,
  2794. Counts const& _assertions,
  2795. double _durationInSeconds,
  2796. bool _missingAssertions );
  2797. SectionStats( SectionStats const& ) = default;
  2798. SectionStats( SectionStats && ) = default;
  2799. SectionStats& operator = ( SectionStats const& ) = default;
  2800. SectionStats& operator = ( SectionStats && ) = default;
  2801. virtual ~SectionStats();
  2802. SectionInfo sectionInfo;
  2803. Counts assertions;
  2804. double durationInSeconds;
  2805. bool missingAssertions;
  2806. };
  2807. struct TestCaseStats {
  2808. TestCaseStats( TestCaseInfo const& _testInfo,
  2809. Totals const& _totals,
  2810. std::string const& _stdOut,
  2811. std::string const& _stdErr,
  2812. bool _aborting );
  2813. TestCaseStats( TestCaseStats const& ) = default;
  2814. TestCaseStats( TestCaseStats && ) = default;
  2815. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  2816. TestCaseStats& operator = ( TestCaseStats && ) = default;
  2817. virtual ~TestCaseStats();
  2818. TestCaseInfo testInfo;
  2819. Totals totals;
  2820. std::string stdOut;
  2821. std::string stdErr;
  2822. bool aborting;
  2823. };
  2824. struct TestGroupStats {
  2825. TestGroupStats( GroupInfo const& _groupInfo,
  2826. Totals const& _totals,
  2827. bool _aborting );
  2828. TestGroupStats( GroupInfo const& _groupInfo );
  2829. TestGroupStats( TestGroupStats const& ) = default;
  2830. TestGroupStats( TestGroupStats && ) = default;
  2831. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  2832. TestGroupStats& operator = ( TestGroupStats && ) = default;
  2833. virtual ~TestGroupStats();
  2834. GroupInfo groupInfo;
  2835. Totals totals;
  2836. bool aborting;
  2837. };
  2838. struct TestRunStats {
  2839. TestRunStats( TestRunInfo const& _runInfo,
  2840. Totals const& _totals,
  2841. bool _aborting );
  2842. TestRunStats( TestRunStats const& ) = default;
  2843. TestRunStats( TestRunStats && ) = default;
  2844. TestRunStats& operator = ( TestRunStats const& ) = default;
  2845. TestRunStats& operator = ( TestRunStats && ) = default;
  2846. virtual ~TestRunStats();
  2847. TestRunInfo runInfo;
  2848. Totals totals;
  2849. bool aborting;
  2850. };
  2851. struct BenchmarkInfo {
  2852. std::string name;
  2853. };
  2854. struct BenchmarkStats {
  2855. BenchmarkInfo info;
  2856. std::size_t iterations;
  2857. uint64_t elapsedTimeInNanoseconds;
  2858. };
  2859. struct IStreamingReporter {
  2860. virtual ~IStreamingReporter() = default;
  2861. // Implementing class must also provide the following static methods:
  2862. // static std::string getDescription();
  2863. // static std::set<Verbosity> getSupportedVerbosities()
  2864. virtual ReporterPreferences getPreferences() const = 0;
  2865. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  2866. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  2867. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  2868. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  2869. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  2870. // *** experimental ***
  2871. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  2872. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  2873. // The return value indicates if the messages buffer should be cleared:
  2874. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  2875. // *** experimental ***
  2876. virtual void benchmarkEnded( BenchmarkStats const& ) {}
  2877. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  2878. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  2879. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  2880. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  2881. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  2882. // Default empty implementation provided
  2883. virtual void fatalErrorEncountered( StringRef name );
  2884. virtual bool isMulti() const;
  2885. };
  2886. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  2887. struct IReporterFactory {
  2888. virtual ~IReporterFactory();
  2889. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  2890. virtual std::string getDescription() const = 0;
  2891. };
  2892. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2893. struct IReporterRegistry {
  2894. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  2895. using Listeners = std::vector<IReporterFactoryPtr>;
  2896. virtual ~IReporterRegistry();
  2897. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  2898. virtual FactoryMap const& getFactories() const = 0;
  2899. virtual Listeners const& getListeners() const = 0;
  2900. };
  2901. void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter );
  2902. } // end namespace Catch
  2903. // end catch_interfaces_reporter.h
  2904. #include <algorithm>
  2905. #include <cstring>
  2906. #include <cfloat>
  2907. #include <cstdio>
  2908. #include <assert.h>
  2909. #include <memory>
  2910. #include <ostream>
  2911. namespace Catch {
  2912. void prepareExpandedExpression(AssertionResult& result);
  2913. // Returns double formatted as %.3f (format expected on output)
  2914. std::string getFormattedDuration( double duration );
  2915. template<typename DerivedT>
  2916. struct StreamingReporterBase : IStreamingReporter {
  2917. StreamingReporterBase( ReporterConfig const& _config )
  2918. : m_config( _config.fullConfig() ),
  2919. stream( _config.stream() )
  2920. {
  2921. m_reporterPrefs.shouldRedirectStdOut = false;
  2922. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  2923. throw std::domain_error( "Verbosity level not supported by this reporter" );
  2924. }
  2925. ReporterPreferences getPreferences() const override {
  2926. return m_reporterPrefs;
  2927. }
  2928. static std::set<Verbosity> getSupportedVerbosities() {
  2929. return { Verbosity::Normal };
  2930. }
  2931. ~StreamingReporterBase() override = default;
  2932. void noMatchingTestCases(std::string const&) override {}
  2933. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  2934. currentTestRunInfo = _testRunInfo;
  2935. }
  2936. void testGroupStarting(GroupInfo const& _groupInfo) override {
  2937. currentGroupInfo = _groupInfo;
  2938. }
  2939. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  2940. currentTestCaseInfo = _testInfo;
  2941. }
  2942. void sectionStarting(SectionInfo const& _sectionInfo) override {
  2943. m_sectionStack.push_back(_sectionInfo);
  2944. }
  2945. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  2946. m_sectionStack.pop_back();
  2947. }
  2948. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  2949. currentTestCaseInfo.reset();
  2950. }
  2951. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  2952. currentGroupInfo.reset();
  2953. }
  2954. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  2955. currentTestCaseInfo.reset();
  2956. currentGroupInfo.reset();
  2957. currentTestRunInfo.reset();
  2958. }
  2959. void skipTest(TestCaseInfo const&) override {
  2960. // Don't do anything with this by default.
  2961. // It can optionally be overridden in the derived class.
  2962. }
  2963. IConfigPtr m_config;
  2964. std::ostream& stream;
  2965. LazyStat<TestRunInfo> currentTestRunInfo;
  2966. LazyStat<GroupInfo> currentGroupInfo;
  2967. LazyStat<TestCaseInfo> currentTestCaseInfo;
  2968. std::vector<SectionInfo> m_sectionStack;
  2969. ReporterPreferences m_reporterPrefs;
  2970. };
  2971. template<typename DerivedT>
  2972. struct CumulativeReporterBase : IStreamingReporter {
  2973. template<typename T, typename ChildNodeT>
  2974. struct Node {
  2975. explicit Node( T const& _value ) : value( _value ) {}
  2976. virtual ~Node() {}
  2977. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  2978. T value;
  2979. ChildNodes children;
  2980. };
  2981. struct SectionNode {
  2982. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  2983. virtual ~SectionNode() = default;
  2984. bool operator == (SectionNode const& other) const {
  2985. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  2986. }
  2987. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  2988. return operator==(*other);
  2989. }
  2990. SectionStats stats;
  2991. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  2992. using Assertions = std::vector<AssertionStats>;
  2993. ChildSections childSections;
  2994. Assertions assertions;
  2995. std::string stdOut;
  2996. std::string stdErr;
  2997. };
  2998. struct BySectionInfo {
  2999. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  3000. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  3001. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  3002. return ((node->stats.sectionInfo.name == m_other.name) &&
  3003. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  3004. }
  3005. void operator=(BySectionInfo const&) = delete;
  3006. private:
  3007. SectionInfo const& m_other;
  3008. };
  3009. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  3010. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  3011. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  3012. CumulativeReporterBase( ReporterConfig const& _config )
  3013. : m_config( _config.fullConfig() ),
  3014. stream( _config.stream() )
  3015. {
  3016. m_reporterPrefs.shouldRedirectStdOut = false;
  3017. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3018. throw std::domain_error( "Verbosity level not supported by this reporter" );
  3019. }
  3020. ~CumulativeReporterBase() override = default;
  3021. ReporterPreferences getPreferences() const override {
  3022. return m_reporterPrefs;
  3023. }
  3024. static std::set<Verbosity> getSupportedVerbosities() {
  3025. return { Verbosity::Normal };
  3026. }
  3027. void testRunStarting( TestRunInfo const& ) override {}
  3028. void testGroupStarting( GroupInfo const& ) override {}
  3029. void testCaseStarting( TestCaseInfo const& ) override {}
  3030. void sectionStarting( SectionInfo const& sectionInfo ) override {
  3031. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  3032. std::shared_ptr<SectionNode> node;
  3033. if( m_sectionStack.empty() ) {
  3034. if( !m_rootSection )
  3035. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  3036. node = m_rootSection;
  3037. }
  3038. else {
  3039. SectionNode& parentNode = *m_sectionStack.back();
  3040. auto it =
  3041. std::find_if( parentNode.childSections.begin(),
  3042. parentNode.childSections.end(),
  3043. BySectionInfo( sectionInfo ) );
  3044. if( it == parentNode.childSections.end() ) {
  3045. node = std::make_shared<SectionNode>( incompleteStats );
  3046. parentNode.childSections.push_back( node );
  3047. }
  3048. else
  3049. node = *it;
  3050. }
  3051. m_sectionStack.push_back( node );
  3052. m_deepestSection = std::move(node);
  3053. }
  3054. void assertionStarting(AssertionInfo const&) override {}
  3055. bool assertionEnded(AssertionStats const& assertionStats) override {
  3056. assert(!m_sectionStack.empty());
  3057. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  3058. // which getExpandedExpression() calls to build the expression string.
  3059. // Our section stack copy of the assertionResult will likely outlive the
  3060. // temporary, so it must be expanded or discarded now to avoid calling
  3061. // a destroyed object later.
  3062. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  3063. SectionNode& sectionNode = *m_sectionStack.back();
  3064. sectionNode.assertions.push_back(assertionStats);
  3065. return true;
  3066. }
  3067. void sectionEnded(SectionStats const& sectionStats) override {
  3068. assert(!m_sectionStack.empty());
  3069. SectionNode& node = *m_sectionStack.back();
  3070. node.stats = sectionStats;
  3071. m_sectionStack.pop_back();
  3072. }
  3073. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  3074. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  3075. assert(m_sectionStack.size() == 0);
  3076. node->children.push_back(m_rootSection);
  3077. m_testCases.push_back(node);
  3078. m_rootSection.reset();
  3079. assert(m_deepestSection);
  3080. m_deepestSection->stdOut = testCaseStats.stdOut;
  3081. m_deepestSection->stdErr = testCaseStats.stdErr;
  3082. }
  3083. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  3084. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  3085. node->children.swap(m_testCases);
  3086. m_testGroups.push_back(node);
  3087. }
  3088. void testRunEnded(TestRunStats const& testRunStats) override {
  3089. auto node = std::make_shared<TestRunNode>(testRunStats);
  3090. node->children.swap(m_testGroups);
  3091. m_testRuns.push_back(node);
  3092. testRunEndedCumulative();
  3093. }
  3094. virtual void testRunEndedCumulative() = 0;
  3095. void skipTest(TestCaseInfo const&) override {}
  3096. IConfigPtr m_config;
  3097. std::ostream& stream;
  3098. std::vector<AssertionStats> m_assertions;
  3099. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  3100. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  3101. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  3102. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  3103. std::shared_ptr<SectionNode> m_rootSection;
  3104. std::shared_ptr<SectionNode> m_deepestSection;
  3105. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  3106. ReporterPreferences m_reporterPrefs;
  3107. };
  3108. template<char C>
  3109. char const* getLineOfChars() {
  3110. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  3111. if( !*line ) {
  3112. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  3113. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  3114. }
  3115. return line;
  3116. }
  3117. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  3118. TestEventListenerBase( ReporterConfig const& _config );
  3119. void assertionStarting(AssertionInfo const&) override;
  3120. bool assertionEnded(AssertionStats const&) override;
  3121. };
  3122. } // end namespace Catch
  3123. // end catch_reporter_bases.hpp
  3124. // start catch_console_colour.h
  3125. namespace Catch {
  3126. struct Colour {
  3127. enum Code {
  3128. None = 0,
  3129. White,
  3130. Red,
  3131. Green,
  3132. Blue,
  3133. Cyan,
  3134. Yellow,
  3135. Grey,
  3136. Bright = 0x10,
  3137. BrightRed = Bright | Red,
  3138. BrightGreen = Bright | Green,
  3139. LightGrey = Bright | Grey,
  3140. BrightWhite = Bright | White,
  3141. BrightYellow = Bright | Yellow,
  3142. // By intention
  3143. FileName = LightGrey,
  3144. Warning = BrightYellow,
  3145. ResultError = BrightRed,
  3146. ResultSuccess = BrightGreen,
  3147. ResultExpectedFailure = Warning,
  3148. Error = BrightRed,
  3149. Success = Green,
  3150. OriginalExpression = Cyan,
  3151. ReconstructedExpression = BrightYellow,
  3152. SecondaryText = LightGrey,
  3153. Headers = White
  3154. };
  3155. // Use constructed object for RAII guard
  3156. Colour( Code _colourCode );
  3157. Colour( Colour&& other ) noexcept;
  3158. Colour& operator=( Colour&& other ) noexcept;
  3159. ~Colour();
  3160. // Use static method for one-shot changes
  3161. static void use( Code _colourCode );
  3162. private:
  3163. bool m_moved = false;
  3164. };
  3165. std::ostream& operator << ( std::ostream& os, Colour const& );
  3166. } // end namespace Catch
  3167. // end catch_console_colour.h
  3168. // start catch_reporter_registrars.hpp
  3169. namespace Catch {
  3170. template<typename T>
  3171. class ReporterRegistrar {
  3172. class ReporterFactory : public IReporterFactory {
  3173. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3174. return std::unique_ptr<T>( new T( config ) );
  3175. }
  3176. virtual std::string getDescription() const override {
  3177. return T::getDescription();
  3178. }
  3179. };
  3180. public:
  3181. explicit ReporterRegistrar( std::string const& name ) {
  3182. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  3183. }
  3184. };
  3185. template<typename T>
  3186. class ListenerRegistrar {
  3187. class ListenerFactory : public IReporterFactory {
  3188. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3189. return std::unique_ptr<T>( new T( config ) );
  3190. }
  3191. virtual std::string getDescription() const override {
  3192. return std::string();
  3193. }
  3194. };
  3195. public:
  3196. ListenerRegistrar() {
  3197. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  3198. }
  3199. };
  3200. }
  3201. #if !defined(CATCH_CONFIG_DISABLE)
  3202. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  3203. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3204. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  3205. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  3206. #define CATCH_REGISTER_LISTENER( listenerType ) \
  3207. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3208. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  3209. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  3210. #else // CATCH_CONFIG_DISABLE
  3211. #define CATCH_REGISTER_REPORTER(name, reporterType)
  3212. #define CATCH_REGISTER_LISTENER(listenerType)
  3213. #endif // CATCH_CONFIG_DISABLE
  3214. // end catch_reporter_registrars.hpp
  3215. // Allow users to base their work off existing reporters
  3216. // start catch_reporter_compact.h
  3217. namespace Catch {
  3218. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  3219. using StreamingReporterBase::StreamingReporterBase;
  3220. ~CompactReporter() override;
  3221. static std::string getDescription();
  3222. ReporterPreferences getPreferences() const override;
  3223. void noMatchingTestCases(std::string const& spec) override;
  3224. void assertionStarting(AssertionInfo const&) override;
  3225. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3226. void sectionEnded(SectionStats const& _sectionStats) override;
  3227. void testRunEnded(TestRunStats const& _testRunStats) override;
  3228. };
  3229. } // end namespace Catch
  3230. // end catch_reporter_compact.h
  3231. // start catch_reporter_console.h
  3232. #if defined(_MSC_VER)
  3233. #pragma warning(push)
  3234. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  3235. // Note that 4062 (not all labels are handled
  3236. // and default is missing) is enabled
  3237. #endif
  3238. namespace Catch {
  3239. // Fwd decls
  3240. struct SummaryColumn;
  3241. class TablePrinter;
  3242. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  3243. std::unique_ptr<TablePrinter> m_tablePrinter;
  3244. ConsoleReporter(ReporterConfig const& config);
  3245. ~ConsoleReporter() override;
  3246. static std::string getDescription();
  3247. void noMatchingTestCases(std::string const& spec) override;
  3248. void assertionStarting(AssertionInfo const&) override;
  3249. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3250. void sectionStarting(SectionInfo const& _sectionInfo) override;
  3251. void sectionEnded(SectionStats const& _sectionStats) override;
  3252. void benchmarkStarting(BenchmarkInfo const& info) override;
  3253. void benchmarkEnded(BenchmarkStats const& stats) override;
  3254. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  3255. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  3256. void testRunEnded(TestRunStats const& _testRunStats) override;
  3257. private:
  3258. void lazyPrint();
  3259. void lazyPrintWithoutClosingBenchmarkTable();
  3260. void lazyPrintRunInfo();
  3261. void lazyPrintGroupInfo();
  3262. void printTestCaseAndSectionHeader();
  3263. void printClosedHeader(std::string const& _name);
  3264. void printOpenHeader(std::string const& _name);
  3265. // if string has a : in first line will set indent to follow it on
  3266. // subsequent lines
  3267. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  3268. void printTotals(Totals const& totals);
  3269. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  3270. void printTotalsDivider(Totals const& totals);
  3271. void printSummaryDivider();
  3272. private:
  3273. bool m_headerPrinted = false;
  3274. };
  3275. } // end namespace Catch
  3276. #if defined(_MSC_VER)
  3277. #pragma warning(pop)
  3278. #endif
  3279. // end catch_reporter_console.h
  3280. // start catch_reporter_junit.h
  3281. // start catch_xmlwriter.h
  3282. #include <vector>
  3283. namespace Catch {
  3284. class XmlEncode {
  3285. public:
  3286. enum ForWhat { ForTextNodes, ForAttributes };
  3287. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  3288. void encodeTo( std::ostream& os ) const;
  3289. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  3290. private:
  3291. std::string m_str;
  3292. ForWhat m_forWhat;
  3293. };
  3294. class XmlWriter {
  3295. public:
  3296. class ScopedElement {
  3297. public:
  3298. ScopedElement( XmlWriter* writer );
  3299. ScopedElement( ScopedElement&& other ) noexcept;
  3300. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  3301. ~ScopedElement();
  3302. ScopedElement& writeText( std::string const& text, bool indent = true );
  3303. template<typename T>
  3304. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  3305. m_writer->writeAttribute( name, attribute );
  3306. return *this;
  3307. }
  3308. private:
  3309. mutable XmlWriter* m_writer = nullptr;
  3310. };
  3311. XmlWriter( std::ostream& os = Catch::cout() );
  3312. ~XmlWriter();
  3313. XmlWriter( XmlWriter const& ) = delete;
  3314. XmlWriter& operator=( XmlWriter const& ) = delete;
  3315. XmlWriter& startElement( std::string const& name );
  3316. ScopedElement scopedElement( std::string const& name );
  3317. XmlWriter& endElement();
  3318. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  3319. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  3320. template<typename T>
  3321. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  3322. ReusableStringStream rss;
  3323. rss << attribute;
  3324. return writeAttribute( name, rss.str() );
  3325. }
  3326. XmlWriter& writeText( std::string const& text, bool indent = true );
  3327. XmlWriter& writeComment( std::string const& text );
  3328. void writeStylesheetRef( std::string const& url );
  3329. XmlWriter& writeBlankLine();
  3330. void ensureTagClosed();
  3331. private:
  3332. void writeDeclaration();
  3333. void newlineIfNecessary();
  3334. bool m_tagIsOpen = false;
  3335. bool m_needsNewline = false;
  3336. std::vector<std::string> m_tags;
  3337. std::string m_indent;
  3338. std::ostream& m_os;
  3339. };
  3340. }
  3341. // end catch_xmlwriter.h
  3342. namespace Catch {
  3343. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  3344. public:
  3345. JunitReporter(ReporterConfig const& _config);
  3346. ~JunitReporter() override;
  3347. static std::string getDescription();
  3348. void noMatchingTestCases(std::string const& /*spec*/) override;
  3349. void testRunStarting(TestRunInfo const& runInfo) override;
  3350. void testGroupStarting(GroupInfo const& groupInfo) override;
  3351. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  3352. bool assertionEnded(AssertionStats const& assertionStats) override;
  3353. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3354. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3355. void testRunEndedCumulative() override;
  3356. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  3357. void writeTestCase(TestCaseNode const& testCaseNode);
  3358. void writeSection(std::string const& className,
  3359. std::string const& rootName,
  3360. SectionNode const& sectionNode);
  3361. void writeAssertions(SectionNode const& sectionNode);
  3362. void writeAssertion(AssertionStats const& stats);
  3363. XmlWriter xml;
  3364. Timer suiteTimer;
  3365. std::string stdOutForSuite;
  3366. std::string stdErrForSuite;
  3367. unsigned int unexpectedExceptions = 0;
  3368. bool m_okToFail = false;
  3369. };
  3370. } // end namespace Catch
  3371. // end catch_reporter_junit.h
  3372. // start catch_reporter_xml.h
  3373. namespace Catch {
  3374. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  3375. public:
  3376. XmlReporter(ReporterConfig const& _config);
  3377. ~XmlReporter() override;
  3378. static std::string getDescription();
  3379. virtual std::string getStylesheetRef() const;
  3380. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  3381. public: // StreamingReporterBase
  3382. void noMatchingTestCases(std::string const& s) override;
  3383. void testRunStarting(TestRunInfo const& testInfo) override;
  3384. void testGroupStarting(GroupInfo const& groupInfo) override;
  3385. void testCaseStarting(TestCaseInfo const& testInfo) override;
  3386. void sectionStarting(SectionInfo const& sectionInfo) override;
  3387. void assertionStarting(AssertionInfo const&) override;
  3388. bool assertionEnded(AssertionStats const& assertionStats) override;
  3389. void sectionEnded(SectionStats const& sectionStats) override;
  3390. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3391. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3392. void testRunEnded(TestRunStats const& testRunStats) override;
  3393. private:
  3394. Timer m_testCaseTimer;
  3395. XmlWriter m_xml;
  3396. int m_sectionDepth = 0;
  3397. };
  3398. } // end namespace Catch
  3399. // end catch_reporter_xml.h
  3400. // end catch_external_interfaces.h
  3401. #endif
  3402. #endif // ! CATCH_CONFIG_IMPL_ONLY
  3403. #ifdef CATCH_IMPL
  3404. // start catch_impl.hpp
  3405. #ifdef __clang__
  3406. #pragma clang diagnostic push
  3407. #pragma clang diagnostic ignored "-Wweak-vtables"
  3408. #endif
  3409. // Keep these here for external reporters
  3410. // start catch_test_case_tracker.h
  3411. #include <string>
  3412. #include <vector>
  3413. #include <memory>
  3414. namespace Catch {
  3415. namespace TestCaseTracking {
  3416. struct NameAndLocation {
  3417. std::string name;
  3418. SourceLineInfo location;
  3419. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  3420. };
  3421. struct ITracker;
  3422. using ITrackerPtr = std::shared_ptr<ITracker>;
  3423. struct ITracker {
  3424. virtual ~ITracker();
  3425. // static queries
  3426. virtual NameAndLocation const& nameAndLocation() const = 0;
  3427. // dynamic queries
  3428. virtual bool isComplete() const = 0; // Successfully completed or failed
  3429. virtual bool isSuccessfullyCompleted() const = 0;
  3430. virtual bool isOpen() const = 0; // Started but not complete
  3431. virtual bool hasChildren() const = 0;
  3432. virtual ITracker& parent() = 0;
  3433. // actions
  3434. virtual void close() = 0; // Successfully complete
  3435. virtual void fail() = 0;
  3436. virtual void markAsNeedingAnotherRun() = 0;
  3437. virtual void addChild( ITrackerPtr const& child ) = 0;
  3438. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  3439. virtual void openChild() = 0;
  3440. // Debug/ checking
  3441. virtual bool isSectionTracker() const = 0;
  3442. virtual bool isIndexTracker() const = 0;
  3443. };
  3444. class TrackerContext {
  3445. enum RunState {
  3446. NotStarted,
  3447. Executing,
  3448. CompletedCycle
  3449. };
  3450. ITrackerPtr m_rootTracker;
  3451. ITracker* m_currentTracker = nullptr;
  3452. RunState m_runState = NotStarted;
  3453. public:
  3454. static TrackerContext& instance();
  3455. ITracker& startRun();
  3456. void endRun();
  3457. void startCycle();
  3458. void completeCycle();
  3459. bool completedCycle() const;
  3460. ITracker& currentTracker();
  3461. void setCurrentTracker( ITracker* tracker );
  3462. };
  3463. class TrackerBase : public ITracker {
  3464. protected:
  3465. enum CycleState {
  3466. NotStarted,
  3467. Executing,
  3468. ExecutingChildren,
  3469. NeedsAnotherRun,
  3470. CompletedSuccessfully,
  3471. Failed
  3472. };
  3473. class TrackerHasName {
  3474. NameAndLocation m_nameAndLocation;
  3475. public:
  3476. TrackerHasName( NameAndLocation const& nameAndLocation );
  3477. bool operator ()( ITrackerPtr const& tracker ) const;
  3478. };
  3479. using Children = std::vector<ITrackerPtr>;
  3480. NameAndLocation m_nameAndLocation;
  3481. TrackerContext& m_ctx;
  3482. ITracker* m_parent;
  3483. Children m_children;
  3484. CycleState m_runState = NotStarted;
  3485. public:
  3486. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3487. NameAndLocation const& nameAndLocation() const override;
  3488. bool isComplete() const override;
  3489. bool isSuccessfullyCompleted() const override;
  3490. bool isOpen() const override;
  3491. bool hasChildren() const override;
  3492. void addChild( ITrackerPtr const& child ) override;
  3493. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  3494. ITracker& parent() override;
  3495. void openChild() override;
  3496. bool isSectionTracker() const override;
  3497. bool isIndexTracker() const override;
  3498. void open();
  3499. void close() override;
  3500. void fail() override;
  3501. void markAsNeedingAnotherRun() override;
  3502. private:
  3503. void moveToParent();
  3504. void moveToThis();
  3505. };
  3506. class SectionTracker : public TrackerBase {
  3507. std::vector<std::string> m_filters;
  3508. public:
  3509. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3510. bool isSectionTracker() const override;
  3511. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  3512. void tryOpen();
  3513. void addInitialFilters( std::vector<std::string> const& filters );
  3514. void addNextFilters( std::vector<std::string> const& filters );
  3515. };
  3516. class IndexTracker : public TrackerBase {
  3517. int m_size;
  3518. int m_index = -1;
  3519. public:
  3520. IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size );
  3521. bool isIndexTracker() const override;
  3522. void close() override;
  3523. static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size );
  3524. int index() const;
  3525. void moveNext();
  3526. };
  3527. } // namespace TestCaseTracking
  3528. using TestCaseTracking::ITracker;
  3529. using TestCaseTracking::TrackerContext;
  3530. using TestCaseTracking::SectionTracker;
  3531. using TestCaseTracking::IndexTracker;
  3532. } // namespace Catch
  3533. // end catch_test_case_tracker.h
  3534. // start catch_leak_detector.h
  3535. namespace Catch {
  3536. struct LeakDetector {
  3537. LeakDetector();
  3538. };
  3539. }
  3540. // end catch_leak_detector.h
  3541. // Cpp files will be included in the single-header file here
  3542. // start catch_approx.cpp
  3543. #include <cmath>
  3544. #include <limits>
  3545. namespace {
  3546. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  3547. // But without the subtraction to allow for INFINITY in comparison
  3548. bool marginComparison(double lhs, double rhs, double margin) {
  3549. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  3550. }
  3551. }
  3552. namespace Catch {
  3553. namespace Detail {
  3554. Approx::Approx ( double value )
  3555. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  3556. m_margin( 0.0 ),
  3557. m_scale( 0.0 ),
  3558. m_value( value )
  3559. {}
  3560. Approx Approx::custom() {
  3561. return Approx( 0 );
  3562. }
  3563. std::string Approx::toString() const {
  3564. ReusableStringStream rss;
  3565. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  3566. return rss.str();
  3567. }
  3568. bool Approx::equalityComparisonImpl(const double other) const {
  3569. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  3570. // Thanks to Richard Harris for his help refining the scaled margin value
  3571. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  3572. }
  3573. } // end namespace Detail
  3574. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  3575. return value.toString();
  3576. }
  3577. } // end namespace Catch
  3578. // end catch_approx.cpp
  3579. // start catch_assertionhandler.cpp
  3580. // start catch_context.h
  3581. #include <memory>
  3582. namespace Catch {
  3583. struct IResultCapture;
  3584. struct IRunner;
  3585. struct IConfig;
  3586. struct IMutableContext;
  3587. using IConfigPtr = std::shared_ptr<IConfig const>;
  3588. struct IContext
  3589. {
  3590. virtual ~IContext();
  3591. virtual IResultCapture* getResultCapture() = 0;
  3592. virtual IRunner* getRunner() = 0;
  3593. virtual IConfigPtr const& getConfig() const = 0;
  3594. };
  3595. struct IMutableContext : IContext
  3596. {
  3597. virtual ~IMutableContext();
  3598. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3599. virtual void setRunner( IRunner* runner ) = 0;
  3600. virtual void setConfig( IConfigPtr const& config ) = 0;
  3601. private:
  3602. static IMutableContext *currentContext;
  3603. friend IMutableContext& getCurrentMutableContext();
  3604. friend void cleanUpContext();
  3605. static void createContext();
  3606. };
  3607. inline IMutableContext& getCurrentMutableContext()
  3608. {
  3609. if( !IMutableContext::currentContext )
  3610. IMutableContext::createContext();
  3611. return *IMutableContext::currentContext;
  3612. }
  3613. inline IContext& getCurrentContext()
  3614. {
  3615. return getCurrentMutableContext();
  3616. }
  3617. void cleanUpContext();
  3618. }
  3619. // end catch_context.h
  3620. // start catch_debugger.h
  3621. namespace Catch {
  3622. bool isDebuggerActive();
  3623. }
  3624. #ifdef CATCH_PLATFORM_MAC
  3625. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  3626. #elif defined(CATCH_PLATFORM_LINUX)
  3627. // If we can use inline assembler, do it because this allows us to break
  3628. // directly at the location of the failing check instead of breaking inside
  3629. // raise() called from it, i.e. one stack frame below.
  3630. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  3631. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  3632. #else // Fall back to the generic way.
  3633. #include <signal.h>
  3634. #define CATCH_TRAP() raise(SIGTRAP)
  3635. #endif
  3636. #elif defined(_MSC_VER)
  3637. #define CATCH_TRAP() __debugbreak()
  3638. #elif defined(__MINGW32__)
  3639. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  3640. #define CATCH_TRAP() DebugBreak()
  3641. #endif
  3642. #ifdef CATCH_TRAP
  3643. #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
  3644. #else
  3645. namespace Catch {
  3646. inline void doNothing() {}
  3647. }
  3648. #define CATCH_BREAK_INTO_DEBUGGER() Catch::doNothing()
  3649. #endif
  3650. // end catch_debugger.h
  3651. // start catch_run_context.h
  3652. // start catch_fatal_condition.h
  3653. #include <string>
  3654. #if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
  3655. // start catch_windows_h_proxy.h
  3656. #if defined(CATCH_PLATFORM_WINDOWS)
  3657. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  3658. # define CATCH_DEFINED_NOMINMAX
  3659. # define NOMINMAX
  3660. #endif
  3661. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  3662. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  3663. # define WIN32_LEAN_AND_MEAN
  3664. #endif
  3665. #ifdef __AFXDLL
  3666. #include <AfxWin.h>
  3667. #else
  3668. #include <windows.h>
  3669. #endif
  3670. #ifdef CATCH_DEFINED_NOMINMAX
  3671. # undef NOMINMAX
  3672. #endif
  3673. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  3674. # undef WIN32_LEAN_AND_MEAN
  3675. #endif
  3676. #endif // defined(CATCH_PLATFORM_WINDOWS)
  3677. // end catch_windows_h_proxy.h
  3678. # if !defined ( CATCH_CONFIG_WINDOWS_SEH )
  3679. namespace Catch {
  3680. struct FatalConditionHandler {
  3681. void reset();
  3682. };
  3683. }
  3684. # else // CATCH_CONFIG_WINDOWS_SEH is defined
  3685. namespace Catch {
  3686. struct FatalConditionHandler {
  3687. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  3688. FatalConditionHandler();
  3689. static void reset();
  3690. ~FatalConditionHandler();
  3691. private:
  3692. static bool isSet;
  3693. static ULONG guaranteeSize;
  3694. static PVOID exceptionHandlerHandle;
  3695. };
  3696. } // namespace Catch
  3697. # endif // CATCH_CONFIG_WINDOWS_SEH
  3698. #else // Not Windows - assumed to be POSIX compatible //////////////////////////
  3699. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  3700. namespace Catch {
  3701. struct FatalConditionHandler {
  3702. void reset();
  3703. };
  3704. }
  3705. # else // CATCH_CONFIG_POSIX_SIGNALS is defined
  3706. #include <signal.h>
  3707. namespace Catch {
  3708. struct FatalConditionHandler {
  3709. static bool isSet;
  3710. static struct sigaction oldSigActions[];// [sizeof(signalDefs) / sizeof(SignalDefs)];
  3711. static stack_t oldSigStack;
  3712. static char altStackMem[];
  3713. static void handleSignal( int sig );
  3714. FatalConditionHandler();
  3715. ~FatalConditionHandler();
  3716. static void reset();
  3717. };
  3718. } // namespace Catch
  3719. # endif // CATCH_CONFIG_POSIX_SIGNALS
  3720. #endif // not Windows
  3721. // end catch_fatal_condition.h
  3722. #include <string>
  3723. namespace Catch {
  3724. struct IMutableContext;
  3725. ///////////////////////////////////////////////////////////////////////////
  3726. class RunContext : public IResultCapture, public IRunner {
  3727. public:
  3728. RunContext( RunContext const& ) = delete;
  3729. RunContext& operator =( RunContext const& ) = delete;
  3730. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  3731. ~RunContext() override;
  3732. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  3733. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  3734. Totals runTest(TestCase const& testCase);
  3735. IConfigPtr config() const;
  3736. IStreamingReporter& reporter() const;
  3737. public: // IResultCapture
  3738. // Assertion handlers
  3739. void handleExpr
  3740. ( AssertionInfo const& info,
  3741. ITransientExpression const& expr,
  3742. AssertionReaction& reaction ) override;
  3743. void handleMessage
  3744. ( AssertionInfo const& info,
  3745. ResultWas::OfType resultType,
  3746. StringRef const& message,
  3747. AssertionReaction& reaction ) override;
  3748. void handleUnexpectedExceptionNotThrown
  3749. ( AssertionInfo const& info,
  3750. AssertionReaction& reaction ) override;
  3751. void handleUnexpectedInflightException
  3752. ( AssertionInfo const& info,
  3753. std::string const& message,
  3754. AssertionReaction& reaction ) override;
  3755. void handleIncomplete
  3756. ( AssertionInfo const& info ) override;
  3757. void handleNonExpr
  3758. ( AssertionInfo const &info,
  3759. ResultWas::OfType resultType,
  3760. AssertionReaction &reaction ) override;
  3761. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  3762. void sectionEnded( SectionEndInfo const& endInfo ) override;
  3763. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  3764. void benchmarkStarting( BenchmarkInfo const& info ) override;
  3765. void benchmarkEnded( BenchmarkStats const& stats ) override;
  3766. void pushScopedMessage( MessageInfo const& message ) override;
  3767. void popScopedMessage( MessageInfo const& message ) override;
  3768. std::string getCurrentTestName() const override;
  3769. const AssertionResult* getLastResult() const override;
  3770. void exceptionEarlyReported() override;
  3771. void handleFatalErrorCondition( StringRef message ) override;
  3772. bool lastAssertionPassed() override;
  3773. void assertionPassed() override;
  3774. public:
  3775. // !TBD We need to do this another way!
  3776. bool aborting() const override;
  3777. private:
  3778. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  3779. void invokeActiveTestCase();
  3780. void resetAssertionInfo();
  3781. bool testForMissingAssertions( Counts& assertions );
  3782. void assertionEnded( AssertionResult const& result );
  3783. void reportExpr
  3784. ( AssertionInfo const &info,
  3785. ResultWas::OfType resultType,
  3786. ITransientExpression const *expr,
  3787. bool negated );
  3788. void populateReaction( AssertionReaction& reaction );
  3789. private:
  3790. void handleUnfinishedSections();
  3791. TestRunInfo m_runInfo;
  3792. IMutableContext& m_context;
  3793. TestCase const* m_activeTestCase = nullptr;
  3794. ITracker* m_testCaseTracker;
  3795. Option<AssertionResult> m_lastResult;
  3796. IConfigPtr m_config;
  3797. Totals m_totals;
  3798. IStreamingReporterPtr m_reporter;
  3799. std::vector<MessageInfo> m_messages;
  3800. AssertionInfo m_lastAssertionInfo;
  3801. std::vector<SectionEndInfo> m_unfinishedSections;
  3802. std::vector<ITracker*> m_activeSections;
  3803. TrackerContext m_trackerContext;
  3804. bool m_lastAssertionPassed = false;
  3805. bool m_shouldReportUnexpected = true;
  3806. bool m_includeSuccessfulResults;
  3807. };
  3808. } // end namespace Catch
  3809. // end catch_run_context.h
  3810. namespace Catch {
  3811. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  3812. expr.streamReconstructedExpression( os );
  3813. return os;
  3814. }
  3815. LazyExpression::LazyExpression( bool isNegated )
  3816. : m_isNegated( isNegated )
  3817. {}
  3818. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  3819. LazyExpression::operator bool() const {
  3820. return m_transientExpression != nullptr;
  3821. }
  3822. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  3823. if( lazyExpr.m_isNegated )
  3824. os << "!";
  3825. if( lazyExpr ) {
  3826. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  3827. os << "(" << *lazyExpr.m_transientExpression << ")";
  3828. else
  3829. os << *lazyExpr.m_transientExpression;
  3830. }
  3831. else {
  3832. os << "{** error - unchecked empty expression requested **}";
  3833. }
  3834. return os;
  3835. }
  3836. AssertionHandler::AssertionHandler
  3837. ( StringRef macroName,
  3838. SourceLineInfo const& lineInfo,
  3839. StringRef capturedExpression,
  3840. ResultDisposition::Flags resultDisposition )
  3841. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  3842. m_resultCapture( getResultCapture() )
  3843. {}
  3844. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  3845. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  3846. }
  3847. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  3848. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  3849. }
  3850. auto AssertionHandler::allowThrows() const -> bool {
  3851. return getCurrentContext().getConfig()->allowThrows();
  3852. }
  3853. void AssertionHandler::complete() {
  3854. setCompleted();
  3855. if( m_reaction.shouldDebugBreak ) {
  3856. // If you find your debugger stopping you here then go one level up on the
  3857. // call-stack for the code that caused it (typically a failed assertion)
  3858. // (To go back to the test and change execution, jump over the throw, next)
  3859. CATCH_BREAK_INTO_DEBUGGER();
  3860. }
  3861. if( m_reaction.shouldThrow )
  3862. throw Catch::TestFailureException();
  3863. }
  3864. void AssertionHandler::setCompleted() {
  3865. m_completed = true;
  3866. }
  3867. void AssertionHandler::handleUnexpectedInflightException() {
  3868. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  3869. }
  3870. void AssertionHandler::handleExceptionThrownAsExpected() {
  3871. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  3872. }
  3873. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  3874. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  3875. }
  3876. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  3877. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  3878. }
  3879. void AssertionHandler::handleThrowingCallSkipped() {
  3880. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  3881. }
  3882. // This is the overload that takes a string and infers the Equals matcher from it
  3883. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  3884. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString ) {
  3885. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  3886. }
  3887. } // namespace Catch
  3888. // end catch_assertionhandler.cpp
  3889. // start catch_assertionresult.cpp
  3890. namespace Catch {
  3891. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  3892. lazyExpression(_lazyExpression),
  3893. resultType(_resultType) {}
  3894. std::string AssertionResultData::reconstructExpression() const {
  3895. if( reconstructedExpression.empty() ) {
  3896. if( lazyExpression ) {
  3897. ReusableStringStream rss;
  3898. rss << lazyExpression;
  3899. reconstructedExpression = rss.str();
  3900. }
  3901. }
  3902. return reconstructedExpression;
  3903. }
  3904. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  3905. : m_info( info ),
  3906. m_resultData( data )
  3907. {}
  3908. // Result was a success
  3909. bool AssertionResult::succeeded() const {
  3910. return Catch::isOk( m_resultData.resultType );
  3911. }
  3912. // Result was a success, or failure is suppressed
  3913. bool AssertionResult::isOk() const {
  3914. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  3915. }
  3916. ResultWas::OfType AssertionResult::getResultType() const {
  3917. return m_resultData.resultType;
  3918. }
  3919. bool AssertionResult::hasExpression() const {
  3920. return m_info.capturedExpression[0] != 0;
  3921. }
  3922. bool AssertionResult::hasMessage() const {
  3923. return !m_resultData.message.empty();
  3924. }
  3925. std::string AssertionResult::getExpression() const {
  3926. if( isFalseTest( m_info.resultDisposition ) )
  3927. return "!(" + m_info.capturedExpression + ")";
  3928. else
  3929. return m_info.capturedExpression;
  3930. }
  3931. std::string AssertionResult::getExpressionInMacro() const {
  3932. std::string expr;
  3933. if( m_info.macroName[0] == 0 )
  3934. expr = m_info.capturedExpression;
  3935. else {
  3936. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  3937. expr += m_info.macroName.c_str();
  3938. expr += "( ";
  3939. expr += m_info.capturedExpression.c_str();
  3940. expr += " )";
  3941. }
  3942. return expr;
  3943. }
  3944. bool AssertionResult::hasExpandedExpression() const {
  3945. return hasExpression() && getExpandedExpression() != getExpression();
  3946. }
  3947. std::string AssertionResult::getExpandedExpression() const {
  3948. std::string expr = m_resultData.reconstructExpression();
  3949. return expr.empty()
  3950. ? getExpression()
  3951. : expr;
  3952. }
  3953. std::string AssertionResult::getMessage() const {
  3954. return m_resultData.message;
  3955. }
  3956. SourceLineInfo AssertionResult::getSourceInfo() const {
  3957. return m_info.lineInfo;
  3958. }
  3959. StringRef AssertionResult::getTestMacroName() const {
  3960. return m_info.macroName;
  3961. }
  3962. } // end namespace Catch
  3963. // end catch_assertionresult.cpp
  3964. // start catch_benchmark.cpp
  3965. namespace Catch {
  3966. auto BenchmarkLooper::getResolution() -> uint64_t {
  3967. return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
  3968. }
  3969. void BenchmarkLooper::reportStart() {
  3970. getResultCapture().benchmarkStarting( { m_name } );
  3971. }
  3972. auto BenchmarkLooper::needsMoreIterations() -> bool {
  3973. auto elapsed = m_timer.getElapsedNanoseconds();
  3974. // Exponentially increasing iterations until we're confident in our timer resolution
  3975. if( elapsed < m_resolution ) {
  3976. m_iterationsToRun *= 10;
  3977. return true;
  3978. }
  3979. getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
  3980. return false;
  3981. }
  3982. } // end namespace Catch
  3983. // end catch_benchmark.cpp
  3984. // start catch_capture_matchers.cpp
  3985. namespace Catch {
  3986. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  3987. // This is the general overload that takes a any string matcher
  3988. // There is another overload, in catch_assertinhandler.h/.cpp, that only takes a string and infers
  3989. // the Equals matcher (so the header does not mention matchers)
  3990. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString ) {
  3991. std::string exceptionMessage = Catch::translateActiveException();
  3992. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  3993. handler.handleExpr( expr );
  3994. }
  3995. } // namespace Catch
  3996. // end catch_capture_matchers.cpp
  3997. // start catch_commandline.cpp
  3998. // start catch_commandline.h
  3999. // start catch_clara.h
  4000. // Use Catch's value for console width (store Clara's off to the side, if present)
  4001. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  4002. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4003. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4004. #endif
  4005. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  4006. #ifdef __clang__
  4007. #pragma clang diagnostic push
  4008. #pragma clang diagnostic ignored "-Wweak-vtables"
  4009. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  4010. #pragma clang diagnostic ignored "-Wshadow"
  4011. #endif
  4012. // start clara.hpp
  4013. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  4014. //
  4015. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4016. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4017. //
  4018. // See https://github.com/philsquared/Clara for more details
  4019. // Clara v1.1.2
  4020. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4021. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  4022. #endif
  4023. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4024. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4025. #endif
  4026. // ----------- #included from clara_textflow.hpp -----------
  4027. // TextFlowCpp
  4028. //
  4029. // A single-header library for wrapping and laying out basic text, by Phil Nash
  4030. //
  4031. // This work is licensed under the BSD 2-Clause license.
  4032. // See the accompanying LICENSE file, or the one at https://opensource.org/licenses/BSD-2-Clause
  4033. //
  4034. // This project is hosted at https://github.com/philsquared/textflowcpp
  4035. #include <cassert>
  4036. #include <ostream>
  4037. #include <sstream>
  4038. #include <vector>
  4039. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4040. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  4041. #endif
  4042. namespace Catch { namespace clara { namespace TextFlow {
  4043. inline auto isWhitespace( char c ) -> bool {
  4044. static std::string chars = " \t\n\r";
  4045. return chars.find( c ) != std::string::npos;
  4046. }
  4047. inline auto isBreakableBefore( char c ) -> bool {
  4048. static std::string chars = "[({<|";
  4049. return chars.find( c ) != std::string::npos;
  4050. }
  4051. inline auto isBreakableAfter( char c ) -> bool {
  4052. static std::string chars = "])}>.,:;*+-=&/\\";
  4053. return chars.find( c ) != std::string::npos;
  4054. }
  4055. class Columns;
  4056. class Column {
  4057. std::vector<std::string> m_strings;
  4058. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  4059. size_t m_indent = 0;
  4060. size_t m_initialIndent = std::string::npos;
  4061. public:
  4062. class iterator {
  4063. friend Column;
  4064. Column const& m_column;
  4065. size_t m_stringIndex = 0;
  4066. size_t m_pos = 0;
  4067. size_t m_len = 0;
  4068. size_t m_end = 0;
  4069. bool m_suffix = false;
  4070. iterator( Column const& column, size_t stringIndex )
  4071. : m_column( column ),
  4072. m_stringIndex( stringIndex )
  4073. {}
  4074. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  4075. auto isBoundary( size_t at ) const -> bool {
  4076. assert( at > 0 );
  4077. assert( at <= line().size() );
  4078. return at == line().size() ||
  4079. ( isWhitespace( line()[at] ) && !isWhitespace( line()[at-1] ) ) ||
  4080. isBreakableBefore( line()[at] ) ||
  4081. isBreakableAfter( line()[at-1] );
  4082. }
  4083. void calcLength() {
  4084. assert( m_stringIndex < m_column.m_strings.size() );
  4085. m_suffix = false;
  4086. auto width = m_column.m_width-indent();
  4087. m_end = m_pos;
  4088. while( m_end < line().size() && line()[m_end] != '\n' )
  4089. ++m_end;
  4090. if( m_end < m_pos + width ) {
  4091. m_len = m_end - m_pos;
  4092. }
  4093. else {
  4094. size_t len = width;
  4095. while (len > 0 && !isBoundary(m_pos + len))
  4096. --len;
  4097. while (len > 0 && isWhitespace( line()[m_pos + len - 1] ))
  4098. --len;
  4099. if (len > 0) {
  4100. m_len = len;
  4101. } else {
  4102. m_suffix = true;
  4103. m_len = width - 1;
  4104. }
  4105. }
  4106. }
  4107. auto indent() const -> size_t {
  4108. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  4109. return initial == std::string::npos ? m_column.m_indent : initial;
  4110. }
  4111. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  4112. return std::string( indent(), ' ' ) + (m_suffix ? plain + "-" : plain);
  4113. }
  4114. public:
  4115. explicit iterator( Column const& column ) : m_column( column ) {
  4116. assert( m_column.m_width > m_column.m_indent );
  4117. assert( m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent );
  4118. calcLength();
  4119. if( m_len == 0 )
  4120. m_stringIndex++; // Empty string
  4121. }
  4122. auto operator *() const -> std::string {
  4123. assert( m_stringIndex < m_column.m_strings.size() );
  4124. assert( m_pos <= m_end );
  4125. if( m_pos + m_column.m_width < m_end )
  4126. return addIndentAndSuffix(line().substr(m_pos, m_len));
  4127. else
  4128. return addIndentAndSuffix(line().substr(m_pos, m_end - m_pos));
  4129. }
  4130. auto operator ++() -> iterator& {
  4131. m_pos += m_len;
  4132. if( m_pos < line().size() && line()[m_pos] == '\n' )
  4133. m_pos += 1;
  4134. else
  4135. while( m_pos < line().size() && isWhitespace( line()[m_pos] ) )
  4136. ++m_pos;
  4137. if( m_pos == line().size() ) {
  4138. m_pos = 0;
  4139. ++m_stringIndex;
  4140. }
  4141. if( m_stringIndex < m_column.m_strings.size() )
  4142. calcLength();
  4143. return *this;
  4144. }
  4145. auto operator ++(int) -> iterator {
  4146. iterator prev( *this );
  4147. operator++();
  4148. return prev;
  4149. }
  4150. auto operator ==( iterator const& other ) const -> bool {
  4151. return
  4152. m_pos == other.m_pos &&
  4153. m_stringIndex == other.m_stringIndex &&
  4154. &m_column == &other.m_column;
  4155. }
  4156. auto operator !=( iterator const& other ) const -> bool {
  4157. return !operator==( other );
  4158. }
  4159. };
  4160. using const_iterator = iterator;
  4161. explicit Column( std::string const& text ) { m_strings.push_back( text ); }
  4162. auto width( size_t newWidth ) -> Column& {
  4163. assert( newWidth > 0 );
  4164. m_width = newWidth;
  4165. return *this;
  4166. }
  4167. auto indent( size_t newIndent ) -> Column& {
  4168. m_indent = newIndent;
  4169. return *this;
  4170. }
  4171. auto initialIndent( size_t newIndent ) -> Column& {
  4172. m_initialIndent = newIndent;
  4173. return *this;
  4174. }
  4175. auto width() const -> size_t { return m_width; }
  4176. auto begin() const -> iterator { return iterator( *this ); }
  4177. auto end() const -> iterator { return { *this, m_strings.size() }; }
  4178. inline friend std::ostream& operator << ( std::ostream& os, Column const& col ) {
  4179. bool first = true;
  4180. for( auto line : col ) {
  4181. if( first )
  4182. first = false;
  4183. else
  4184. os << "\n";
  4185. os << line;
  4186. }
  4187. return os;
  4188. }
  4189. auto operator + ( Column const& other ) -> Columns;
  4190. auto toString() const -> std::string {
  4191. std::ostringstream oss;
  4192. oss << *this;
  4193. return oss.str();
  4194. }
  4195. };
  4196. class Spacer : public Column {
  4197. public:
  4198. explicit Spacer( size_t spaceWidth ) : Column( "" ) {
  4199. width( spaceWidth );
  4200. }
  4201. };
  4202. class Columns {
  4203. std::vector<Column> m_columns;
  4204. public:
  4205. class iterator {
  4206. friend Columns;
  4207. struct EndTag {};
  4208. std::vector<Column> const& m_columns;
  4209. std::vector<Column::iterator> m_iterators;
  4210. size_t m_activeIterators;
  4211. iterator( Columns const& columns, EndTag )
  4212. : m_columns( columns.m_columns ),
  4213. m_activeIterators( 0 )
  4214. {
  4215. m_iterators.reserve( m_columns.size() );
  4216. for( auto const& col : m_columns )
  4217. m_iterators.push_back( col.end() );
  4218. }
  4219. public:
  4220. explicit iterator( Columns const& columns )
  4221. : m_columns( columns.m_columns ),
  4222. m_activeIterators( m_columns.size() )
  4223. {
  4224. m_iterators.reserve( m_columns.size() );
  4225. for( auto const& col : m_columns )
  4226. m_iterators.push_back( col.begin() );
  4227. }
  4228. auto operator ==( iterator const& other ) const -> bool {
  4229. return m_iterators == other.m_iterators;
  4230. }
  4231. auto operator !=( iterator const& other ) const -> bool {
  4232. return m_iterators != other.m_iterators;
  4233. }
  4234. auto operator *() const -> std::string {
  4235. std::string row, padding;
  4236. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4237. auto width = m_columns[i].width();
  4238. if( m_iterators[i] != m_columns[i].end() ) {
  4239. std::string col = *m_iterators[i];
  4240. row += padding + col;
  4241. if( col.size() < width )
  4242. padding = std::string( width - col.size(), ' ' );
  4243. else
  4244. padding = "";
  4245. }
  4246. else {
  4247. padding += std::string( width, ' ' );
  4248. }
  4249. }
  4250. return row;
  4251. }
  4252. auto operator ++() -> iterator& {
  4253. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4254. if (m_iterators[i] != m_columns[i].end())
  4255. ++m_iterators[i];
  4256. }
  4257. return *this;
  4258. }
  4259. auto operator ++(int) -> iterator {
  4260. iterator prev( *this );
  4261. operator++();
  4262. return prev;
  4263. }
  4264. };
  4265. using const_iterator = iterator;
  4266. auto begin() const -> iterator { return iterator( *this ); }
  4267. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  4268. auto operator += ( Column const& col ) -> Columns& {
  4269. m_columns.push_back( col );
  4270. return *this;
  4271. }
  4272. auto operator + ( Column const& col ) -> Columns {
  4273. Columns combined = *this;
  4274. combined += col;
  4275. return combined;
  4276. }
  4277. inline friend std::ostream& operator << ( std::ostream& os, Columns const& cols ) {
  4278. bool first = true;
  4279. for( auto line : cols ) {
  4280. if( first )
  4281. first = false;
  4282. else
  4283. os << "\n";
  4284. os << line;
  4285. }
  4286. return os;
  4287. }
  4288. auto toString() const -> std::string {
  4289. std::ostringstream oss;
  4290. oss << *this;
  4291. return oss.str();
  4292. }
  4293. };
  4294. inline auto Column::operator + ( Column const& other ) -> Columns {
  4295. Columns cols;
  4296. cols += *this;
  4297. cols += other;
  4298. return cols;
  4299. }
  4300. }}} // namespace Catch::clara::TextFlow
  4301. // ----------- end of #include from clara_textflow.hpp -----------
  4302. // ........... back in clara.hpp
  4303. #include <memory>
  4304. #include <set>
  4305. #include <algorithm>
  4306. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  4307. #define CATCH_PLATFORM_WINDOWS
  4308. #endif
  4309. namespace Catch { namespace clara {
  4310. namespace detail {
  4311. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  4312. template<typename L>
  4313. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  4314. template<typename ClassT, typename ReturnT, typename... Args>
  4315. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  4316. static const bool isValid = false;
  4317. };
  4318. template<typename ClassT, typename ReturnT, typename ArgT>
  4319. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  4320. static const bool isValid = true;
  4321. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  4322. using ReturnType = ReturnT;
  4323. };
  4324. class TokenStream;
  4325. // Transport for raw args (copied from main args, or supplied via init list for testing)
  4326. class Args {
  4327. friend TokenStream;
  4328. std::string m_exeName;
  4329. std::vector<std::string> m_args;
  4330. public:
  4331. Args( int argc, char *argv[] ) {
  4332. m_exeName = argv[0];
  4333. for( int i = 1; i < argc; ++i )
  4334. m_args.push_back( argv[i] );
  4335. }
  4336. Args( std::initializer_list<std::string> args )
  4337. : m_exeName( *args.begin() ),
  4338. m_args( args.begin()+1, args.end() )
  4339. {}
  4340. auto exeName() const -> std::string {
  4341. return m_exeName;
  4342. }
  4343. };
  4344. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  4345. // may encode an option + its argument if the : or = form is used
  4346. enum class TokenType {
  4347. Option, Argument
  4348. };
  4349. struct Token {
  4350. TokenType type;
  4351. std::string token;
  4352. };
  4353. inline auto isOptPrefix( char c ) -> bool {
  4354. return c == '-'
  4355. #ifdef CATCH_PLATFORM_WINDOWS
  4356. || c == '/'
  4357. #endif
  4358. ;
  4359. }
  4360. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  4361. class TokenStream {
  4362. using Iterator = std::vector<std::string>::const_iterator;
  4363. Iterator it;
  4364. Iterator itEnd;
  4365. std::vector<Token> m_tokenBuffer;
  4366. void loadBuffer() {
  4367. m_tokenBuffer.resize( 0 );
  4368. // Skip any empty strings
  4369. while( it != itEnd && it->empty() )
  4370. ++it;
  4371. if( it != itEnd ) {
  4372. auto const &next = *it;
  4373. if( isOptPrefix( next[0] ) ) {
  4374. auto delimiterPos = next.find_first_of( " :=" );
  4375. if( delimiterPos != std::string::npos ) {
  4376. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  4377. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  4378. } else {
  4379. if( next[1] != '-' && next.size() > 2 ) {
  4380. std::string opt = "- ";
  4381. for( size_t i = 1; i < next.size(); ++i ) {
  4382. opt[1] = next[i];
  4383. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  4384. }
  4385. } else {
  4386. m_tokenBuffer.push_back( { TokenType::Option, next } );
  4387. }
  4388. }
  4389. } else {
  4390. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  4391. }
  4392. }
  4393. }
  4394. public:
  4395. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  4396. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  4397. loadBuffer();
  4398. }
  4399. explicit operator bool() const {
  4400. return !m_tokenBuffer.empty() || it != itEnd;
  4401. }
  4402. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  4403. auto operator*() const -> Token {
  4404. assert( !m_tokenBuffer.empty() );
  4405. return m_tokenBuffer.front();
  4406. }
  4407. auto operator->() const -> Token const * {
  4408. assert( !m_tokenBuffer.empty() );
  4409. return &m_tokenBuffer.front();
  4410. }
  4411. auto operator++() -> TokenStream & {
  4412. if( m_tokenBuffer.size() >= 2 ) {
  4413. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  4414. } else {
  4415. if( it != itEnd )
  4416. ++it;
  4417. loadBuffer();
  4418. }
  4419. return *this;
  4420. }
  4421. };
  4422. class ResultBase {
  4423. public:
  4424. enum Type {
  4425. Ok, LogicError, RuntimeError
  4426. };
  4427. protected:
  4428. ResultBase( Type type ) : m_type( type ) {}
  4429. virtual ~ResultBase() = default;
  4430. virtual void enforceOk() const = 0;
  4431. Type m_type;
  4432. };
  4433. template<typename T>
  4434. class ResultValueBase : public ResultBase {
  4435. public:
  4436. auto value() const -> T const & {
  4437. enforceOk();
  4438. return m_value;
  4439. }
  4440. protected:
  4441. ResultValueBase( Type type ) : ResultBase( type ) {}
  4442. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  4443. if( m_type == ResultBase::Ok )
  4444. new( &m_value ) T( other.m_value );
  4445. }
  4446. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  4447. new( &m_value ) T( value );
  4448. }
  4449. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  4450. if( m_type == ResultBase::Ok )
  4451. m_value.~T();
  4452. ResultBase::operator=(other);
  4453. if( m_type == ResultBase::Ok )
  4454. new( &m_value ) T( other.m_value );
  4455. return *this;
  4456. }
  4457. ~ResultValueBase() override {
  4458. if( m_type == Ok )
  4459. m_value.~T();
  4460. }
  4461. union {
  4462. T m_value;
  4463. };
  4464. };
  4465. template<>
  4466. class ResultValueBase<void> : public ResultBase {
  4467. protected:
  4468. using ResultBase::ResultBase;
  4469. };
  4470. template<typename T = void>
  4471. class BasicResult : public ResultValueBase<T> {
  4472. public:
  4473. template<typename U>
  4474. explicit BasicResult( BasicResult<U> const &other )
  4475. : ResultValueBase<T>( other.type() ),
  4476. m_errorMessage( other.errorMessage() )
  4477. {
  4478. assert( type() != ResultBase::Ok );
  4479. }
  4480. template<typename U>
  4481. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  4482. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  4483. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  4484. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  4485. explicit operator bool() const { return m_type == ResultBase::Ok; }
  4486. auto type() const -> ResultBase::Type { return m_type; }
  4487. auto errorMessage() const -> std::string { return m_errorMessage; }
  4488. protected:
  4489. void enforceOk() const override {
  4490. // !TBD: If no exceptions, std::terminate here or something
  4491. switch( m_type ) {
  4492. case ResultBase::LogicError:
  4493. throw std::logic_error( m_errorMessage );
  4494. case ResultBase::RuntimeError:
  4495. throw std::runtime_error( m_errorMessage );
  4496. case ResultBase::Ok:
  4497. break;
  4498. }
  4499. }
  4500. std::string m_errorMessage; // Only populated if resultType is an error
  4501. BasicResult( ResultBase::Type type, std::string const &message )
  4502. : ResultValueBase<T>(type),
  4503. m_errorMessage(message)
  4504. {
  4505. assert( m_type != ResultBase::Ok );
  4506. }
  4507. using ResultValueBase<T>::ResultValueBase;
  4508. using ResultBase::m_type;
  4509. };
  4510. enum class ParseResultType {
  4511. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  4512. };
  4513. class ParseState {
  4514. public:
  4515. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  4516. : m_type(type),
  4517. m_remainingTokens( remainingTokens )
  4518. {}
  4519. auto type() const -> ParseResultType { return m_type; }
  4520. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  4521. private:
  4522. ParseResultType m_type;
  4523. TokenStream m_remainingTokens;
  4524. };
  4525. using Result = BasicResult<void>;
  4526. using ParserResult = BasicResult<ParseResultType>;
  4527. using InternalParseResult = BasicResult<ParseState>;
  4528. struct HelpColumns {
  4529. std::string left;
  4530. std::string right;
  4531. };
  4532. template<typename T>
  4533. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  4534. std::stringstream ss;
  4535. ss << source;
  4536. ss >> target;
  4537. if( ss.fail() )
  4538. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  4539. else
  4540. return ParserResult::ok( ParseResultType::Matched );
  4541. }
  4542. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  4543. target = source;
  4544. return ParserResult::ok( ParseResultType::Matched );
  4545. }
  4546. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  4547. std::string srcLC = source;
  4548. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( ::tolower(c) ); } );
  4549. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  4550. target = true;
  4551. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  4552. target = false;
  4553. else
  4554. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  4555. return ParserResult::ok( ParseResultType::Matched );
  4556. }
  4557. struct NonCopyable {
  4558. NonCopyable() = default;
  4559. NonCopyable( NonCopyable const & ) = delete;
  4560. NonCopyable( NonCopyable && ) = delete;
  4561. NonCopyable &operator=( NonCopyable const & ) = delete;
  4562. NonCopyable &operator=( NonCopyable && ) = delete;
  4563. };
  4564. struct BoundRef : NonCopyable {
  4565. virtual ~BoundRef() = default;
  4566. virtual auto isContainer() const -> bool { return false; }
  4567. virtual auto isFlag() const -> bool { return false; }
  4568. };
  4569. struct BoundValueRefBase : BoundRef {
  4570. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  4571. };
  4572. struct BoundFlagRefBase : BoundRef {
  4573. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  4574. virtual auto isFlag() const -> bool { return true; }
  4575. };
  4576. template<typename T>
  4577. struct BoundValueRef : BoundValueRefBase {
  4578. T &m_ref;
  4579. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  4580. auto setValue( std::string const &arg ) -> ParserResult override {
  4581. return convertInto( arg, m_ref );
  4582. }
  4583. };
  4584. template<typename T>
  4585. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  4586. std::vector<T> &m_ref;
  4587. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  4588. auto isContainer() const -> bool override { return true; }
  4589. auto setValue( std::string const &arg ) -> ParserResult override {
  4590. T temp;
  4591. auto result = convertInto( arg, temp );
  4592. if( result )
  4593. m_ref.push_back( temp );
  4594. return result;
  4595. }
  4596. };
  4597. struct BoundFlagRef : BoundFlagRefBase {
  4598. bool &m_ref;
  4599. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  4600. auto setFlag( bool flag ) -> ParserResult override {
  4601. m_ref = flag;
  4602. return ParserResult::ok( ParseResultType::Matched );
  4603. }
  4604. };
  4605. template<typename ReturnType>
  4606. struct LambdaInvoker {
  4607. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  4608. template<typename L, typename ArgType>
  4609. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4610. return lambda( arg );
  4611. }
  4612. };
  4613. template<>
  4614. struct LambdaInvoker<void> {
  4615. template<typename L, typename ArgType>
  4616. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4617. lambda( arg );
  4618. return ParserResult::ok( ParseResultType::Matched );
  4619. }
  4620. };
  4621. template<typename ArgType, typename L>
  4622. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  4623. ArgType temp{};
  4624. auto result = convertInto( arg, temp );
  4625. return !result
  4626. ? result
  4627. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  4628. }
  4629. template<typename L>
  4630. struct BoundLambda : BoundValueRefBase {
  4631. L m_lambda;
  4632. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4633. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  4634. auto setValue( std::string const &arg ) -> ParserResult override {
  4635. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  4636. }
  4637. };
  4638. template<typename L>
  4639. struct BoundFlagLambda : BoundFlagRefBase {
  4640. L m_lambda;
  4641. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4642. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  4643. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  4644. auto setFlag( bool flag ) -> ParserResult override {
  4645. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  4646. }
  4647. };
  4648. enum class Optionality { Optional, Required };
  4649. struct Parser;
  4650. class ParserBase {
  4651. public:
  4652. virtual ~ParserBase() = default;
  4653. virtual auto validate() const -> Result { return Result::ok(); }
  4654. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  4655. virtual auto cardinality() const -> size_t { return 1; }
  4656. auto parse( Args const &args ) const -> InternalParseResult {
  4657. return parse( args.exeName(), TokenStream( args ) );
  4658. }
  4659. };
  4660. template<typename DerivedT>
  4661. class ComposableParserImpl : public ParserBase {
  4662. public:
  4663. template<typename T>
  4664. auto operator|( T const &other ) const -> Parser;
  4665. template<typename T>
  4666. auto operator+( T const &other ) const -> Parser;
  4667. };
  4668. // Common code and state for Args and Opts
  4669. template<typename DerivedT>
  4670. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  4671. protected:
  4672. Optionality m_optionality = Optionality::Optional;
  4673. std::shared_ptr<BoundRef> m_ref;
  4674. std::string m_hint;
  4675. std::string m_description;
  4676. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  4677. public:
  4678. template<typename T>
  4679. ParserRefImpl( T &ref, std::string const &hint )
  4680. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  4681. m_hint( hint )
  4682. {}
  4683. template<typename LambdaT>
  4684. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  4685. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  4686. m_hint(hint)
  4687. {}
  4688. auto operator()( std::string const &description ) -> DerivedT & {
  4689. m_description = description;
  4690. return static_cast<DerivedT &>( *this );
  4691. }
  4692. auto optional() -> DerivedT & {
  4693. m_optionality = Optionality::Optional;
  4694. return static_cast<DerivedT &>( *this );
  4695. };
  4696. auto required() -> DerivedT & {
  4697. m_optionality = Optionality::Required;
  4698. return static_cast<DerivedT &>( *this );
  4699. };
  4700. auto isOptional() const -> bool {
  4701. return m_optionality == Optionality::Optional;
  4702. }
  4703. auto cardinality() const -> size_t override {
  4704. if( m_ref->isContainer() )
  4705. return 0;
  4706. else
  4707. return 1;
  4708. }
  4709. auto hint() const -> std::string { return m_hint; }
  4710. };
  4711. class ExeName : public ComposableParserImpl<ExeName> {
  4712. std::shared_ptr<std::string> m_name;
  4713. std::shared_ptr<BoundValueRefBase> m_ref;
  4714. template<typename LambdaT>
  4715. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  4716. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  4717. }
  4718. public:
  4719. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  4720. explicit ExeName( std::string &ref ) : ExeName() {
  4721. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  4722. }
  4723. template<typename LambdaT>
  4724. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  4725. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  4726. }
  4727. // The exe name is not parsed out of the normal tokens, but is handled specially
  4728. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4729. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  4730. }
  4731. auto name() const -> std::string { return *m_name; }
  4732. auto set( std::string const& newName ) -> ParserResult {
  4733. auto lastSlash = newName.find_last_of( "\\/" );
  4734. auto filename = ( lastSlash == std::string::npos )
  4735. ? newName
  4736. : newName.substr( lastSlash+1 );
  4737. *m_name = filename;
  4738. if( m_ref )
  4739. return m_ref->setValue( filename );
  4740. else
  4741. return ParserResult::ok( ParseResultType::Matched );
  4742. }
  4743. };
  4744. class Arg : public ParserRefImpl<Arg> {
  4745. public:
  4746. using ParserRefImpl::ParserRefImpl;
  4747. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  4748. auto validationResult = validate();
  4749. if( !validationResult )
  4750. return InternalParseResult( validationResult );
  4751. auto remainingTokens = tokens;
  4752. auto const &token = *remainingTokens;
  4753. if( token.type != TokenType::Argument )
  4754. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  4755. assert( !m_ref->isFlag() );
  4756. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  4757. auto result = valueRef->setValue( remainingTokens->token );
  4758. if( !result )
  4759. return InternalParseResult( result );
  4760. else
  4761. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  4762. }
  4763. };
  4764. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  4765. #ifdef CATCH_PLATFORM_WINDOWS
  4766. if( optName[0] == '/' )
  4767. return "-" + optName.substr( 1 );
  4768. else
  4769. #endif
  4770. return optName;
  4771. }
  4772. class Opt : public ParserRefImpl<Opt> {
  4773. protected:
  4774. std::vector<std::string> m_optNames;
  4775. public:
  4776. template<typename LambdaT>
  4777. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  4778. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  4779. template<typename LambdaT>
  4780. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4781. template<typename T>
  4782. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4783. auto operator[]( std::string const &optName ) -> Opt & {
  4784. m_optNames.push_back( optName );
  4785. return *this;
  4786. }
  4787. auto getHelpColumns() const -> std::vector<HelpColumns> {
  4788. std::ostringstream oss;
  4789. bool first = true;
  4790. for( auto const &opt : m_optNames ) {
  4791. if (first)
  4792. first = false;
  4793. else
  4794. oss << ", ";
  4795. oss << opt;
  4796. }
  4797. if( !m_hint.empty() )
  4798. oss << " <" << m_hint << ">";
  4799. return { { oss.str(), m_description } };
  4800. }
  4801. auto isMatch( std::string const &optToken ) const -> bool {
  4802. auto normalisedToken = normaliseOpt( optToken );
  4803. for( auto const &name : m_optNames ) {
  4804. if( normaliseOpt( name ) == normalisedToken )
  4805. return true;
  4806. }
  4807. return false;
  4808. }
  4809. using ParserBase::parse;
  4810. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4811. auto validationResult = validate();
  4812. if( !validationResult )
  4813. return InternalParseResult( validationResult );
  4814. auto remainingTokens = tokens;
  4815. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  4816. auto const &token = *remainingTokens;
  4817. if( isMatch(token.token ) ) {
  4818. if( m_ref->isFlag() ) {
  4819. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  4820. auto result = flagRef->setFlag( true );
  4821. if( !result )
  4822. return InternalParseResult( result );
  4823. if( result.value() == ParseResultType::ShortCircuitAll )
  4824. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  4825. } else {
  4826. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  4827. ++remainingTokens;
  4828. if( !remainingTokens )
  4829. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  4830. auto const &argToken = *remainingTokens;
  4831. if( argToken.type != TokenType::Argument )
  4832. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  4833. auto result = valueRef->setValue( argToken.token );
  4834. if( !result )
  4835. return InternalParseResult( result );
  4836. if( result.value() == ParseResultType::ShortCircuitAll )
  4837. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  4838. }
  4839. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  4840. }
  4841. }
  4842. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  4843. }
  4844. auto validate() const -> Result override {
  4845. if( m_optNames.empty() )
  4846. return Result::logicError( "No options supplied to Opt" );
  4847. for( auto const &name : m_optNames ) {
  4848. if( name.empty() )
  4849. return Result::logicError( "Option name cannot be empty" );
  4850. #ifdef CATCH_PLATFORM_WINDOWS
  4851. if( name[0] != '-' && name[0] != '/' )
  4852. return Result::logicError( "Option name must begin with '-' or '/'" );
  4853. #else
  4854. if( name[0] != '-' )
  4855. return Result::logicError( "Option name must begin with '-'" );
  4856. #endif
  4857. }
  4858. return ParserRefImpl::validate();
  4859. }
  4860. };
  4861. struct Help : Opt {
  4862. Help( bool &showHelpFlag )
  4863. : Opt([&]( bool flag ) {
  4864. showHelpFlag = flag;
  4865. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  4866. })
  4867. {
  4868. static_cast<Opt &>( *this )
  4869. ("display usage information")
  4870. ["-?"]["-h"]["--help"]
  4871. .optional();
  4872. }
  4873. };
  4874. struct Parser : ParserBase {
  4875. mutable ExeName m_exeName;
  4876. std::vector<Opt> m_options;
  4877. std::vector<Arg> m_args;
  4878. auto operator|=( ExeName const &exeName ) -> Parser & {
  4879. m_exeName = exeName;
  4880. return *this;
  4881. }
  4882. auto operator|=( Arg const &arg ) -> Parser & {
  4883. m_args.push_back(arg);
  4884. return *this;
  4885. }
  4886. auto operator|=( Opt const &opt ) -> Parser & {
  4887. m_options.push_back(opt);
  4888. return *this;
  4889. }
  4890. auto operator|=( Parser const &other ) -> Parser & {
  4891. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  4892. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  4893. return *this;
  4894. }
  4895. template<typename T>
  4896. auto operator|( T const &other ) const -> Parser {
  4897. return Parser( *this ) |= other;
  4898. }
  4899. // Forward deprecated interface with '+' instead of '|'
  4900. template<typename T>
  4901. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  4902. template<typename T>
  4903. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  4904. auto getHelpColumns() const -> std::vector<HelpColumns> {
  4905. std::vector<HelpColumns> cols;
  4906. for (auto const &o : m_options) {
  4907. auto childCols = o.getHelpColumns();
  4908. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  4909. }
  4910. return cols;
  4911. }
  4912. void writeToStream( std::ostream &os ) const {
  4913. if (!m_exeName.name().empty()) {
  4914. os << "usage:\n" << " " << m_exeName.name() << " ";
  4915. bool required = true, first = true;
  4916. for( auto const &arg : m_args ) {
  4917. if (first)
  4918. first = false;
  4919. else
  4920. os << " ";
  4921. if( arg.isOptional() && required ) {
  4922. os << "[";
  4923. required = false;
  4924. }
  4925. os << "<" << arg.hint() << ">";
  4926. if( arg.cardinality() == 0 )
  4927. os << " ... ";
  4928. }
  4929. if( !required )
  4930. os << "]";
  4931. if( !m_options.empty() )
  4932. os << " options";
  4933. os << "\n\nwhere options are:" << std::endl;
  4934. }
  4935. auto rows = getHelpColumns();
  4936. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  4937. size_t optWidth = 0;
  4938. for( auto const &cols : rows )
  4939. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  4940. optWidth = (std::min)(optWidth, consoleWidth/2);
  4941. for( auto const &cols : rows ) {
  4942. auto row =
  4943. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  4944. TextFlow::Spacer(4) +
  4945. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  4946. os << row << std::endl;
  4947. }
  4948. }
  4949. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  4950. parser.writeToStream( os );
  4951. return os;
  4952. }
  4953. auto validate() const -> Result override {
  4954. for( auto const &opt : m_options ) {
  4955. auto result = opt.validate();
  4956. if( !result )
  4957. return result;
  4958. }
  4959. for( auto const &arg : m_args ) {
  4960. auto result = arg.validate();
  4961. if( !result )
  4962. return result;
  4963. }
  4964. return Result::ok();
  4965. }
  4966. using ParserBase::parse;
  4967. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  4968. struct ParserInfo {
  4969. ParserBase const* parser = nullptr;
  4970. size_t count = 0;
  4971. };
  4972. const size_t totalParsers = m_options.size() + m_args.size();
  4973. assert( totalParsers < 512 );
  4974. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  4975. ParserInfo parseInfos[512];
  4976. {
  4977. size_t i = 0;
  4978. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  4979. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  4980. }
  4981. m_exeName.set( exeName );
  4982. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  4983. while( result.value().remainingTokens() ) {
  4984. bool tokenParsed = false;
  4985. for( size_t i = 0; i < totalParsers; ++i ) {
  4986. auto& parseInfo = parseInfos[i];
  4987. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  4988. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  4989. if (!result)
  4990. return result;
  4991. if (result.value().type() != ParseResultType::NoMatch) {
  4992. tokenParsed = true;
  4993. ++parseInfo.count;
  4994. break;
  4995. }
  4996. }
  4997. }
  4998. if( result.value().type() == ParseResultType::ShortCircuitAll )
  4999. return result;
  5000. if( !tokenParsed )
  5001. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  5002. }
  5003. // !TBD Check missing required options
  5004. return result;
  5005. }
  5006. };
  5007. template<typename DerivedT>
  5008. template<typename T>
  5009. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  5010. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  5011. }
  5012. } // namespace detail
  5013. // A Combined parser
  5014. using detail::Parser;
  5015. // A parser for options
  5016. using detail::Opt;
  5017. // A parser for arguments
  5018. using detail::Arg;
  5019. // Wrapper for argc, argv from main()
  5020. using detail::Args;
  5021. // Specifies the name of the executable
  5022. using detail::ExeName;
  5023. // Convenience wrapper for option parser that specifies the help option
  5024. using detail::Help;
  5025. // enum of result types from a parse
  5026. using detail::ParseResultType;
  5027. // Result type for parser operation
  5028. using detail::ParserResult;
  5029. }} // namespace Catch::clara
  5030. // end clara.hpp
  5031. #ifdef __clang__
  5032. #pragma clang diagnostic pop
  5033. #endif
  5034. // Restore Clara's value for console width, if present
  5035. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5036. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5037. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5038. #endif
  5039. // end catch_clara.h
  5040. namespace Catch {
  5041. clara::Parser makeCommandLineParser( ConfigData& config );
  5042. } // end namespace Catch
  5043. // end catch_commandline.h
  5044. #include <fstream>
  5045. #include <ctime>
  5046. namespace Catch {
  5047. clara::Parser makeCommandLineParser( ConfigData& config ) {
  5048. using namespace clara;
  5049. auto const setWarning = [&]( std::string const& warning ) {
  5050. if( warning != "NoAssertions" )
  5051. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  5052. config.warnings = static_cast<WarnAbout::What>( config.warnings | WarnAbout::NoAssertions );
  5053. return ParserResult::ok( ParseResultType::Matched );
  5054. };
  5055. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  5056. std::ifstream f( filename.c_str() );
  5057. if( !f.is_open() )
  5058. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  5059. std::string line;
  5060. while( std::getline( f, line ) ) {
  5061. line = trim(line);
  5062. if( !line.empty() && !startsWith( line, '#' ) ) {
  5063. if( !startsWith( line, '"' ) )
  5064. line = '"' + line + '"';
  5065. config.testsOrTags.push_back( line + ',' );
  5066. }
  5067. }
  5068. return ParserResult::ok( ParseResultType::Matched );
  5069. };
  5070. auto const setTestOrder = [&]( std::string const& order ) {
  5071. if( startsWith( "declared", order ) )
  5072. config.runOrder = RunTests::InDeclarationOrder;
  5073. else if( startsWith( "lexical", order ) )
  5074. config.runOrder = RunTests::InLexicographicalOrder;
  5075. else if( startsWith( "random", order ) )
  5076. config.runOrder = RunTests::InRandomOrder;
  5077. else
  5078. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  5079. return ParserResult::ok( ParseResultType::Matched );
  5080. };
  5081. auto const setRngSeed = [&]( std::string const& seed ) {
  5082. if( seed != "time" )
  5083. return clara::detail::convertInto( seed, config.rngSeed );
  5084. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  5085. return ParserResult::ok( ParseResultType::Matched );
  5086. };
  5087. auto const setColourUsage = [&]( std::string const& useColour ) {
  5088. auto mode = toLower( useColour );
  5089. if( mode == "yes" )
  5090. config.useColour = UseColour::Yes;
  5091. else if( mode == "no" )
  5092. config.useColour = UseColour::No;
  5093. else if( mode == "auto" )
  5094. config.useColour = UseColour::Auto;
  5095. else
  5096. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  5097. return ParserResult::ok( ParseResultType::Matched );
  5098. };
  5099. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  5100. auto keypressLc = toLower( keypress );
  5101. if( keypressLc == "start" )
  5102. config.waitForKeypress = WaitForKeypress::BeforeStart;
  5103. else if( keypressLc == "exit" )
  5104. config.waitForKeypress = WaitForKeypress::BeforeExit;
  5105. else if( keypressLc == "both" )
  5106. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  5107. else
  5108. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  5109. return ParserResult::ok( ParseResultType::Matched );
  5110. };
  5111. auto const setVerbosity = [&]( std::string const& verbosity ) {
  5112. auto lcVerbosity = toLower( verbosity );
  5113. if( lcVerbosity == "quiet" )
  5114. config.verbosity = Verbosity::Quiet;
  5115. else if( lcVerbosity == "normal" )
  5116. config.verbosity = Verbosity::Normal;
  5117. else if( lcVerbosity == "high" )
  5118. config.verbosity = Verbosity::High;
  5119. else
  5120. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  5121. return ParserResult::ok( ParseResultType::Matched );
  5122. };
  5123. auto cli
  5124. = ExeName( config.processName )
  5125. | Help( config.showHelp )
  5126. | Opt( config.listTests )
  5127. ["-l"]["--list-tests"]
  5128. ( "list all/matching test cases" )
  5129. | Opt( config.listTags )
  5130. ["-t"]["--list-tags"]
  5131. ( "list all/matching tags" )
  5132. | Opt( config.showSuccessfulTests )
  5133. ["-s"]["--success"]
  5134. ( "include successful tests in output" )
  5135. | Opt( config.shouldDebugBreak )
  5136. ["-b"]["--break"]
  5137. ( "break into debugger on failure" )
  5138. | Opt( config.noThrow )
  5139. ["-e"]["--nothrow"]
  5140. ( "skip exception tests" )
  5141. | Opt( config.showInvisibles )
  5142. ["-i"]["--invisibles"]
  5143. ( "show invisibles (tabs, newlines)" )
  5144. | Opt( config.outputFilename, "filename" )
  5145. ["-o"]["--out"]
  5146. ( "output filename" )
  5147. | Opt( config.reporterNames, "name" )
  5148. ["-r"]["--reporter"]
  5149. ( "reporter to use (defaults to console)" )
  5150. | Opt( config.name, "name" )
  5151. ["-n"]["--name"]
  5152. ( "suite name" )
  5153. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  5154. ["-a"]["--abort"]
  5155. ( "abort at first failure" )
  5156. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  5157. ["-x"]["--abortx"]
  5158. ( "abort after x failures" )
  5159. | Opt( setWarning, "warning name" )
  5160. ["-w"]["--warn"]
  5161. ( "enable warnings" )
  5162. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  5163. ["-d"]["--durations"]
  5164. ( "show test durations" )
  5165. | Opt( loadTestNamesFromFile, "filename" )
  5166. ["-f"]["--input-file"]
  5167. ( "load test names to run from a file" )
  5168. | Opt( config.filenamesAsTags )
  5169. ["-#"]["--filenames-as-tags"]
  5170. ( "adds a tag for the filename" )
  5171. | Opt( config.sectionsToRun, "section name" )
  5172. ["-c"]["--section"]
  5173. ( "specify section to run" )
  5174. | Opt( setVerbosity, "quiet|normal|high" )
  5175. ["-v"]["--verbosity"]
  5176. ( "set output verbosity" )
  5177. | Opt( config.listTestNamesOnly )
  5178. ["--list-test-names-only"]
  5179. ( "list all/matching test cases names only" )
  5180. | Opt( config.listReporters )
  5181. ["--list-reporters"]
  5182. ( "list all reporters" )
  5183. | Opt( setTestOrder, "decl|lex|rand" )
  5184. ["--order"]
  5185. ( "test case order (defaults to decl)" )
  5186. | Opt( setRngSeed, "'time'|number" )
  5187. ["--rng-seed"]
  5188. ( "set a specific seed for random numbers" )
  5189. | Opt( setColourUsage, "yes|no" )
  5190. ["--use-colour"]
  5191. ( "should output be colourised" )
  5192. | Opt( config.libIdentify )
  5193. ["--libidentify"]
  5194. ( "report name and version according to libidentify standard" )
  5195. | Opt( setWaitForKeypress, "start|exit|both" )
  5196. ["--wait-for-keypress"]
  5197. ( "waits for a keypress before exiting" )
  5198. | Opt( config.benchmarkResolutionMultiple, "multiplier" )
  5199. ["--benchmark-resolution-multiple"]
  5200. ( "multiple of clock resolution to run benchmarks" )
  5201. | Arg( config.testsOrTags, "test name|pattern|tags" )
  5202. ( "which test or tests to use" );
  5203. return cli;
  5204. }
  5205. } // end namespace Catch
  5206. // end catch_commandline.cpp
  5207. // start catch_common.cpp
  5208. #include <cstring>
  5209. #include <ostream>
  5210. namespace Catch {
  5211. bool SourceLineInfo::empty() const noexcept {
  5212. return file[0] == '\0';
  5213. }
  5214. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  5215. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  5216. }
  5217. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  5218. return line < other.line || ( line == other.line && (std::strcmp(file, other.file) < 0));
  5219. }
  5220. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  5221. #ifndef __GNUG__
  5222. os << info.file << '(' << info.line << ')';
  5223. #else
  5224. os << info.file << ':' << info.line;
  5225. #endif
  5226. return os;
  5227. }
  5228. std::string StreamEndStop::operator+() const {
  5229. return std::string();
  5230. }
  5231. NonCopyable::NonCopyable() = default;
  5232. NonCopyable::~NonCopyable() = default;
  5233. }
  5234. // end catch_common.cpp
  5235. // start catch_config.cpp
  5236. // start catch_enforce.h
  5237. #include <stdexcept>
  5238. #include <iosfwd>
  5239. #define CATCH_PREPARE_EXCEPTION( type, msg ) \
  5240. type( static_cast<std::ostringstream&&>( Catch::ReusableStringStream().get() << msg ).str() )
  5241. #define CATCH_INTERNAL_ERROR( msg ) \
  5242. throw CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg);
  5243. #define CATCH_ERROR( msg ) \
  5244. throw CATCH_PREPARE_EXCEPTION( std::domain_error, msg )
  5245. #define CATCH_ENFORCE( condition, msg ) \
  5246. do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
  5247. // end catch_enforce.h
  5248. namespace Catch {
  5249. Config::Config( ConfigData const& data )
  5250. : m_data( data ),
  5251. m_stream( openStream() )
  5252. {
  5253. if( !data.testsOrTags.empty() ) {
  5254. TestSpecParser parser( ITagAliasRegistry::get() );
  5255. for( auto const& testOrTags : data.testsOrTags )
  5256. parser.parse( testOrTags );
  5257. m_testSpec = parser.testSpec();
  5258. }
  5259. }
  5260. std::string const& Config::getFilename() const {
  5261. return m_data.outputFilename ;
  5262. }
  5263. bool Config::listTests() const { return m_data.listTests; }
  5264. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  5265. bool Config::listTags() const { return m_data.listTags; }
  5266. bool Config::listReporters() const { return m_data.listReporters; }
  5267. std::string Config::getProcessName() const { return m_data.processName; }
  5268. std::vector<std::string> const& Config::getReporterNames() const { return m_data.reporterNames; }
  5269. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  5270. TestSpec const& Config::testSpec() const { return m_testSpec; }
  5271. bool Config::showHelp() const { return m_data.showHelp; }
  5272. // IConfig interface
  5273. bool Config::allowThrows() const { return !m_data.noThrow; }
  5274. std::ostream& Config::stream() const { return m_stream->stream(); }
  5275. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  5276. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  5277. bool Config::warnAboutMissingAssertions() const { return m_data.warnings & WarnAbout::NoAssertions; }
  5278. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  5279. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  5280. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  5281. int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
  5282. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  5283. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  5284. int Config::abortAfter() const { return m_data.abortAfter; }
  5285. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  5286. Verbosity Config::verbosity() const { return m_data.verbosity; }
  5287. IStream const* Config::openStream() {
  5288. return Catch::makeStream(m_data.outputFilename);
  5289. }
  5290. } // end namespace Catch
  5291. // end catch_config.cpp
  5292. // start catch_console_colour.cpp
  5293. #if defined(__clang__)
  5294. # pragma clang diagnostic push
  5295. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  5296. #endif
  5297. // start catch_errno_guard.h
  5298. namespace Catch {
  5299. class ErrnoGuard {
  5300. public:
  5301. ErrnoGuard();
  5302. ~ErrnoGuard();
  5303. private:
  5304. int m_oldErrno;
  5305. };
  5306. }
  5307. // end catch_errno_guard.h
  5308. #include <sstream>
  5309. namespace Catch {
  5310. namespace {
  5311. struct IColourImpl {
  5312. virtual ~IColourImpl() = default;
  5313. virtual void use( Colour::Code _colourCode ) = 0;
  5314. };
  5315. struct NoColourImpl : IColourImpl {
  5316. void use( Colour::Code ) {}
  5317. static IColourImpl* instance() {
  5318. static NoColourImpl s_instance;
  5319. return &s_instance;
  5320. }
  5321. };
  5322. } // anon namespace
  5323. } // namespace Catch
  5324. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  5325. # ifdef CATCH_PLATFORM_WINDOWS
  5326. # define CATCH_CONFIG_COLOUR_WINDOWS
  5327. # else
  5328. # define CATCH_CONFIG_COLOUR_ANSI
  5329. # endif
  5330. #endif
  5331. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  5332. namespace Catch {
  5333. namespace {
  5334. class Win32ColourImpl : public IColourImpl {
  5335. public:
  5336. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  5337. {
  5338. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  5339. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  5340. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  5341. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  5342. }
  5343. virtual void use( Colour::Code _colourCode ) override {
  5344. switch( _colourCode ) {
  5345. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  5346. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5347. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  5348. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  5349. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  5350. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  5351. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  5352. case Colour::Grey: return setTextAttribute( 0 );
  5353. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  5354. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  5355. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  5356. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5357. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  5358. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5359. default:
  5360. CATCH_ERROR( "Unknown colour requested" );
  5361. }
  5362. }
  5363. private:
  5364. void setTextAttribute( WORD _textAttribute ) {
  5365. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  5366. }
  5367. HANDLE stdoutHandle;
  5368. WORD originalForegroundAttributes;
  5369. WORD originalBackgroundAttributes;
  5370. };
  5371. IColourImpl* platformColourInstance() {
  5372. static Win32ColourImpl s_instance;
  5373. IConfigPtr config = getCurrentContext().getConfig();
  5374. UseColour::YesOrNo colourMode = config
  5375. ? config->useColour()
  5376. : UseColour::Auto;
  5377. if( colourMode == UseColour::Auto )
  5378. colourMode = UseColour::Yes;
  5379. return colourMode == UseColour::Yes
  5380. ? &s_instance
  5381. : NoColourImpl::instance();
  5382. }
  5383. } // end anon namespace
  5384. } // end namespace Catch
  5385. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  5386. #include <unistd.h>
  5387. namespace Catch {
  5388. namespace {
  5389. // use POSIX/ ANSI console terminal codes
  5390. // Thanks to Adam Strzelecki for original contribution
  5391. // (http://github.com/nanoant)
  5392. // https://github.com/philsquared/Catch/pull/131
  5393. class PosixColourImpl : public IColourImpl {
  5394. public:
  5395. virtual void use( Colour::Code _colourCode ) override {
  5396. switch( _colourCode ) {
  5397. case Colour::None:
  5398. case Colour::White: return setColour( "[0m" );
  5399. case Colour::Red: return setColour( "[0;31m" );
  5400. case Colour::Green: return setColour( "[0;32m" );
  5401. case Colour::Blue: return setColour( "[0;34m" );
  5402. case Colour::Cyan: return setColour( "[0;36m" );
  5403. case Colour::Yellow: return setColour( "[0;33m" );
  5404. case Colour::Grey: return setColour( "[1;30m" );
  5405. case Colour::LightGrey: return setColour( "[0;37m" );
  5406. case Colour::BrightRed: return setColour( "[1;31m" );
  5407. case Colour::BrightGreen: return setColour( "[1;32m" );
  5408. case Colour::BrightWhite: return setColour( "[1;37m" );
  5409. case Colour::BrightYellow: return setColour( "[1;33m" );
  5410. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5411. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  5412. }
  5413. }
  5414. static IColourImpl* instance() {
  5415. static PosixColourImpl s_instance;
  5416. return &s_instance;
  5417. }
  5418. private:
  5419. void setColour( const char* _escapeCode ) {
  5420. Catch::cout() << '\033' << _escapeCode;
  5421. }
  5422. };
  5423. bool useColourOnPlatform() {
  5424. return
  5425. #ifdef CATCH_PLATFORM_MAC
  5426. !isDebuggerActive() &&
  5427. #endif
  5428. isatty(STDOUT_FILENO);
  5429. }
  5430. IColourImpl* platformColourInstance() {
  5431. ErrnoGuard guard;
  5432. IConfigPtr config = getCurrentContext().getConfig();
  5433. UseColour::YesOrNo colourMode = config
  5434. ? config->useColour()
  5435. : UseColour::Auto;
  5436. if( colourMode == UseColour::Auto )
  5437. colourMode = useColourOnPlatform()
  5438. ? UseColour::Yes
  5439. : UseColour::No;
  5440. return colourMode == UseColour::Yes
  5441. ? PosixColourImpl::instance()
  5442. : NoColourImpl::instance();
  5443. }
  5444. } // end anon namespace
  5445. } // end namespace Catch
  5446. #else // not Windows or ANSI ///////////////////////////////////////////////
  5447. namespace Catch {
  5448. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  5449. } // end namespace Catch
  5450. #endif // Windows/ ANSI/ None
  5451. namespace Catch {
  5452. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  5453. Colour::Colour( Colour&& rhs ) noexcept {
  5454. m_moved = rhs.m_moved;
  5455. rhs.m_moved = true;
  5456. }
  5457. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  5458. m_moved = rhs.m_moved;
  5459. rhs.m_moved = true;
  5460. return *this;
  5461. }
  5462. Colour::~Colour(){ if( !m_moved ) use( None ); }
  5463. void Colour::use( Code _colourCode ) {
  5464. static IColourImpl* impl = platformColourInstance();
  5465. impl->use( _colourCode );
  5466. }
  5467. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  5468. return os;
  5469. }
  5470. } // end namespace Catch
  5471. #if defined(__clang__)
  5472. # pragma clang diagnostic pop
  5473. #endif
  5474. // end catch_console_colour.cpp
  5475. // start catch_context.cpp
  5476. namespace Catch {
  5477. class Context : public IMutableContext, NonCopyable {
  5478. public: // IContext
  5479. virtual IResultCapture* getResultCapture() override {
  5480. return m_resultCapture;
  5481. }
  5482. virtual IRunner* getRunner() override {
  5483. return m_runner;
  5484. }
  5485. virtual IConfigPtr const& getConfig() const override {
  5486. return m_config;
  5487. }
  5488. virtual ~Context() override;
  5489. public: // IMutableContext
  5490. virtual void setResultCapture( IResultCapture* resultCapture ) override {
  5491. m_resultCapture = resultCapture;
  5492. }
  5493. virtual void setRunner( IRunner* runner ) override {
  5494. m_runner = runner;
  5495. }
  5496. virtual void setConfig( IConfigPtr const& config ) override {
  5497. m_config = config;
  5498. }
  5499. friend IMutableContext& getCurrentMutableContext();
  5500. private:
  5501. IConfigPtr m_config;
  5502. IRunner* m_runner = nullptr;
  5503. IResultCapture* m_resultCapture = nullptr;
  5504. };
  5505. IMutableContext *IMutableContext::currentContext = nullptr;
  5506. void IMutableContext::createContext()
  5507. {
  5508. currentContext = new Context();
  5509. }
  5510. void cleanUpContext() {
  5511. delete IMutableContext::currentContext;
  5512. IMutableContext::currentContext = nullptr;
  5513. }
  5514. IContext::~IContext() = default;
  5515. IMutableContext::~IMutableContext() = default;
  5516. Context::~Context() = default;
  5517. }
  5518. // end catch_context.cpp
  5519. // start catch_debug_console.cpp
  5520. // start catch_debug_console.h
  5521. #include <string>
  5522. namespace Catch {
  5523. void writeToDebugConsole( std::string const& text );
  5524. }
  5525. // end catch_debug_console.h
  5526. #ifdef CATCH_PLATFORM_WINDOWS
  5527. namespace Catch {
  5528. void writeToDebugConsole( std::string const& text ) {
  5529. ::OutputDebugStringA( text.c_str() );
  5530. }
  5531. }
  5532. #else
  5533. namespace Catch {
  5534. void writeToDebugConsole( std::string const& text ) {
  5535. // !TBD: Need a version for Mac/ XCode and other IDEs
  5536. Catch::cout() << text;
  5537. }
  5538. }
  5539. #endif // Platform
  5540. // end catch_debug_console.cpp
  5541. // start catch_debugger.cpp
  5542. #ifdef CATCH_PLATFORM_MAC
  5543. # include <assert.h>
  5544. # include <stdbool.h>
  5545. # include <sys/types.h>
  5546. # include <unistd.h>
  5547. # include <sys/sysctl.h>
  5548. # include <cstddef>
  5549. # include <ostream>
  5550. namespace Catch {
  5551. // The following function is taken directly from the following technical note:
  5552. // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  5553. // Returns true if the current process is being debugged (either
  5554. // running under the debugger or has a debugger attached post facto).
  5555. bool isDebuggerActive(){
  5556. int mib[4];
  5557. struct kinfo_proc info;
  5558. std::size_t size;
  5559. // Initialize the flags so that, if sysctl fails for some bizarre
  5560. // reason, we get a predictable result.
  5561. info.kp_proc.p_flag = 0;
  5562. // Initialize mib, which tells sysctl the info we want, in this case
  5563. // we're looking for information about a specific process ID.
  5564. mib[0] = CTL_KERN;
  5565. mib[1] = KERN_PROC;
  5566. mib[2] = KERN_PROC_PID;
  5567. mib[3] = getpid();
  5568. // Call sysctl.
  5569. size = sizeof(info);
  5570. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  5571. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  5572. return false;
  5573. }
  5574. // We're being debugged if the P_TRACED flag is set.
  5575. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  5576. }
  5577. } // namespace Catch
  5578. #elif defined(CATCH_PLATFORM_LINUX)
  5579. #include <fstream>
  5580. #include <string>
  5581. namespace Catch{
  5582. // The standard POSIX way of detecting a debugger is to attempt to
  5583. // ptrace() the process, but this needs to be done from a child and not
  5584. // this process itself to still allow attaching to this process later
  5585. // if wanted, so is rather heavy. Under Linux we have the PID of the
  5586. // "debugger" (which doesn't need to be gdb, of course, it could also
  5587. // be strace, for example) in /proc/$PID/status, so just get it from
  5588. // there instead.
  5589. bool isDebuggerActive(){
  5590. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  5591. // This way our users can properly assert over errno values
  5592. ErrnoGuard guard;
  5593. std::ifstream in("/proc/self/status");
  5594. for( std::string line; std::getline(in, line); ) {
  5595. static const int PREFIX_LEN = 11;
  5596. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  5597. // We're traced if the PID is not 0 and no other PID starts
  5598. // with 0 digit, so it's enough to check for just a single
  5599. // character.
  5600. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  5601. }
  5602. }
  5603. return false;
  5604. }
  5605. } // namespace Catch
  5606. #elif defined(_MSC_VER)
  5607. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5608. namespace Catch {
  5609. bool isDebuggerActive() {
  5610. return IsDebuggerPresent() != 0;
  5611. }
  5612. }
  5613. #elif defined(__MINGW32__)
  5614. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5615. namespace Catch {
  5616. bool isDebuggerActive() {
  5617. return IsDebuggerPresent() != 0;
  5618. }
  5619. }
  5620. #else
  5621. namespace Catch {
  5622. bool isDebuggerActive() { return false; }
  5623. }
  5624. #endif // Platform
  5625. // end catch_debugger.cpp
  5626. // start catch_decomposer.cpp
  5627. namespace Catch {
  5628. ITransientExpression::~ITransientExpression() = default;
  5629. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  5630. if( lhs.size() + rhs.size() < 40 &&
  5631. lhs.find('\n') == std::string::npos &&
  5632. rhs.find('\n') == std::string::npos )
  5633. os << lhs << " " << op << " " << rhs;
  5634. else
  5635. os << lhs << "\n" << op << "\n" << rhs;
  5636. }
  5637. }
  5638. // end catch_decomposer.cpp
  5639. // start catch_errno_guard.cpp
  5640. #include <cerrno>
  5641. namespace Catch {
  5642. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  5643. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  5644. }
  5645. // end catch_errno_guard.cpp
  5646. // start catch_exception_translator_registry.cpp
  5647. // start catch_exception_translator_registry.h
  5648. #include <vector>
  5649. #include <string>
  5650. #include <memory>
  5651. namespace Catch {
  5652. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  5653. public:
  5654. ~ExceptionTranslatorRegistry();
  5655. virtual void registerTranslator( const IExceptionTranslator* translator );
  5656. virtual std::string translateActiveException() const override;
  5657. std::string tryTranslators() const;
  5658. private:
  5659. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  5660. };
  5661. }
  5662. // end catch_exception_translator_registry.h
  5663. #ifdef __OBJC__
  5664. #import "Foundation/Foundation.h"
  5665. #endif
  5666. namespace Catch {
  5667. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  5668. }
  5669. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  5670. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  5671. }
  5672. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  5673. try {
  5674. #ifdef __OBJC__
  5675. // In Objective-C try objective-c exceptions first
  5676. @try {
  5677. return tryTranslators();
  5678. }
  5679. @catch (NSException *exception) {
  5680. return Catch::Detail::stringify( [exception description] );
  5681. }
  5682. #else
  5683. // Compiling a mixed mode project with MSVC means that CLR
  5684. // exceptions will be caught in (...) as well. However, these
  5685. // do not fill-in std::current_exception and thus lead to crash
  5686. // when attempting rethrow.
  5687. // /EHa switch also causes structured exceptions to be caught
  5688. // here, but they fill-in current_exception properly, so
  5689. // at worst the output should be a little weird, instead of
  5690. // causing a crash.
  5691. if (std::current_exception() == nullptr) {
  5692. return "Non C++ exception. Possibly a CLR exception.";
  5693. }
  5694. return tryTranslators();
  5695. #endif
  5696. }
  5697. catch( TestFailureException& ) {
  5698. std::rethrow_exception(std::current_exception());
  5699. }
  5700. catch( std::exception& ex ) {
  5701. return ex.what();
  5702. }
  5703. catch( std::string& msg ) {
  5704. return msg;
  5705. }
  5706. catch( const char* msg ) {
  5707. return msg;
  5708. }
  5709. catch(...) {
  5710. return "Unknown exception";
  5711. }
  5712. }
  5713. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  5714. if( m_translators.empty() )
  5715. std::rethrow_exception(std::current_exception());
  5716. else
  5717. return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() );
  5718. }
  5719. }
  5720. // end catch_exception_translator_registry.cpp
  5721. // start catch_fatal_condition.cpp
  5722. #if defined(__GNUC__)
  5723. # pragma GCC diagnostic push
  5724. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  5725. #endif
  5726. #if (defined(CATCH_PLATFORM_WINDOWS) && defined(CATCH_CONFIG_WINDOWS_SEH)) || defined(CATCH_CONFIG_POSIX_SIGNALS)
  5727. namespace {
  5728. // Report the error condition
  5729. void reportFatal( char const * const message ) {
  5730. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  5731. }
  5732. }
  5733. #endif
  5734. #if defined ( CATCH_PLATFORM_WINDOWS ) /////////////////////////////////////////
  5735. # if !defined ( CATCH_CONFIG_WINDOWS_SEH )
  5736. namespace Catch {
  5737. void FatalConditionHandler::reset() {}
  5738. }
  5739. # else // CATCH_CONFIG_WINDOWS_SEH is defined
  5740. namespace Catch {
  5741. struct SignalDefs { DWORD id; const char* name; };
  5742. // There is no 1-1 mapping between signals and windows exceptions.
  5743. // Windows can easily distinguish between SO and SigSegV,
  5744. // but SigInt, SigTerm, etc are handled differently.
  5745. static SignalDefs signalDefs[] = {
  5746. { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
  5747. { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
  5748. { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
  5749. { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
  5750. };
  5751. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  5752. for (auto const& def : signalDefs) {
  5753. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  5754. reportFatal(def.name);
  5755. }
  5756. }
  5757. // If its not an exception we care about, pass it along.
  5758. // This stops us from eating debugger breaks etc.
  5759. return EXCEPTION_CONTINUE_SEARCH;
  5760. }
  5761. FatalConditionHandler::FatalConditionHandler() {
  5762. isSet = true;
  5763. // 32k seems enough for Catch to handle stack overflow,
  5764. // but the value was found experimentally, so there is no strong guarantee
  5765. guaranteeSize = 32 * 1024;
  5766. exceptionHandlerHandle = nullptr;
  5767. // Register as first handler in current chain
  5768. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  5769. // Pass in guarantee size to be filled
  5770. SetThreadStackGuarantee(&guaranteeSize);
  5771. }
  5772. void FatalConditionHandler::reset() {
  5773. if (isSet) {
  5774. // Unregister handler and restore the old guarantee
  5775. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  5776. SetThreadStackGuarantee(&guaranteeSize);
  5777. exceptionHandlerHandle = nullptr;
  5778. isSet = false;
  5779. }
  5780. }
  5781. FatalConditionHandler::~FatalConditionHandler() {
  5782. reset();
  5783. }
  5784. bool FatalConditionHandler::isSet = false;
  5785. ULONG FatalConditionHandler::guaranteeSize = 0;
  5786. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  5787. } // namespace Catch
  5788. # endif // CATCH_CONFIG_WINDOWS_SEH
  5789. #else // Not Windows - assumed to be POSIX compatible //////////////////////////
  5790. # if !defined(CATCH_CONFIG_POSIX_SIGNALS)
  5791. namespace Catch {
  5792. void FatalConditionHandler::reset() {}
  5793. }
  5794. # else // CATCH_CONFIG_POSIX_SIGNALS is defined
  5795. #include <signal.h>
  5796. namespace Catch {
  5797. struct SignalDefs {
  5798. int id;
  5799. const char* name;
  5800. };
  5801. static SignalDefs signalDefs[] = {
  5802. { SIGINT, "SIGINT - Terminal interrupt signal" },
  5803. { SIGILL, "SIGILL - Illegal instruction signal" },
  5804. { SIGFPE, "SIGFPE - Floating point error signal" },
  5805. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  5806. { SIGTERM, "SIGTERM - Termination request signal" },
  5807. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  5808. };
  5809. void FatalConditionHandler::handleSignal( int sig ) {
  5810. char const * name = "<unknown signal>";
  5811. for (auto const& def : signalDefs) {
  5812. if (sig == def.id) {
  5813. name = def.name;
  5814. break;
  5815. }
  5816. }
  5817. reset();
  5818. reportFatal(name);
  5819. raise( sig );
  5820. }
  5821. FatalConditionHandler::FatalConditionHandler() {
  5822. isSet = true;
  5823. stack_t sigStack;
  5824. sigStack.ss_sp = altStackMem;
  5825. sigStack.ss_size = SIGSTKSZ;
  5826. sigStack.ss_flags = 0;
  5827. sigaltstack(&sigStack, &oldSigStack);
  5828. struct sigaction sa = { };
  5829. sa.sa_handler = handleSignal;
  5830. sa.sa_flags = SA_ONSTACK;
  5831. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  5832. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  5833. }
  5834. }
  5835. FatalConditionHandler::~FatalConditionHandler() {
  5836. reset();
  5837. }
  5838. void FatalConditionHandler::reset() {
  5839. if( isSet ) {
  5840. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  5841. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  5842. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  5843. }
  5844. // Return the old stack
  5845. sigaltstack(&oldSigStack, nullptr);
  5846. isSet = false;
  5847. }
  5848. }
  5849. bool FatalConditionHandler::isSet = false;
  5850. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  5851. stack_t FatalConditionHandler::oldSigStack = {};
  5852. char FatalConditionHandler::altStackMem[SIGSTKSZ] = {};
  5853. } // namespace Catch
  5854. # endif // CATCH_CONFIG_POSIX_SIGNALS
  5855. #endif // not Windows
  5856. #if defined(__GNUC__)
  5857. # pragma GCC diagnostic pop
  5858. #endif
  5859. // end catch_fatal_condition.cpp
  5860. // start catch_interfaces_capture.cpp
  5861. namespace Catch {
  5862. IResultCapture::~IResultCapture() = default;
  5863. }
  5864. // end catch_interfaces_capture.cpp
  5865. // start catch_interfaces_config.cpp
  5866. namespace Catch {
  5867. IConfig::~IConfig() = default;
  5868. }
  5869. // end catch_interfaces_config.cpp
  5870. // start catch_interfaces_exception.cpp
  5871. namespace Catch {
  5872. IExceptionTranslator::~IExceptionTranslator() = default;
  5873. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  5874. }
  5875. // end catch_interfaces_exception.cpp
  5876. // start catch_interfaces_registry_hub.cpp
  5877. namespace Catch {
  5878. IRegistryHub::~IRegistryHub() = default;
  5879. IMutableRegistryHub::~IMutableRegistryHub() = default;
  5880. }
  5881. // end catch_interfaces_registry_hub.cpp
  5882. // start catch_interfaces_reporter.cpp
  5883. // start catch_reporter_multi.h
  5884. namespace Catch {
  5885. class MultipleReporters : public IStreamingReporter {
  5886. using Reporters = std::vector<IStreamingReporterPtr>;
  5887. Reporters m_reporters;
  5888. public:
  5889. void add( IStreamingReporterPtr&& reporter );
  5890. public: // IStreamingReporter
  5891. ReporterPreferences getPreferences() const override;
  5892. void noMatchingTestCases( std::string const& spec ) override;
  5893. static std::set<Verbosity> getSupportedVerbosities();
  5894. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  5895. void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override;
  5896. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  5897. void testGroupStarting( GroupInfo const& groupInfo ) override;
  5898. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  5899. void sectionStarting( SectionInfo const& sectionInfo ) override;
  5900. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  5901. // The return value indicates if the messages buffer should be cleared:
  5902. bool assertionEnded( AssertionStats const& assertionStats ) override;
  5903. void sectionEnded( SectionStats const& sectionStats ) override;
  5904. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  5905. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  5906. void testRunEnded( TestRunStats const& testRunStats ) override;
  5907. void skipTest( TestCaseInfo const& testInfo ) override;
  5908. bool isMulti() const override;
  5909. };
  5910. } // end namespace Catch
  5911. // end catch_reporter_multi.h
  5912. namespace Catch {
  5913. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  5914. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  5915. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  5916. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  5917. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  5918. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  5919. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  5920. GroupInfo::GroupInfo( std::string const& _name,
  5921. std::size_t _groupIndex,
  5922. std::size_t _groupsCount )
  5923. : name( _name ),
  5924. groupIndex( _groupIndex ),
  5925. groupsCounts( _groupsCount )
  5926. {}
  5927. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  5928. std::vector<MessageInfo> const& _infoMessages,
  5929. Totals const& _totals )
  5930. : assertionResult( _assertionResult ),
  5931. infoMessages( _infoMessages ),
  5932. totals( _totals )
  5933. {
  5934. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  5935. if( assertionResult.hasMessage() ) {
  5936. // Copy message into messages list.
  5937. // !TBD This should have been done earlier, somewhere
  5938. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  5939. builder << assertionResult.getMessage();
  5940. builder.m_info.message = builder.m_stream.str();
  5941. infoMessages.push_back( builder.m_info );
  5942. }
  5943. }
  5944. AssertionStats::~AssertionStats() = default;
  5945. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  5946. Counts const& _assertions,
  5947. double _durationInSeconds,
  5948. bool _missingAssertions )
  5949. : sectionInfo( _sectionInfo ),
  5950. assertions( _assertions ),
  5951. durationInSeconds( _durationInSeconds ),
  5952. missingAssertions( _missingAssertions )
  5953. {}
  5954. SectionStats::~SectionStats() = default;
  5955. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  5956. Totals const& _totals,
  5957. std::string const& _stdOut,
  5958. std::string const& _stdErr,
  5959. bool _aborting )
  5960. : testInfo( _testInfo ),
  5961. totals( _totals ),
  5962. stdOut( _stdOut ),
  5963. stdErr( _stdErr ),
  5964. aborting( _aborting )
  5965. {}
  5966. TestCaseStats::~TestCaseStats() = default;
  5967. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  5968. Totals const& _totals,
  5969. bool _aborting )
  5970. : groupInfo( _groupInfo ),
  5971. totals( _totals ),
  5972. aborting( _aborting )
  5973. {}
  5974. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  5975. : groupInfo( _groupInfo ),
  5976. aborting( false )
  5977. {}
  5978. TestGroupStats::~TestGroupStats() = default;
  5979. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  5980. Totals const& _totals,
  5981. bool _aborting )
  5982. : runInfo( _runInfo ),
  5983. totals( _totals ),
  5984. aborting( _aborting )
  5985. {}
  5986. TestRunStats::~TestRunStats() = default;
  5987. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  5988. bool IStreamingReporter::isMulti() const { return false; }
  5989. IReporterFactory::~IReporterFactory() = default;
  5990. IReporterRegistry::~IReporterRegistry() = default;
  5991. void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter ) {
  5992. if( !existingReporter ) {
  5993. existingReporter = std::move( additionalReporter );
  5994. return;
  5995. }
  5996. MultipleReporters* multi = nullptr;
  5997. if( existingReporter->isMulti() ) {
  5998. multi = static_cast<MultipleReporters*>( existingReporter.get() );
  5999. }
  6000. else {
  6001. auto newMulti = std::unique_ptr<MultipleReporters>( new MultipleReporters );
  6002. newMulti->add( std::move( existingReporter ) );
  6003. multi = newMulti.get();
  6004. existingReporter = std::move( newMulti );
  6005. }
  6006. multi->add( std::move( additionalReporter ) );
  6007. }
  6008. } // end namespace Catch
  6009. // end catch_interfaces_reporter.cpp
  6010. // start catch_interfaces_runner.cpp
  6011. namespace Catch {
  6012. IRunner::~IRunner() = default;
  6013. }
  6014. // end catch_interfaces_runner.cpp
  6015. // start catch_interfaces_testcase.cpp
  6016. namespace Catch {
  6017. ITestInvoker::~ITestInvoker() = default;
  6018. ITestCaseRegistry::~ITestCaseRegistry() = default;
  6019. }
  6020. // end catch_interfaces_testcase.cpp
  6021. // start catch_leak_detector.cpp
  6022. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  6023. #include <crtdbg.h>
  6024. namespace Catch {
  6025. LeakDetector::LeakDetector() {
  6026. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  6027. flag |= _CRTDBG_LEAK_CHECK_DF;
  6028. flag |= _CRTDBG_ALLOC_MEM_DF;
  6029. _CrtSetDbgFlag(flag);
  6030. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  6031. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  6032. // Change this to leaking allocation's number to break there
  6033. _CrtSetBreakAlloc(-1);
  6034. }
  6035. }
  6036. #else
  6037. Catch::LeakDetector::LeakDetector() {}
  6038. #endif
  6039. // end catch_leak_detector.cpp
  6040. // start catch_list.cpp
  6041. // start catch_list.h
  6042. #include <set>
  6043. namespace Catch {
  6044. std::size_t listTests( Config const& config );
  6045. std::size_t listTestsNamesOnly( Config const& config );
  6046. struct TagInfo {
  6047. void add( std::string const& spelling );
  6048. std::string all() const;
  6049. std::set<std::string> spellings;
  6050. std::size_t count = 0;
  6051. };
  6052. std::size_t listTags( Config const& config );
  6053. std::size_t listReporters( Config const& /*config*/ );
  6054. Option<std::size_t> list( Config const& config );
  6055. } // end namespace Catch
  6056. // end catch_list.h
  6057. // start catch_text.h
  6058. namespace Catch {
  6059. using namespace clara::TextFlow;
  6060. }
  6061. // end catch_text.h
  6062. #include <limits>
  6063. #include <algorithm>
  6064. #include <iomanip>
  6065. namespace Catch {
  6066. std::size_t listTests( Config const& config ) {
  6067. TestSpec testSpec = config.testSpec();
  6068. if( config.testSpec().hasFilters() )
  6069. Catch::cout() << "Matching test cases:\n";
  6070. else {
  6071. Catch::cout() << "All available test cases:\n";
  6072. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  6073. }
  6074. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6075. for( auto const& testCaseInfo : matchedTestCases ) {
  6076. Colour::Code colour = testCaseInfo.isHidden()
  6077. ? Colour::SecondaryText
  6078. : Colour::None;
  6079. Colour colourGuard( colour );
  6080. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  6081. if( config.verbosity() >= Verbosity::High ) {
  6082. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  6083. std::string description = testCaseInfo.description;
  6084. if( description.empty() )
  6085. description = "(NO DESCRIPTION)";
  6086. Catch::cout() << Column( description ).indent(4) << std::endl;
  6087. }
  6088. if( !testCaseInfo.tags.empty() )
  6089. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  6090. }
  6091. if( !config.testSpec().hasFilters() )
  6092. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  6093. else
  6094. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  6095. return matchedTestCases.size();
  6096. }
  6097. std::size_t listTestsNamesOnly( Config const& config ) {
  6098. TestSpec testSpec = config.testSpec();
  6099. if( !config.testSpec().hasFilters() )
  6100. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  6101. std::size_t matchedTests = 0;
  6102. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6103. for( auto const& testCaseInfo : matchedTestCases ) {
  6104. matchedTests++;
  6105. if( startsWith( testCaseInfo.name, '#' ) )
  6106. Catch::cout() << '"' << testCaseInfo.name << '"';
  6107. else
  6108. Catch::cout() << testCaseInfo.name;
  6109. if ( config.verbosity() >= Verbosity::High )
  6110. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  6111. Catch::cout() << std::endl;
  6112. }
  6113. return matchedTests;
  6114. }
  6115. void TagInfo::add( std::string const& spelling ) {
  6116. ++count;
  6117. spellings.insert( spelling );
  6118. }
  6119. std::string TagInfo::all() const {
  6120. std::string out;
  6121. for( auto const& spelling : spellings )
  6122. out += "[" + spelling + "]";
  6123. return out;
  6124. }
  6125. std::size_t listTags( Config const& config ) {
  6126. TestSpec testSpec = config.testSpec();
  6127. if( config.testSpec().hasFilters() )
  6128. Catch::cout() << "Tags for matching test cases:\n";
  6129. else {
  6130. Catch::cout() << "All available tags:\n";
  6131. testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( "*" ).testSpec();
  6132. }
  6133. std::map<std::string, TagInfo> tagCounts;
  6134. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6135. for( auto const& testCase : matchedTestCases ) {
  6136. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  6137. std::string lcaseTagName = toLower( tagName );
  6138. auto countIt = tagCounts.find( lcaseTagName );
  6139. if( countIt == tagCounts.end() )
  6140. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  6141. countIt->second.add( tagName );
  6142. }
  6143. }
  6144. for( auto const& tagCount : tagCounts ) {
  6145. ReusableStringStream rss;
  6146. rss << " " << std::setw(2) << tagCount.second.count << " ";
  6147. auto str = rss.str();
  6148. auto wrapper = Column( tagCount.second.all() )
  6149. .initialIndent( 0 )
  6150. .indent( str.size() )
  6151. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  6152. Catch::cout() << str << wrapper << '\n';
  6153. }
  6154. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  6155. return tagCounts.size();
  6156. }
  6157. std::size_t listReporters( Config const& /*config*/ ) {
  6158. Catch::cout() << "Available reporters:\n";
  6159. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  6160. std::size_t maxNameLen = 0;
  6161. for( auto const& factoryKvp : factories )
  6162. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  6163. for( auto const& factoryKvp : factories ) {
  6164. Catch::cout()
  6165. << Column( factoryKvp.first + ":" )
  6166. .indent(2)
  6167. .width( 5+maxNameLen )
  6168. + Column( factoryKvp.second->getDescription() )
  6169. .initialIndent(0)
  6170. .indent(2)
  6171. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  6172. << "\n";
  6173. }
  6174. Catch::cout() << std::endl;
  6175. return factories.size();
  6176. }
  6177. Option<std::size_t> list( Config const& config ) {
  6178. Option<std::size_t> listedCount;
  6179. if( config.listTests() )
  6180. listedCount = listedCount.valueOr(0) + listTests( config );
  6181. if( config.listTestNamesOnly() )
  6182. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
  6183. if( config.listTags() )
  6184. listedCount = listedCount.valueOr(0) + listTags( config );
  6185. if( config.listReporters() )
  6186. listedCount = listedCount.valueOr(0) + listReporters( config );
  6187. return listedCount;
  6188. }
  6189. } // end namespace Catch
  6190. // end catch_list.cpp
  6191. // start catch_matchers.cpp
  6192. namespace Catch {
  6193. namespace Matchers {
  6194. namespace Impl {
  6195. std::string MatcherUntypedBase::toString() const {
  6196. if( m_cachedToString.empty() )
  6197. m_cachedToString = describe();
  6198. return m_cachedToString;
  6199. }
  6200. MatcherUntypedBase::~MatcherUntypedBase() = default;
  6201. } // namespace Impl
  6202. } // namespace Matchers
  6203. using namespace Matchers;
  6204. using Matchers::Impl::MatcherBase;
  6205. } // namespace Catch
  6206. // end catch_matchers.cpp
  6207. // start catch_matchers_floating.cpp
  6208. #include <cstdlib>
  6209. #include <cstdint>
  6210. #include <cstring>
  6211. #include <stdexcept>
  6212. namespace Catch {
  6213. namespace Matchers {
  6214. namespace Floating {
  6215. enum class FloatingPointKind : uint8_t {
  6216. Float,
  6217. Double
  6218. };
  6219. }
  6220. }
  6221. }
  6222. namespace {
  6223. template <typename T>
  6224. struct Converter;
  6225. template <>
  6226. struct Converter<float> {
  6227. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  6228. Converter(float f) {
  6229. std::memcpy(&i, &f, sizeof(f));
  6230. }
  6231. int32_t i;
  6232. };
  6233. template <>
  6234. struct Converter<double> {
  6235. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  6236. Converter(double d) {
  6237. std::memcpy(&i, &d, sizeof(d));
  6238. }
  6239. int64_t i;
  6240. };
  6241. template <typename T>
  6242. auto convert(T t) -> Converter<T> {
  6243. return Converter<T>(t);
  6244. }
  6245. template <typename FP>
  6246. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  6247. // Comparison with NaN should always be false.
  6248. // This way we can rule it out before getting into the ugly details
  6249. if (std::isnan(lhs) || std::isnan(rhs)) {
  6250. return false;
  6251. }
  6252. auto lc = convert(lhs);
  6253. auto rc = convert(rhs);
  6254. if ((lc.i < 0) != (rc.i < 0)) {
  6255. // Potentially we can have +0 and -0
  6256. return lhs == rhs;
  6257. }
  6258. auto ulpDiff = std::abs(lc.i - rc.i);
  6259. return ulpDiff <= maxUlpDiff;
  6260. }
  6261. }
  6262. namespace Catch {
  6263. namespace Matchers {
  6264. namespace Floating {
  6265. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  6266. :m_target{ target }, m_margin{ margin } {
  6267. if (m_margin < 0) {
  6268. throw std::domain_error("Allowed margin difference has to be >= 0");
  6269. }
  6270. }
  6271. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6272. // But without the subtraction to allow for INFINITY in comparison
  6273. bool WithinAbsMatcher::match(double const& matchee) const {
  6274. return (matchee + m_margin >= m_target) && (m_target + m_margin >= m_margin);
  6275. }
  6276. std::string WithinAbsMatcher::describe() const {
  6277. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  6278. }
  6279. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  6280. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  6281. if (m_ulps < 0) {
  6282. throw std::domain_error("Allowed ulp difference has to be >= 0");
  6283. }
  6284. }
  6285. bool WithinUlpsMatcher::match(double const& matchee) const {
  6286. switch (m_type) {
  6287. case FloatingPointKind::Float:
  6288. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  6289. case FloatingPointKind::Double:
  6290. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  6291. default:
  6292. throw std::domain_error("Unknown FloatingPointKind value");
  6293. }
  6294. }
  6295. std::string WithinUlpsMatcher::describe() const {
  6296. return "is within " + std::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  6297. }
  6298. }// namespace Floating
  6299. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  6300. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  6301. }
  6302. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  6303. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  6304. }
  6305. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  6306. return Floating::WithinAbsMatcher(target, margin);
  6307. }
  6308. } // namespace Matchers
  6309. } // namespace Catch
  6310. // end catch_matchers_floating.cpp
  6311. // start catch_matchers_string.cpp
  6312. #include <regex>
  6313. namespace Catch {
  6314. namespace Matchers {
  6315. namespace StdString {
  6316. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  6317. : m_caseSensitivity( caseSensitivity ),
  6318. m_str( adjustString( str ) )
  6319. {}
  6320. std::string CasedString::adjustString( std::string const& str ) const {
  6321. return m_caseSensitivity == CaseSensitive::No
  6322. ? toLower( str )
  6323. : str;
  6324. }
  6325. std::string CasedString::caseSensitivitySuffix() const {
  6326. return m_caseSensitivity == CaseSensitive::No
  6327. ? " (case insensitive)"
  6328. : std::string();
  6329. }
  6330. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  6331. : m_comparator( comparator ),
  6332. m_operation( operation ) {
  6333. }
  6334. std::string StringMatcherBase::describe() const {
  6335. std::string description;
  6336. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  6337. m_comparator.caseSensitivitySuffix().size());
  6338. description += m_operation;
  6339. description += ": \"";
  6340. description += m_comparator.m_str;
  6341. description += "\"";
  6342. description += m_comparator.caseSensitivitySuffix();
  6343. return description;
  6344. }
  6345. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  6346. bool EqualsMatcher::match( std::string const& source ) const {
  6347. return m_comparator.adjustString( source ) == m_comparator.m_str;
  6348. }
  6349. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  6350. bool ContainsMatcher::match( std::string const& source ) const {
  6351. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  6352. }
  6353. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  6354. bool StartsWithMatcher::match( std::string const& source ) const {
  6355. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6356. }
  6357. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  6358. bool EndsWithMatcher::match( std::string const& source ) const {
  6359. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6360. }
  6361. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  6362. bool RegexMatcher::match(std::string const& matchee) const {
  6363. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  6364. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  6365. flags |= std::regex::icase;
  6366. }
  6367. auto reg = std::regex(m_regex, flags);
  6368. return std::regex_match(matchee, reg);
  6369. }
  6370. std::string RegexMatcher::describe() const {
  6371. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  6372. }
  6373. } // namespace StdString
  6374. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6375. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  6376. }
  6377. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6378. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  6379. }
  6380. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6381. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  6382. }
  6383. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6384. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  6385. }
  6386. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  6387. return StdString::RegexMatcher(regex, caseSensitivity);
  6388. }
  6389. } // namespace Matchers
  6390. } // namespace Catch
  6391. // end catch_matchers_string.cpp
  6392. // start catch_message.cpp
  6393. // start catch_uncaught_exceptions.h
  6394. namespace Catch {
  6395. bool uncaught_exceptions();
  6396. } // end namespace Catch
  6397. // end catch_uncaught_exceptions.h
  6398. namespace Catch {
  6399. MessageInfo::MessageInfo( std::string const& _macroName,
  6400. SourceLineInfo const& _lineInfo,
  6401. ResultWas::OfType _type )
  6402. : macroName( _macroName ),
  6403. lineInfo( _lineInfo ),
  6404. type( _type ),
  6405. sequence( ++globalCount )
  6406. {}
  6407. bool MessageInfo::operator==( MessageInfo const& other ) const {
  6408. return sequence == other.sequence;
  6409. }
  6410. bool MessageInfo::operator<( MessageInfo const& other ) const {
  6411. return sequence < other.sequence;
  6412. }
  6413. // This may need protecting if threading support is added
  6414. unsigned int MessageInfo::globalCount = 0;
  6415. ////////////////////////////////////////////////////////////////////////////
  6416. Catch::MessageBuilder::MessageBuilder( std::string const& macroName,
  6417. SourceLineInfo const& lineInfo,
  6418. ResultWas::OfType type )
  6419. :m_info(macroName, lineInfo, type) {}
  6420. ////////////////////////////////////////////////////////////////////////////
  6421. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  6422. : m_info( builder.m_info )
  6423. {
  6424. m_info.message = builder.m_stream.str();
  6425. getResultCapture().pushScopedMessage( m_info );
  6426. }
  6427. ScopedMessage::~ScopedMessage() {
  6428. if ( !uncaught_exceptions() ){
  6429. getResultCapture().popScopedMessage(m_info);
  6430. }
  6431. }
  6432. } // end namespace Catch
  6433. // end catch_message.cpp
  6434. // start catch_random_number_generator.cpp
  6435. // start catch_random_number_generator.h
  6436. #include <algorithm>
  6437. namespace Catch {
  6438. struct IConfig;
  6439. void seedRng( IConfig const& config );
  6440. unsigned int rngSeed();
  6441. struct RandomNumberGenerator {
  6442. using result_type = unsigned int;
  6443. static constexpr result_type (min)() { return 0; }
  6444. static constexpr result_type (max)() { return 1000000; }
  6445. result_type operator()( result_type n ) const;
  6446. result_type operator()() const;
  6447. template<typename V>
  6448. static void shuffle( V& vector ) {
  6449. RandomNumberGenerator rng;
  6450. std::shuffle( vector.begin(), vector.end(), rng );
  6451. }
  6452. };
  6453. }
  6454. // end catch_random_number_generator.h
  6455. #include <cstdlib>
  6456. namespace Catch {
  6457. void seedRng( IConfig const& config ) {
  6458. if( config.rngSeed() != 0 )
  6459. std::srand( config.rngSeed() );
  6460. }
  6461. unsigned int rngSeed() {
  6462. return getCurrentContext().getConfig()->rngSeed();
  6463. }
  6464. RandomNumberGenerator::result_type RandomNumberGenerator::operator()( result_type n ) const {
  6465. return std::rand() % n;
  6466. }
  6467. RandomNumberGenerator::result_type RandomNumberGenerator::operator()() const {
  6468. return std::rand() % (max)();
  6469. }
  6470. }
  6471. // end catch_random_number_generator.cpp
  6472. // start catch_registry_hub.cpp
  6473. // start catch_test_case_registry_impl.h
  6474. #include <vector>
  6475. #include <set>
  6476. #include <algorithm>
  6477. #include <ios>
  6478. namespace Catch {
  6479. class TestCase;
  6480. struct IConfig;
  6481. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  6482. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  6483. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  6484. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  6485. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  6486. class TestRegistry : public ITestCaseRegistry {
  6487. public:
  6488. virtual ~TestRegistry() = default;
  6489. virtual void registerTest( TestCase const& testCase );
  6490. std::vector<TestCase> const& getAllTests() const override;
  6491. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  6492. private:
  6493. std::vector<TestCase> m_functions;
  6494. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  6495. mutable std::vector<TestCase> m_sortedFunctions;
  6496. std::size_t m_unnamedCount = 0;
  6497. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  6498. };
  6499. ///////////////////////////////////////////////////////////////////////////
  6500. class TestInvokerAsFunction : public ITestInvoker {
  6501. void(*m_testAsFunction)();
  6502. public:
  6503. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  6504. void invoke() const override;
  6505. };
  6506. std::string extractClassName( std::string const& classOrQualifiedMethodName );
  6507. ///////////////////////////////////////////////////////////////////////////
  6508. } // end namespace Catch
  6509. // end catch_test_case_registry_impl.h
  6510. // start catch_reporter_registry.h
  6511. #include <map>
  6512. namespace Catch {
  6513. class ReporterRegistry : public IReporterRegistry {
  6514. public:
  6515. ~ReporterRegistry() override;
  6516. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  6517. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  6518. void registerListener( IReporterFactoryPtr const& factory );
  6519. FactoryMap const& getFactories() const override;
  6520. Listeners const& getListeners() const override;
  6521. private:
  6522. FactoryMap m_factories;
  6523. Listeners m_listeners;
  6524. };
  6525. }
  6526. // end catch_reporter_registry.h
  6527. // start catch_tag_alias_registry.h
  6528. // start catch_tag_alias.h
  6529. #include <string>
  6530. namespace Catch {
  6531. struct TagAlias {
  6532. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  6533. std::string tag;
  6534. SourceLineInfo lineInfo;
  6535. };
  6536. } // end namespace Catch
  6537. // end catch_tag_alias.h
  6538. #include <map>
  6539. namespace Catch {
  6540. class TagAliasRegistry : public ITagAliasRegistry {
  6541. public:
  6542. ~TagAliasRegistry() override;
  6543. TagAlias const* find( std::string const& alias ) const override;
  6544. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  6545. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  6546. private:
  6547. std::map<std::string, TagAlias> m_registry;
  6548. };
  6549. } // end namespace Catch
  6550. // end catch_tag_alias_registry.h
  6551. // start catch_startup_exception_registry.h
  6552. #include <vector>
  6553. #include <exception>
  6554. namespace Catch {
  6555. class StartupExceptionRegistry {
  6556. public:
  6557. void add(std::exception_ptr const& exception) noexcept;
  6558. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  6559. private:
  6560. std::vector<std::exception_ptr> m_exceptions;
  6561. };
  6562. } // end namespace Catch
  6563. // end catch_startup_exception_registry.h
  6564. namespace Catch {
  6565. namespace {
  6566. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  6567. private NonCopyable {
  6568. public: // IRegistryHub
  6569. RegistryHub() = default;
  6570. IReporterRegistry const& getReporterRegistry() const override {
  6571. return m_reporterRegistry;
  6572. }
  6573. ITestCaseRegistry const& getTestCaseRegistry() const override {
  6574. return m_testCaseRegistry;
  6575. }
  6576. IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() override {
  6577. return m_exceptionTranslatorRegistry;
  6578. }
  6579. ITagAliasRegistry const& getTagAliasRegistry() const override {
  6580. return m_tagAliasRegistry;
  6581. }
  6582. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  6583. return m_exceptionRegistry;
  6584. }
  6585. public: // IMutableRegistryHub
  6586. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  6587. m_reporterRegistry.registerReporter( name, factory );
  6588. }
  6589. void registerListener( IReporterFactoryPtr const& factory ) override {
  6590. m_reporterRegistry.registerListener( factory );
  6591. }
  6592. void registerTest( TestCase const& testInfo ) override {
  6593. m_testCaseRegistry.registerTest( testInfo );
  6594. }
  6595. void registerTranslator( const IExceptionTranslator* translator ) override {
  6596. m_exceptionTranslatorRegistry.registerTranslator( translator );
  6597. }
  6598. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  6599. m_tagAliasRegistry.add( alias, tag, lineInfo );
  6600. }
  6601. void registerStartupException() noexcept override {
  6602. m_exceptionRegistry.add(std::current_exception());
  6603. }
  6604. private:
  6605. TestRegistry m_testCaseRegistry;
  6606. ReporterRegistry m_reporterRegistry;
  6607. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  6608. TagAliasRegistry m_tagAliasRegistry;
  6609. StartupExceptionRegistry m_exceptionRegistry;
  6610. };
  6611. // Single, global, instance
  6612. RegistryHub*& getTheRegistryHub() {
  6613. static RegistryHub* theRegistryHub = nullptr;
  6614. if( !theRegistryHub )
  6615. theRegistryHub = new RegistryHub();
  6616. return theRegistryHub;
  6617. }
  6618. }
  6619. IRegistryHub& getRegistryHub() {
  6620. return *getTheRegistryHub();
  6621. }
  6622. IMutableRegistryHub& getMutableRegistryHub() {
  6623. return *getTheRegistryHub();
  6624. }
  6625. void cleanUp() {
  6626. delete getTheRegistryHub();
  6627. getTheRegistryHub() = nullptr;
  6628. cleanUpContext();
  6629. ReusableStringStream::cleanup();
  6630. }
  6631. std::string translateActiveException() {
  6632. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  6633. }
  6634. } // end namespace Catch
  6635. // end catch_registry_hub.cpp
  6636. // start catch_reporter_registry.cpp
  6637. namespace Catch {
  6638. ReporterRegistry::~ReporterRegistry() = default;
  6639. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  6640. auto it = m_factories.find( name );
  6641. if( it == m_factories.end() )
  6642. return nullptr;
  6643. return it->second->create( ReporterConfig( config ) );
  6644. }
  6645. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  6646. m_factories.emplace(name, factory);
  6647. }
  6648. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  6649. m_listeners.push_back( factory );
  6650. }
  6651. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  6652. return m_factories;
  6653. }
  6654. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  6655. return m_listeners;
  6656. }
  6657. }
  6658. // end catch_reporter_registry.cpp
  6659. // start catch_result_type.cpp
  6660. namespace Catch {
  6661. bool isOk( ResultWas::OfType resultType ) {
  6662. return ( resultType & ResultWas::FailureBit ) == 0;
  6663. }
  6664. bool isJustInfo( int flags ) {
  6665. return flags == ResultWas::Info;
  6666. }
  6667. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  6668. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  6669. }
  6670. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  6671. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  6672. } // end namespace Catch
  6673. // end catch_result_type.cpp
  6674. // start catch_run_context.cpp
  6675. #include <cassert>
  6676. #include <algorithm>
  6677. #include <sstream>
  6678. namespace Catch {
  6679. class RedirectedStream {
  6680. std::ostream& m_originalStream;
  6681. std::ostream& m_redirectionStream;
  6682. std::streambuf* m_prevBuf;
  6683. public:
  6684. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  6685. : m_originalStream( originalStream ),
  6686. m_redirectionStream( redirectionStream ),
  6687. m_prevBuf( m_originalStream.rdbuf() )
  6688. {
  6689. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  6690. }
  6691. ~RedirectedStream() {
  6692. m_originalStream.rdbuf( m_prevBuf );
  6693. }
  6694. };
  6695. class RedirectedStdOut {
  6696. ReusableStringStream m_rss;
  6697. RedirectedStream m_cout;
  6698. public:
  6699. RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  6700. auto str() const -> std::string { return m_rss.str(); }
  6701. };
  6702. // StdErr has two constituent streams in C++, std::cerr and std::clog
  6703. // This means that we need to redirect 2 streams into 1 to keep proper
  6704. // order of writes
  6705. class RedirectedStdErr {
  6706. ReusableStringStream m_rss;
  6707. RedirectedStream m_cerr;
  6708. RedirectedStream m_clog;
  6709. public:
  6710. RedirectedStdErr()
  6711. : m_cerr( Catch::cerr(), m_rss.get() ),
  6712. m_clog( Catch::clog(), m_rss.get() )
  6713. {}
  6714. auto str() const -> std::string { return m_rss.str(); }
  6715. };
  6716. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  6717. : m_runInfo(_config->name()),
  6718. m_context(getCurrentMutableContext()),
  6719. m_config(_config),
  6720. m_reporter(std::move(reporter)),
  6721. m_lastAssertionInfo{ "", SourceLineInfo("",0), "", ResultDisposition::Normal },
  6722. m_includeSuccessfulResults( m_config->includeSuccessfulResults() )
  6723. {
  6724. m_context.setRunner(this);
  6725. m_context.setConfig(m_config);
  6726. m_context.setResultCapture(this);
  6727. m_reporter->testRunStarting(m_runInfo);
  6728. }
  6729. RunContext::~RunContext() {
  6730. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  6731. }
  6732. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  6733. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  6734. }
  6735. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  6736. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  6737. }
  6738. Totals RunContext::runTest(TestCase const& testCase) {
  6739. Totals prevTotals = m_totals;
  6740. std::string redirectedCout;
  6741. std::string redirectedCerr;
  6742. TestCaseInfo testInfo = testCase.getTestCaseInfo();
  6743. m_reporter->testCaseStarting(testInfo);
  6744. m_activeTestCase = &testCase;
  6745. ITracker& rootTracker = m_trackerContext.startRun();
  6746. assert(rootTracker.isSectionTracker());
  6747. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  6748. do {
  6749. m_trackerContext.startCycle();
  6750. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  6751. runCurrentTest(redirectedCout, redirectedCerr);
  6752. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  6753. Totals deltaTotals = m_totals.delta(prevTotals);
  6754. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  6755. deltaTotals.assertions.failed++;
  6756. deltaTotals.testCases.passed--;
  6757. deltaTotals.testCases.failed++;
  6758. }
  6759. m_totals.testCases += deltaTotals.testCases;
  6760. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  6761. deltaTotals,
  6762. redirectedCout,
  6763. redirectedCerr,
  6764. aborting()));
  6765. m_activeTestCase = nullptr;
  6766. m_testCaseTracker = nullptr;
  6767. return deltaTotals;
  6768. }
  6769. IConfigPtr RunContext::config() const {
  6770. return m_config;
  6771. }
  6772. IStreamingReporter& RunContext::reporter() const {
  6773. return *m_reporter;
  6774. }
  6775. void RunContext::assertionEnded(AssertionResult const & result) {
  6776. if (result.getResultType() == ResultWas::Ok) {
  6777. m_totals.assertions.passed++;
  6778. m_lastAssertionPassed = true;
  6779. } else if (!result.isOk()) {
  6780. m_lastAssertionPassed = false;
  6781. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  6782. m_totals.assertions.failedButOk++;
  6783. else
  6784. m_totals.assertions.failed++;
  6785. }
  6786. else {
  6787. m_lastAssertionPassed = true;
  6788. }
  6789. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  6790. // and should be let to clear themselves out.
  6791. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  6792. // Reset working state
  6793. resetAssertionInfo();
  6794. m_lastResult = result;
  6795. }
  6796. void RunContext::resetAssertionInfo() {
  6797. m_lastAssertionInfo.macroName = StringRef();
  6798. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  6799. }
  6800. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  6801. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  6802. if (!sectionTracker.isOpen())
  6803. return false;
  6804. m_activeSections.push_back(&sectionTracker);
  6805. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  6806. m_reporter->sectionStarting(sectionInfo);
  6807. assertions = m_totals.assertions;
  6808. return true;
  6809. }
  6810. bool RunContext::testForMissingAssertions(Counts& assertions) {
  6811. if (assertions.total() != 0)
  6812. return false;
  6813. if (!m_config->warnAboutMissingAssertions())
  6814. return false;
  6815. if (m_trackerContext.currentTracker().hasChildren())
  6816. return false;
  6817. m_totals.assertions.failed++;
  6818. assertions.failed++;
  6819. return true;
  6820. }
  6821. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  6822. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  6823. bool missingAssertions = testForMissingAssertions(assertions);
  6824. if (!m_activeSections.empty()) {
  6825. m_activeSections.back()->close();
  6826. m_activeSections.pop_back();
  6827. }
  6828. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  6829. m_messages.clear();
  6830. }
  6831. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  6832. if (m_unfinishedSections.empty())
  6833. m_activeSections.back()->fail();
  6834. else
  6835. m_activeSections.back()->close();
  6836. m_activeSections.pop_back();
  6837. m_unfinishedSections.push_back(endInfo);
  6838. }
  6839. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  6840. m_reporter->benchmarkStarting( info );
  6841. }
  6842. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  6843. m_reporter->benchmarkEnded( stats );
  6844. }
  6845. void RunContext::pushScopedMessage(MessageInfo const & message) {
  6846. m_messages.push_back(message);
  6847. }
  6848. void RunContext::popScopedMessage(MessageInfo const & message) {
  6849. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  6850. }
  6851. std::string RunContext::getCurrentTestName() const {
  6852. return m_activeTestCase
  6853. ? m_activeTestCase->getTestCaseInfo().name
  6854. : std::string();
  6855. }
  6856. const AssertionResult * RunContext::getLastResult() const {
  6857. return &(*m_lastResult);
  6858. }
  6859. void RunContext::exceptionEarlyReported() {
  6860. m_shouldReportUnexpected = false;
  6861. }
  6862. void RunContext::handleFatalErrorCondition( StringRef message ) {
  6863. // First notify reporter that bad things happened
  6864. m_reporter->fatalErrorEncountered(message);
  6865. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  6866. // Instead, fake a result data.
  6867. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  6868. tempResult.message = message;
  6869. AssertionResult result(m_lastAssertionInfo, tempResult);
  6870. assertionEnded(result);
  6871. handleUnfinishedSections();
  6872. // Recreate section for test case (as we will lose the one that was in scope)
  6873. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  6874. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  6875. Counts assertions;
  6876. assertions.failed = 1;
  6877. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  6878. m_reporter->sectionEnded(testCaseSectionStats);
  6879. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  6880. Totals deltaTotals;
  6881. deltaTotals.testCases.failed = 1;
  6882. deltaTotals.assertions.failed = 1;
  6883. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  6884. deltaTotals,
  6885. std::string(),
  6886. std::string(),
  6887. false));
  6888. m_totals.testCases.failed++;
  6889. testGroupEnded(std::string(), m_totals, 1, 1);
  6890. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  6891. }
  6892. bool RunContext::lastAssertionPassed() {
  6893. return m_lastAssertionPassed;
  6894. }
  6895. void RunContext::assertionPassed() {
  6896. m_lastAssertionPassed = true;
  6897. ++m_totals.assertions.passed;
  6898. resetAssertionInfo();
  6899. }
  6900. bool RunContext::aborting() const {
  6901. return m_totals.assertions.failed == static_cast<std::size_t>(m_config->abortAfter());
  6902. }
  6903. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  6904. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  6905. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  6906. m_reporter->sectionStarting(testCaseSection);
  6907. Counts prevAssertions = m_totals.assertions;
  6908. double duration = 0;
  6909. m_shouldReportUnexpected = true;
  6910. m_lastAssertionInfo = { "TEST_CASE", testCaseInfo.lineInfo, "", ResultDisposition::Normal };
  6911. seedRng(*m_config);
  6912. Timer timer;
  6913. try {
  6914. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  6915. RedirectedStdOut redirectedStdOut;
  6916. RedirectedStdErr redirectedStdErr;
  6917. timer.start();
  6918. invokeActiveTestCase();
  6919. redirectedCout += redirectedStdOut.str();
  6920. redirectedCerr += redirectedStdErr.str();
  6921. } else {
  6922. timer.start();
  6923. invokeActiveTestCase();
  6924. }
  6925. duration = timer.getElapsedSeconds();
  6926. } catch (TestFailureException&) {
  6927. // This just means the test was aborted due to failure
  6928. } catch (...) {
  6929. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  6930. // are reported without translation at the point of origin.
  6931. if( m_shouldReportUnexpected ) {
  6932. AssertionReaction dummyReaction;
  6933. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  6934. }
  6935. }
  6936. Counts assertions = m_totals.assertions - prevAssertions;
  6937. bool missingAssertions = testForMissingAssertions(assertions);
  6938. m_testCaseTracker->close();
  6939. handleUnfinishedSections();
  6940. m_messages.clear();
  6941. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  6942. m_reporter->sectionEnded(testCaseSectionStats);
  6943. }
  6944. void RunContext::invokeActiveTestCase() {
  6945. FatalConditionHandler fatalConditionHandler; // Handle signals
  6946. m_activeTestCase->invoke();
  6947. fatalConditionHandler.reset();
  6948. }
  6949. void RunContext::handleUnfinishedSections() {
  6950. // If sections ended prematurely due to an exception we stored their
  6951. // infos here so we can tear them down outside the unwind process.
  6952. for (auto it = m_unfinishedSections.rbegin(),
  6953. itEnd = m_unfinishedSections.rend();
  6954. it != itEnd;
  6955. ++it)
  6956. sectionEnded(*it);
  6957. m_unfinishedSections.clear();
  6958. }
  6959. void RunContext::handleExpr(
  6960. AssertionInfo const& info,
  6961. ITransientExpression const& expr,
  6962. AssertionReaction& reaction
  6963. ) {
  6964. m_reporter->assertionStarting( info );
  6965. bool negated = isFalseTest( info.resultDisposition );
  6966. bool result = expr.getResult() != negated;
  6967. if( result ) {
  6968. if (!m_includeSuccessfulResults) {
  6969. assertionPassed();
  6970. }
  6971. else {
  6972. reportExpr(info, ResultWas::Ok, &expr, negated);
  6973. }
  6974. }
  6975. else {
  6976. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  6977. populateReaction( reaction );
  6978. }
  6979. }
  6980. void RunContext::reportExpr(
  6981. AssertionInfo const &info,
  6982. ResultWas::OfType resultType,
  6983. ITransientExpression const *expr,
  6984. bool negated ) {
  6985. m_lastAssertionInfo = info;
  6986. AssertionResultData data( resultType, LazyExpression( negated ) );
  6987. AssertionResult assertionResult{ info, data };
  6988. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  6989. assertionEnded( assertionResult );
  6990. }
  6991. void RunContext::handleMessage(
  6992. AssertionInfo const& info,
  6993. ResultWas::OfType resultType,
  6994. StringRef const& message,
  6995. AssertionReaction& reaction
  6996. ) {
  6997. m_reporter->assertionStarting( info );
  6998. m_lastAssertionInfo = info;
  6999. AssertionResultData data( resultType, LazyExpression( false ) );
  7000. data.message = message;
  7001. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  7002. assertionEnded( assertionResult );
  7003. if( !assertionResult.isOk() )
  7004. populateReaction( reaction );
  7005. }
  7006. void RunContext::handleUnexpectedExceptionNotThrown(
  7007. AssertionInfo const& info,
  7008. AssertionReaction& reaction
  7009. ) {
  7010. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  7011. }
  7012. void RunContext::handleUnexpectedInflightException(
  7013. AssertionInfo const& info,
  7014. std::string const& message,
  7015. AssertionReaction& reaction
  7016. ) {
  7017. m_lastAssertionInfo = info;
  7018. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  7019. data.message = message;
  7020. AssertionResult assertionResult{ info, data };
  7021. assertionEnded( assertionResult );
  7022. populateReaction( reaction );
  7023. }
  7024. void RunContext::populateReaction( AssertionReaction& reaction ) {
  7025. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  7026. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  7027. }
  7028. void RunContext::handleIncomplete(
  7029. AssertionInfo const& info
  7030. ) {
  7031. m_lastAssertionInfo = info;
  7032. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  7033. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  7034. AssertionResult assertionResult{ info, data };
  7035. assertionEnded( assertionResult );
  7036. }
  7037. void RunContext::handleNonExpr(
  7038. AssertionInfo const &info,
  7039. ResultWas::OfType resultType,
  7040. AssertionReaction &reaction
  7041. ) {
  7042. m_lastAssertionInfo = info;
  7043. AssertionResultData data( resultType, LazyExpression( false ) );
  7044. AssertionResult assertionResult{ info, data };
  7045. assertionEnded( assertionResult );
  7046. if( !assertionResult.isOk() )
  7047. populateReaction( reaction );
  7048. }
  7049. IResultCapture& getResultCapture() {
  7050. if (auto* capture = getCurrentContext().getResultCapture())
  7051. return *capture;
  7052. else
  7053. CATCH_INTERNAL_ERROR("No result capture instance");
  7054. }
  7055. }
  7056. // end catch_run_context.cpp
  7057. // start catch_section.cpp
  7058. namespace Catch {
  7059. Section::Section( SectionInfo const& info )
  7060. : m_info( info ),
  7061. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  7062. {
  7063. m_timer.start();
  7064. }
  7065. Section::~Section() {
  7066. if( m_sectionIncluded ) {
  7067. SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() );
  7068. if( uncaught_exceptions() )
  7069. getResultCapture().sectionEndedEarly( endInfo );
  7070. else
  7071. getResultCapture().sectionEnded( endInfo );
  7072. }
  7073. }
  7074. // This indicates whether the section should be executed or not
  7075. Section::operator bool() const {
  7076. return m_sectionIncluded;
  7077. }
  7078. } // end namespace Catch
  7079. // end catch_section.cpp
  7080. // start catch_section_info.cpp
  7081. namespace Catch {
  7082. SectionInfo::SectionInfo
  7083. ( SourceLineInfo const& _lineInfo,
  7084. std::string const& _name,
  7085. std::string const& _description )
  7086. : name( _name ),
  7087. description( _description ),
  7088. lineInfo( _lineInfo )
  7089. {}
  7090. SectionEndInfo::SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds )
  7091. : sectionInfo( _sectionInfo ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds )
  7092. {}
  7093. } // end namespace Catch
  7094. // end catch_section_info.cpp
  7095. // start catch_session.cpp
  7096. // start catch_session.h
  7097. #include <memory>
  7098. namespace Catch {
  7099. class Session : NonCopyable {
  7100. public:
  7101. Session();
  7102. ~Session() override;
  7103. void showHelp() const;
  7104. void libIdentify();
  7105. int applyCommandLine( int argc, char* argv[] );
  7106. void useConfigData( ConfigData const& configData );
  7107. int run( int argc, char* argv[] );
  7108. #if defined(WIN32) && defined(UNICODE)
  7109. int run( int argc, wchar_t* const argv[] );
  7110. #endif
  7111. int run();
  7112. clara::Parser const& cli() const;
  7113. void cli( clara::Parser const& newParser );
  7114. ConfigData& configData();
  7115. Config& config();
  7116. private:
  7117. int runInternal();
  7118. clara::Parser m_cli;
  7119. ConfigData m_configData;
  7120. std::shared_ptr<Config> m_config;
  7121. bool m_startupExceptions = false;
  7122. };
  7123. } // end namespace Catch
  7124. // end catch_session.h
  7125. // start catch_version.h
  7126. #include <iosfwd>
  7127. namespace Catch {
  7128. // Versioning information
  7129. struct Version {
  7130. Version( Version const& ) = delete;
  7131. Version& operator=( Version const& ) = delete;
  7132. Version( unsigned int _majorVersion,
  7133. unsigned int _minorVersion,
  7134. unsigned int _patchNumber,
  7135. char const * const _branchName,
  7136. unsigned int _buildNumber );
  7137. unsigned int const majorVersion;
  7138. unsigned int const minorVersion;
  7139. unsigned int const patchNumber;
  7140. // buildNumber is only used if branchName is not null
  7141. char const * const branchName;
  7142. unsigned int const buildNumber;
  7143. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  7144. };
  7145. Version const& libraryVersion();
  7146. }
  7147. // end catch_version.h
  7148. #include <cstdlib>
  7149. #include <iomanip>
  7150. namespace Catch {
  7151. namespace {
  7152. const int MaxExitCode = 255;
  7153. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  7154. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  7155. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  7156. return reporter;
  7157. }
  7158. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  7159. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  7160. #endif
  7161. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  7162. auto const& reporterNames = config->getReporterNames();
  7163. if (reporterNames.empty())
  7164. return createReporter(CATCH_CONFIG_DEFAULT_REPORTER, config);
  7165. IStreamingReporterPtr reporter;
  7166. for (auto const& name : reporterNames)
  7167. addReporter(reporter, createReporter(name, config));
  7168. return reporter;
  7169. }
  7170. #undef CATCH_CONFIG_DEFAULT_REPORTER
  7171. void addListeners(IStreamingReporterPtr& reporters, IConfigPtr const& config) {
  7172. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  7173. for (auto const& listener : listeners)
  7174. addReporter(reporters, listener->create(Catch::ReporterConfig(config)));
  7175. }
  7176. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  7177. IStreamingReporterPtr reporter = makeReporter(config);
  7178. addListeners(reporter, config);
  7179. RunContext context(config, std::move(reporter));
  7180. Totals totals;
  7181. context.testGroupStarting(config->name(), 1, 1);
  7182. TestSpec testSpec = config->testSpec();
  7183. if (!testSpec.hasFilters())
  7184. testSpec = TestSpecParser(ITagAliasRegistry::get()).parse("~[.]").testSpec(); // All not hidden tests
  7185. auto const& allTestCases = getAllTestCasesSorted(*config);
  7186. for (auto const& testCase : allTestCases) {
  7187. if (!context.aborting() && matchTest(testCase, testSpec, *config))
  7188. totals += context.runTest(testCase);
  7189. else
  7190. context.reporter().skipTest(testCase);
  7191. }
  7192. context.testGroupEnded(config->name(), totals, 1, 1);
  7193. return totals;
  7194. }
  7195. void applyFilenamesAsTags(Catch::IConfig const& config) {
  7196. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  7197. for (auto& testCase : tests) {
  7198. auto tags = testCase.tags;
  7199. std::string filename = testCase.lineInfo.file;
  7200. auto lastSlash = filename.find_last_of("\\/");
  7201. if (lastSlash != std::string::npos) {
  7202. filename.erase(0, lastSlash);
  7203. filename[0] = '#';
  7204. }
  7205. auto lastDot = filename.find_last_of('.');
  7206. if (lastDot != std::string::npos) {
  7207. filename.erase(lastDot);
  7208. }
  7209. tags.push_back(std::move(filename));
  7210. setTags(testCase, tags);
  7211. }
  7212. }
  7213. } // anon namespace
  7214. Session::Session() {
  7215. static bool alreadyInstantiated = false;
  7216. if( alreadyInstantiated ) {
  7217. try { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  7218. catch(...) { getMutableRegistryHub().registerStartupException(); }
  7219. }
  7220. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  7221. if ( !exceptions.empty() ) {
  7222. m_startupExceptions = true;
  7223. Colour colourGuard( Colour::Red );
  7224. Catch::cerr() << "Errors occured during startup!" << '\n';
  7225. // iterate over all exceptions and notify user
  7226. for ( const auto& ex_ptr : exceptions ) {
  7227. try {
  7228. std::rethrow_exception(ex_ptr);
  7229. } catch ( std::exception const& ex ) {
  7230. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  7231. }
  7232. }
  7233. }
  7234. alreadyInstantiated = true;
  7235. m_cli = makeCommandLineParser( m_configData );
  7236. }
  7237. Session::~Session() {
  7238. Catch::cleanUp();
  7239. }
  7240. void Session::showHelp() const {
  7241. Catch::cout()
  7242. << "\nCatch v" << libraryVersion() << "\n"
  7243. << m_cli << std::endl
  7244. << "For more detailed usage please see the project docs\n" << std::endl;
  7245. }
  7246. void Session::libIdentify() {
  7247. Catch::cout()
  7248. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  7249. << std::left << std::setw(16) << "category: " << "testframework\n"
  7250. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  7251. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  7252. }
  7253. int Session::applyCommandLine( int argc, char* argv[] ) {
  7254. if( m_startupExceptions )
  7255. return 1;
  7256. auto result = m_cli.parse( clara::Args( argc, argv ) );
  7257. if( !result ) {
  7258. Catch::cerr()
  7259. << Colour( Colour::Red )
  7260. << "\nError(s) in input:\n"
  7261. << Column( result.errorMessage() ).indent( 2 )
  7262. << "\n\n";
  7263. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  7264. return MaxExitCode;
  7265. }
  7266. if( m_configData.showHelp )
  7267. showHelp();
  7268. if( m_configData.libIdentify )
  7269. libIdentify();
  7270. m_config.reset();
  7271. return 0;
  7272. }
  7273. void Session::useConfigData( ConfigData const& configData ) {
  7274. m_configData = configData;
  7275. m_config.reset();
  7276. }
  7277. int Session::run( int argc, char* argv[] ) {
  7278. if( m_startupExceptions )
  7279. return 1;
  7280. int returnCode = applyCommandLine( argc, argv );
  7281. if( returnCode == 0 )
  7282. returnCode = run();
  7283. return returnCode;
  7284. }
  7285. #if defined(WIN32) && defined(UNICODE)
  7286. int Session::run( int argc, wchar_t* const argv[] ) {
  7287. char **utf8Argv = new char *[ argc ];
  7288. for ( int i = 0; i < argc; ++i ) {
  7289. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  7290. utf8Argv[ i ] = new char[ bufSize ];
  7291. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  7292. }
  7293. int returnCode = run( argc, utf8Argv );
  7294. for ( int i = 0; i < argc; ++i )
  7295. delete [] utf8Argv[ i ];
  7296. delete [] utf8Argv;
  7297. return returnCode;
  7298. }
  7299. #endif
  7300. int Session::run() {
  7301. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  7302. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  7303. static_cast<void>(std::getchar());
  7304. }
  7305. int exitCode = runInternal();
  7306. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  7307. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  7308. static_cast<void>(std::getchar());
  7309. }
  7310. return exitCode;
  7311. }
  7312. clara::Parser const& Session::cli() const {
  7313. return m_cli;
  7314. }
  7315. void Session::cli( clara::Parser const& newParser ) {
  7316. m_cli = newParser;
  7317. }
  7318. ConfigData& Session::configData() {
  7319. return m_configData;
  7320. }
  7321. Config& Session::config() {
  7322. if( !m_config )
  7323. m_config = std::make_shared<Config>( m_configData );
  7324. return *m_config;
  7325. }
  7326. int Session::runInternal() {
  7327. if( m_startupExceptions )
  7328. return 1;
  7329. if( m_configData.showHelp || m_configData.libIdentify )
  7330. return 0;
  7331. try
  7332. {
  7333. config(); // Force config to be constructed
  7334. seedRng( *m_config );
  7335. if( m_configData.filenamesAsTags )
  7336. applyFilenamesAsTags( *m_config );
  7337. // Handle list request
  7338. if( Option<std::size_t> listed = list( config() ) )
  7339. return static_cast<int>( *listed );
  7340. // Note that on unices only the lower 8 bits are usually used, clamping
  7341. // the return value to 255 prevents false negative when some multiple
  7342. // of 256 tests has failed
  7343. return (std::min)( MaxExitCode, static_cast<int>( runTests( m_config ).assertions.failed ) );
  7344. }
  7345. catch( std::exception& ex ) {
  7346. Catch::cerr() << ex.what() << std::endl;
  7347. return MaxExitCode;
  7348. }
  7349. }
  7350. } // end namespace Catch
  7351. // end catch_session.cpp
  7352. // start catch_startup_exception_registry.cpp
  7353. namespace Catch {
  7354. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  7355. try {
  7356. m_exceptions.push_back(exception);
  7357. }
  7358. catch(...) {
  7359. // If we run out of memory during start-up there's really not a lot more we can do about it
  7360. std::terminate();
  7361. }
  7362. }
  7363. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  7364. return m_exceptions;
  7365. }
  7366. } // end namespace Catch
  7367. // end catch_startup_exception_registry.cpp
  7368. // start catch_stream.cpp
  7369. #include <cstdio>
  7370. #include <iostream>
  7371. #include <fstream>
  7372. #include <sstream>
  7373. #include <vector>
  7374. #include <memory>
  7375. #if defined(__clang__)
  7376. # pragma clang diagnostic push
  7377. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7378. #endif
  7379. namespace Catch {
  7380. Catch::IStream::~IStream() = default;
  7381. namespace detail { namespace {
  7382. template<typename WriterF, std::size_t bufferSize=256>
  7383. class StreamBufImpl : public std::streambuf {
  7384. char data[bufferSize];
  7385. WriterF m_writer;
  7386. public:
  7387. StreamBufImpl() {
  7388. setp( data, data + sizeof(data) );
  7389. }
  7390. ~StreamBufImpl() noexcept {
  7391. StreamBufImpl::sync();
  7392. }
  7393. private:
  7394. int overflow( int c ) override {
  7395. sync();
  7396. if( c != EOF ) {
  7397. if( pbase() == epptr() )
  7398. m_writer( std::string( 1, static_cast<char>( c ) ) );
  7399. else
  7400. sputc( static_cast<char>( c ) );
  7401. }
  7402. return 0;
  7403. }
  7404. int sync() override {
  7405. if( pbase() != pptr() ) {
  7406. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  7407. setp( pbase(), epptr() );
  7408. }
  7409. return 0;
  7410. }
  7411. };
  7412. ///////////////////////////////////////////////////////////////////////////
  7413. struct OutputDebugWriter {
  7414. void operator()( std::string const&str ) {
  7415. writeToDebugConsole( str );
  7416. }
  7417. };
  7418. ///////////////////////////////////////////////////////////////////////////
  7419. class FileStream : public IStream {
  7420. mutable std::ofstream m_ofs;
  7421. public:
  7422. FileStream( StringRef filename ) {
  7423. m_ofs.open( filename.c_str() );
  7424. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  7425. }
  7426. ~FileStream() override = default;
  7427. public: // IStream
  7428. std::ostream& stream() const override {
  7429. return m_ofs;
  7430. }
  7431. };
  7432. ///////////////////////////////////////////////////////////////////////////
  7433. class CoutStream : public IStream {
  7434. mutable std::ostream m_os;
  7435. public:
  7436. // Store the streambuf from cout up-front because
  7437. // cout may get redirected when running tests
  7438. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  7439. ~CoutStream() override = default;
  7440. public: // IStream
  7441. std::ostream& stream() const override { return m_os; }
  7442. };
  7443. ///////////////////////////////////////////////////////////////////////////
  7444. class DebugOutStream : public IStream {
  7445. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  7446. mutable std::ostream m_os;
  7447. public:
  7448. DebugOutStream()
  7449. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  7450. m_os( m_streamBuf.get() )
  7451. {}
  7452. ~DebugOutStream() override = default;
  7453. public: // IStream
  7454. std::ostream& stream() const override { return m_os; }
  7455. };
  7456. }} // namespace anon::detail
  7457. ///////////////////////////////////////////////////////////////////////////
  7458. auto makeStream( StringRef const &filename ) -> IStream const* {
  7459. if( filename.empty() )
  7460. return new detail::CoutStream();
  7461. else if( filename[0] == '%' ) {
  7462. if( filename == "%debug" )
  7463. return new detail::DebugOutStream();
  7464. else
  7465. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  7466. }
  7467. else
  7468. return new detail::FileStream( filename );
  7469. }
  7470. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  7471. struct StringStreams {
  7472. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  7473. std::vector<std::size_t> m_unused;
  7474. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  7475. static StringStreams* s_instance;
  7476. auto add() -> std::size_t {
  7477. if( m_unused.empty() ) {
  7478. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  7479. return m_streams.size()-1;
  7480. }
  7481. else {
  7482. auto index = m_unused.back();
  7483. m_unused.pop_back();
  7484. return index;
  7485. }
  7486. }
  7487. void release( std::size_t index ) {
  7488. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  7489. m_unused.push_back(index);
  7490. }
  7491. // !TBD: put in TLS
  7492. static auto instance() -> StringStreams& {
  7493. if( !s_instance )
  7494. s_instance = new StringStreams();
  7495. return *s_instance;
  7496. }
  7497. static void cleanup() {
  7498. delete s_instance;
  7499. s_instance = nullptr;
  7500. }
  7501. };
  7502. StringStreams* StringStreams::s_instance = nullptr;
  7503. void ReusableStringStream::cleanup() {
  7504. StringStreams::cleanup();
  7505. }
  7506. ReusableStringStream::ReusableStringStream()
  7507. : m_index( StringStreams::instance().add() ),
  7508. m_oss( StringStreams::instance().m_streams[m_index].get() )
  7509. {}
  7510. ReusableStringStream::~ReusableStringStream() {
  7511. static_cast<std::ostringstream*>( m_oss )->str("");
  7512. m_oss->clear();
  7513. StringStreams::instance().release( m_index );
  7514. }
  7515. auto ReusableStringStream::str() const -> std::string {
  7516. return static_cast<std::ostringstream*>( m_oss )->str();
  7517. }
  7518. ///////////////////////////////////////////////////////////////////////////
  7519. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  7520. std::ostream& cout() { return std::cout; }
  7521. std::ostream& cerr() { return std::cerr; }
  7522. std::ostream& clog() { return std::clog; }
  7523. #endif
  7524. }
  7525. #if defined(__clang__)
  7526. # pragma clang diagnostic pop
  7527. #endif
  7528. // end catch_stream.cpp
  7529. // start catch_string_manip.cpp
  7530. #include <algorithm>
  7531. #include <ostream>
  7532. #include <cstring>
  7533. #include <cctype>
  7534. namespace Catch {
  7535. bool startsWith( std::string const& s, std::string const& prefix ) {
  7536. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  7537. }
  7538. bool startsWith( std::string const& s, char prefix ) {
  7539. return !s.empty() && s[0] == prefix;
  7540. }
  7541. bool endsWith( std::string const& s, std::string const& suffix ) {
  7542. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  7543. }
  7544. bool endsWith( std::string const& s, char suffix ) {
  7545. return !s.empty() && s[s.size()-1] == suffix;
  7546. }
  7547. bool contains( std::string const& s, std::string const& infix ) {
  7548. return s.find( infix ) != std::string::npos;
  7549. }
  7550. char toLowerCh(char c) {
  7551. return static_cast<char>( std::tolower( c ) );
  7552. }
  7553. void toLowerInPlace( std::string& s ) {
  7554. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  7555. }
  7556. std::string toLower( std::string const& s ) {
  7557. std::string lc = s;
  7558. toLowerInPlace( lc );
  7559. return lc;
  7560. }
  7561. std::string trim( std::string const& str ) {
  7562. static char const* whitespaceChars = "\n\r\t ";
  7563. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  7564. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  7565. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  7566. }
  7567. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  7568. bool replaced = false;
  7569. std::size_t i = str.find( replaceThis );
  7570. while( i != std::string::npos ) {
  7571. replaced = true;
  7572. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  7573. if( i < str.size()-withThis.size() )
  7574. i = str.find( replaceThis, i+withThis.size() );
  7575. else
  7576. i = std::string::npos;
  7577. }
  7578. return replaced;
  7579. }
  7580. pluralise::pluralise( std::size_t count, std::string const& label )
  7581. : m_count( count ),
  7582. m_label( label )
  7583. {}
  7584. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  7585. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  7586. if( pluraliser.m_count != 1 )
  7587. os << 's';
  7588. return os;
  7589. }
  7590. }
  7591. // end catch_string_manip.cpp
  7592. // start catch_stringref.cpp
  7593. #if defined(__clang__)
  7594. # pragma clang diagnostic push
  7595. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7596. #endif
  7597. #include <ostream>
  7598. #include <cstring>
  7599. #include <cstdint>
  7600. namespace {
  7601. const uint32_t byte_2_lead = 0xC0;
  7602. const uint32_t byte_3_lead = 0xE0;
  7603. const uint32_t byte_4_lead = 0xF0;
  7604. }
  7605. namespace Catch {
  7606. StringRef::StringRef( char const* rawChars ) noexcept
  7607. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  7608. {}
  7609. StringRef::operator std::string() const {
  7610. return std::string( m_start, m_size );
  7611. }
  7612. void StringRef::swap( StringRef& other ) noexcept {
  7613. std::swap( m_start, other.m_start );
  7614. std::swap( m_size, other.m_size );
  7615. std::swap( m_data, other.m_data );
  7616. }
  7617. auto StringRef::c_str() const -> char const* {
  7618. if( isSubstring() )
  7619. const_cast<StringRef*>( this )->takeOwnership();
  7620. return m_start;
  7621. }
  7622. auto StringRef::data() const noexcept -> char const* {
  7623. return m_start;
  7624. }
  7625. auto StringRef::isOwned() const noexcept -> bool {
  7626. return m_data != nullptr;
  7627. }
  7628. auto StringRef::isSubstring() const noexcept -> bool {
  7629. return m_start[m_size] != '\0';
  7630. }
  7631. void StringRef::takeOwnership() {
  7632. if( !isOwned() ) {
  7633. m_data = new char[m_size+1];
  7634. memcpy( m_data, m_start, m_size );
  7635. m_data[m_size] = '\0';
  7636. m_start = m_data;
  7637. }
  7638. }
  7639. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  7640. if( start < m_size )
  7641. return StringRef( m_start+start, size );
  7642. else
  7643. return StringRef();
  7644. }
  7645. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  7646. return
  7647. size() == other.size() &&
  7648. (std::strncmp( m_start, other.m_start, size() ) == 0);
  7649. }
  7650. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  7651. return !operator==( other );
  7652. }
  7653. auto StringRef::operator[](size_type index) const noexcept -> char {
  7654. return m_start[index];
  7655. }
  7656. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  7657. size_type noChars = m_size;
  7658. // Make adjustments for uft encodings
  7659. for( size_type i=0; i < m_size; ++i ) {
  7660. char c = m_start[i];
  7661. if( ( c & byte_2_lead ) == byte_2_lead ) {
  7662. noChars--;
  7663. if (( c & byte_3_lead ) == byte_3_lead )
  7664. noChars--;
  7665. if( ( c & byte_4_lead ) == byte_4_lead )
  7666. noChars--;
  7667. }
  7668. }
  7669. return noChars;
  7670. }
  7671. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  7672. std::string str;
  7673. str.reserve( lhs.size() + rhs.size() );
  7674. str += lhs;
  7675. str += rhs;
  7676. return str;
  7677. }
  7678. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  7679. return std::string( lhs ) + std::string( rhs );
  7680. }
  7681. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  7682. return std::string( lhs ) + std::string( rhs );
  7683. }
  7684. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  7685. return os << str.c_str();
  7686. }
  7687. } // namespace Catch
  7688. #if defined(__clang__)
  7689. # pragma clang diagnostic pop
  7690. #endif
  7691. // end catch_stringref.cpp
  7692. // start catch_tag_alias.cpp
  7693. namespace Catch {
  7694. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  7695. }
  7696. // end catch_tag_alias.cpp
  7697. // start catch_tag_alias_autoregistrar.cpp
  7698. namespace Catch {
  7699. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  7700. try {
  7701. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  7702. } catch (...) {
  7703. // Do not throw when constructing global objects, instead register the exception to be processed later
  7704. getMutableRegistryHub().registerStartupException();
  7705. }
  7706. }
  7707. }
  7708. // end catch_tag_alias_autoregistrar.cpp
  7709. // start catch_tag_alias_registry.cpp
  7710. #include <sstream>
  7711. namespace Catch {
  7712. TagAliasRegistry::~TagAliasRegistry() {}
  7713. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  7714. auto it = m_registry.find( alias );
  7715. if( it != m_registry.end() )
  7716. return &(it->second);
  7717. else
  7718. return nullptr;
  7719. }
  7720. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  7721. std::string expandedTestSpec = unexpandedTestSpec;
  7722. for( auto const& registryKvp : m_registry ) {
  7723. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  7724. if( pos != std::string::npos ) {
  7725. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  7726. registryKvp.second.tag +
  7727. expandedTestSpec.substr( pos + registryKvp.first.size() );
  7728. }
  7729. }
  7730. return expandedTestSpec;
  7731. }
  7732. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  7733. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  7734. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  7735. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  7736. "error: tag alias, '" << alias << "' already registered.\n"
  7737. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  7738. << "\tRedefined at: " << lineInfo );
  7739. }
  7740. ITagAliasRegistry::~ITagAliasRegistry() {}
  7741. ITagAliasRegistry const& ITagAliasRegistry::get() {
  7742. return getRegistryHub().getTagAliasRegistry();
  7743. }
  7744. } // end namespace Catch
  7745. // end catch_tag_alias_registry.cpp
  7746. // start catch_test_case_info.cpp
  7747. #include <cctype>
  7748. #include <exception>
  7749. #include <algorithm>
  7750. #include <sstream>
  7751. namespace Catch {
  7752. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  7753. if( startsWith( tag, '.' ) ||
  7754. tag == "!hide" )
  7755. return TestCaseInfo::IsHidden;
  7756. else if( tag == "!throws" )
  7757. return TestCaseInfo::Throws;
  7758. else if( tag == "!shouldfail" )
  7759. return TestCaseInfo::ShouldFail;
  7760. else if( tag == "!mayfail" )
  7761. return TestCaseInfo::MayFail;
  7762. else if( tag == "!nonportable" )
  7763. return TestCaseInfo::NonPortable;
  7764. else if( tag == "!benchmark" )
  7765. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  7766. else
  7767. return TestCaseInfo::None;
  7768. }
  7769. bool isReservedTag( std::string const& tag ) {
  7770. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( tag[0] );
  7771. }
  7772. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  7773. CATCH_ENFORCE( !isReservedTag(tag),
  7774. "Tag name: [" << tag << "] is not allowed.\n"
  7775. << "Tag names starting with non alpha-numeric characters are reserved\n"
  7776. << _lineInfo );
  7777. }
  7778. TestCase makeTestCase( ITestInvoker* _testCase,
  7779. std::string const& _className,
  7780. std::string const& _name,
  7781. std::string const& _descOrTags,
  7782. SourceLineInfo const& _lineInfo )
  7783. {
  7784. bool isHidden = false;
  7785. // Parse out tags
  7786. std::vector<std::string> tags;
  7787. std::string desc, tag;
  7788. bool inTag = false;
  7789. for (char c : _descOrTags) {
  7790. if( !inTag ) {
  7791. if( c == '[' )
  7792. inTag = true;
  7793. else
  7794. desc += c;
  7795. }
  7796. else {
  7797. if( c == ']' ) {
  7798. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  7799. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  7800. isHidden = true;
  7801. else if( prop == TestCaseInfo::None )
  7802. enforceNotReservedTag( tag, _lineInfo );
  7803. tags.push_back( tag );
  7804. tag.clear();
  7805. inTag = false;
  7806. }
  7807. else
  7808. tag += c;
  7809. }
  7810. }
  7811. if( isHidden ) {
  7812. tags.push_back( "." );
  7813. }
  7814. TestCaseInfo info( _name, _className, desc, tags, _lineInfo );
  7815. return TestCase( _testCase, info );
  7816. }
  7817. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  7818. std::sort(begin(tags), end(tags));
  7819. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  7820. testCaseInfo.lcaseTags.clear();
  7821. for( auto const& tag : tags ) {
  7822. std::string lcaseTag = toLower( tag );
  7823. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  7824. testCaseInfo.lcaseTags.push_back( lcaseTag );
  7825. }
  7826. testCaseInfo.tags = std::move(tags);
  7827. }
  7828. TestCaseInfo::TestCaseInfo( std::string const& _name,
  7829. std::string const& _className,
  7830. std::string const& _description,
  7831. std::vector<std::string> const& _tags,
  7832. SourceLineInfo const& _lineInfo )
  7833. : name( _name ),
  7834. className( _className ),
  7835. description( _description ),
  7836. lineInfo( _lineInfo ),
  7837. properties( None )
  7838. {
  7839. setTags( *this, _tags );
  7840. }
  7841. bool TestCaseInfo::isHidden() const {
  7842. return ( properties & IsHidden ) != 0;
  7843. }
  7844. bool TestCaseInfo::throws() const {
  7845. return ( properties & Throws ) != 0;
  7846. }
  7847. bool TestCaseInfo::okToFail() const {
  7848. return ( properties & (ShouldFail | MayFail ) ) != 0;
  7849. }
  7850. bool TestCaseInfo::expectedToFail() const {
  7851. return ( properties & (ShouldFail ) ) != 0;
  7852. }
  7853. std::string TestCaseInfo::tagsAsString() const {
  7854. std::string ret;
  7855. // '[' and ']' per tag
  7856. std::size_t full_size = 2 * tags.size();
  7857. for (const auto& tag : tags) {
  7858. full_size += tag.size();
  7859. }
  7860. ret.reserve(full_size);
  7861. for (const auto& tag : tags) {
  7862. ret.push_back('[');
  7863. ret.append(tag);
  7864. ret.push_back(']');
  7865. }
  7866. return ret;
  7867. }
  7868. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo const& info ) : TestCaseInfo( info ), test( testCase ) {}
  7869. TestCase TestCase::withName( std::string const& _newName ) const {
  7870. TestCase other( *this );
  7871. other.name = _newName;
  7872. return other;
  7873. }
  7874. void TestCase::invoke() const {
  7875. test->invoke();
  7876. }
  7877. bool TestCase::operator == ( TestCase const& other ) const {
  7878. return test.get() == other.test.get() &&
  7879. name == other.name &&
  7880. className == other.className;
  7881. }
  7882. bool TestCase::operator < ( TestCase const& other ) const {
  7883. return name < other.name;
  7884. }
  7885. TestCaseInfo const& TestCase::getTestCaseInfo() const
  7886. {
  7887. return *this;
  7888. }
  7889. } // end namespace Catch
  7890. // end catch_test_case_info.cpp
  7891. // start catch_test_case_registry_impl.cpp
  7892. #include <sstream>
  7893. namespace Catch {
  7894. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  7895. std::vector<TestCase> sorted = unsortedTestCases;
  7896. switch( config.runOrder() ) {
  7897. case RunTests::InLexicographicalOrder:
  7898. std::sort( sorted.begin(), sorted.end() );
  7899. break;
  7900. case RunTests::InRandomOrder:
  7901. seedRng( config );
  7902. RandomNumberGenerator::shuffle( sorted );
  7903. break;
  7904. case RunTests::InDeclarationOrder:
  7905. // already in declaration order
  7906. break;
  7907. }
  7908. return sorted;
  7909. }
  7910. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  7911. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  7912. }
  7913. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  7914. std::set<TestCase> seenFunctions;
  7915. for( auto const& function : functions ) {
  7916. auto prev = seenFunctions.insert( function );
  7917. CATCH_ENFORCE( prev.second,
  7918. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  7919. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  7920. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  7921. }
  7922. }
  7923. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  7924. std::vector<TestCase> filtered;
  7925. filtered.reserve( testCases.size() );
  7926. for( auto const& testCase : testCases )
  7927. if( matchTest( testCase, testSpec, config ) )
  7928. filtered.push_back( testCase );
  7929. return filtered;
  7930. }
  7931. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  7932. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  7933. }
  7934. void TestRegistry::registerTest( TestCase const& testCase ) {
  7935. std::string name = testCase.getTestCaseInfo().name;
  7936. if( name.empty() ) {
  7937. ReusableStringStream rss;
  7938. rss << "Anonymous test case " << ++m_unnamedCount;
  7939. return registerTest( testCase.withName( rss.str() ) );
  7940. }
  7941. m_functions.push_back( testCase );
  7942. }
  7943. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  7944. return m_functions;
  7945. }
  7946. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  7947. if( m_sortedFunctions.empty() )
  7948. enforceNoDuplicateTestCases( m_functions );
  7949. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  7950. m_sortedFunctions = sortTests( config, m_functions );
  7951. m_currentSortOrder = config.runOrder();
  7952. }
  7953. return m_sortedFunctions;
  7954. }
  7955. ///////////////////////////////////////////////////////////////////////////
  7956. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  7957. void TestInvokerAsFunction::invoke() const {
  7958. m_testAsFunction();
  7959. }
  7960. std::string extractClassName( std::string const& classOrQualifiedMethodName ) {
  7961. std::string className = classOrQualifiedMethodName;
  7962. if( startsWith( className, '&' ) )
  7963. {
  7964. std::size_t lastColons = className.rfind( "::" );
  7965. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  7966. if( penultimateColons == std::string::npos )
  7967. penultimateColons = 1;
  7968. className = className.substr( penultimateColons, lastColons-penultimateColons );
  7969. }
  7970. return className;
  7971. }
  7972. } // end namespace Catch
  7973. // end catch_test_case_registry_impl.cpp
  7974. // start catch_test_case_tracker.cpp
  7975. #include <algorithm>
  7976. #include <assert.h>
  7977. #include <stdexcept>
  7978. #include <memory>
  7979. #include <sstream>
  7980. #if defined(__clang__)
  7981. # pragma clang diagnostic push
  7982. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7983. #endif
  7984. namespace Catch {
  7985. namespace TestCaseTracking {
  7986. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  7987. : name( _name ),
  7988. location( _location )
  7989. {}
  7990. ITracker::~ITracker() = default;
  7991. TrackerContext& TrackerContext::instance() {
  7992. static TrackerContext s_instance;
  7993. return s_instance;
  7994. }
  7995. ITracker& TrackerContext::startRun() {
  7996. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  7997. m_currentTracker = nullptr;
  7998. m_runState = Executing;
  7999. return *m_rootTracker;
  8000. }
  8001. void TrackerContext::endRun() {
  8002. m_rootTracker.reset();
  8003. m_currentTracker = nullptr;
  8004. m_runState = NotStarted;
  8005. }
  8006. void TrackerContext::startCycle() {
  8007. m_currentTracker = m_rootTracker.get();
  8008. m_runState = Executing;
  8009. }
  8010. void TrackerContext::completeCycle() {
  8011. m_runState = CompletedCycle;
  8012. }
  8013. bool TrackerContext::completedCycle() const {
  8014. return m_runState == CompletedCycle;
  8015. }
  8016. ITracker& TrackerContext::currentTracker() {
  8017. return *m_currentTracker;
  8018. }
  8019. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  8020. m_currentTracker = tracker;
  8021. }
  8022. TrackerBase::TrackerHasName::TrackerHasName( NameAndLocation const& nameAndLocation ) : m_nameAndLocation( nameAndLocation ) {}
  8023. bool TrackerBase::TrackerHasName::operator ()( ITrackerPtr const& tracker ) const {
  8024. return
  8025. tracker->nameAndLocation().name == m_nameAndLocation.name &&
  8026. tracker->nameAndLocation().location == m_nameAndLocation.location;
  8027. }
  8028. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8029. : m_nameAndLocation( nameAndLocation ),
  8030. m_ctx( ctx ),
  8031. m_parent( parent )
  8032. {}
  8033. NameAndLocation const& TrackerBase::nameAndLocation() const {
  8034. return m_nameAndLocation;
  8035. }
  8036. bool TrackerBase::isComplete() const {
  8037. return m_runState == CompletedSuccessfully || m_runState == Failed;
  8038. }
  8039. bool TrackerBase::isSuccessfullyCompleted() const {
  8040. return m_runState == CompletedSuccessfully;
  8041. }
  8042. bool TrackerBase::isOpen() const {
  8043. return m_runState != NotStarted && !isComplete();
  8044. }
  8045. bool TrackerBase::hasChildren() const {
  8046. return !m_children.empty();
  8047. }
  8048. void TrackerBase::addChild( ITrackerPtr const& child ) {
  8049. m_children.push_back( child );
  8050. }
  8051. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  8052. auto it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( nameAndLocation ) );
  8053. return( it != m_children.end() )
  8054. ? *it
  8055. : nullptr;
  8056. }
  8057. ITracker& TrackerBase::parent() {
  8058. assert( m_parent ); // Should always be non-null except for root
  8059. return *m_parent;
  8060. }
  8061. void TrackerBase::openChild() {
  8062. if( m_runState != ExecutingChildren ) {
  8063. m_runState = ExecutingChildren;
  8064. if( m_parent )
  8065. m_parent->openChild();
  8066. }
  8067. }
  8068. bool TrackerBase::isSectionTracker() const { return false; }
  8069. bool TrackerBase::isIndexTracker() const { return false; }
  8070. void TrackerBase::open() {
  8071. m_runState = Executing;
  8072. moveToThis();
  8073. if( m_parent )
  8074. m_parent->openChild();
  8075. }
  8076. void TrackerBase::close() {
  8077. // Close any still open children (e.g. generators)
  8078. while( &m_ctx.currentTracker() != this )
  8079. m_ctx.currentTracker().close();
  8080. switch( m_runState ) {
  8081. case NeedsAnotherRun:
  8082. break;
  8083. case Executing:
  8084. m_runState = CompletedSuccessfully;
  8085. break;
  8086. case ExecutingChildren:
  8087. if( m_children.empty() || m_children.back()->isComplete() )
  8088. m_runState = CompletedSuccessfully;
  8089. break;
  8090. case NotStarted:
  8091. case CompletedSuccessfully:
  8092. case Failed:
  8093. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  8094. default:
  8095. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  8096. }
  8097. moveToParent();
  8098. m_ctx.completeCycle();
  8099. }
  8100. void TrackerBase::fail() {
  8101. m_runState = Failed;
  8102. if( m_parent )
  8103. m_parent->markAsNeedingAnotherRun();
  8104. moveToParent();
  8105. m_ctx.completeCycle();
  8106. }
  8107. void TrackerBase::markAsNeedingAnotherRun() {
  8108. m_runState = NeedsAnotherRun;
  8109. }
  8110. void TrackerBase::moveToParent() {
  8111. assert( m_parent );
  8112. m_ctx.setCurrentTracker( m_parent );
  8113. }
  8114. void TrackerBase::moveToThis() {
  8115. m_ctx.setCurrentTracker( this );
  8116. }
  8117. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8118. : TrackerBase( nameAndLocation, ctx, parent )
  8119. {
  8120. if( parent ) {
  8121. while( !parent->isSectionTracker() )
  8122. parent = &parent->parent();
  8123. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  8124. addNextFilters( parentSection.m_filters );
  8125. }
  8126. }
  8127. bool SectionTracker::isSectionTracker() const { return true; }
  8128. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  8129. std::shared_ptr<SectionTracker> section;
  8130. ITracker& currentTracker = ctx.currentTracker();
  8131. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8132. assert( childTracker );
  8133. assert( childTracker->isSectionTracker() );
  8134. section = std::static_pointer_cast<SectionTracker>( childTracker );
  8135. }
  8136. else {
  8137. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  8138. currentTracker.addChild( section );
  8139. }
  8140. if( !ctx.completedCycle() )
  8141. section->tryOpen();
  8142. return *section;
  8143. }
  8144. void SectionTracker::tryOpen() {
  8145. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  8146. open();
  8147. }
  8148. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  8149. if( !filters.empty() ) {
  8150. m_filters.push_back(""); // Root - should never be consulted
  8151. m_filters.push_back(""); // Test Case - not a section filter
  8152. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  8153. }
  8154. }
  8155. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  8156. if( filters.size() > 1 )
  8157. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  8158. }
  8159. IndexTracker::IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size )
  8160. : TrackerBase( nameAndLocation, ctx, parent ),
  8161. m_size( size )
  8162. {}
  8163. bool IndexTracker::isIndexTracker() const { return true; }
  8164. IndexTracker& IndexTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) {
  8165. std::shared_ptr<IndexTracker> tracker;
  8166. ITracker& currentTracker = ctx.currentTracker();
  8167. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8168. assert( childTracker );
  8169. assert( childTracker->isIndexTracker() );
  8170. tracker = std::static_pointer_cast<IndexTracker>( childTracker );
  8171. }
  8172. else {
  8173. tracker = std::make_shared<IndexTracker>( nameAndLocation, ctx, &currentTracker, size );
  8174. currentTracker.addChild( tracker );
  8175. }
  8176. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  8177. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  8178. tracker->moveNext();
  8179. tracker->open();
  8180. }
  8181. return *tracker;
  8182. }
  8183. int IndexTracker::index() const { return m_index; }
  8184. void IndexTracker::moveNext() {
  8185. m_index++;
  8186. m_children.clear();
  8187. }
  8188. void IndexTracker::close() {
  8189. TrackerBase::close();
  8190. if( m_runState == CompletedSuccessfully && m_index < m_size-1 )
  8191. m_runState = Executing;
  8192. }
  8193. } // namespace TestCaseTracking
  8194. using TestCaseTracking::ITracker;
  8195. using TestCaseTracking::TrackerContext;
  8196. using TestCaseTracking::SectionTracker;
  8197. using TestCaseTracking::IndexTracker;
  8198. } // namespace Catch
  8199. #if defined(__clang__)
  8200. # pragma clang diagnostic pop
  8201. #endif
  8202. // end catch_test_case_tracker.cpp
  8203. // start catch_test_registry.cpp
  8204. namespace Catch {
  8205. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  8206. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  8207. }
  8208. NameAndTags::NameAndTags( StringRef name_ , StringRef tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  8209. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  8210. try {
  8211. getMutableRegistryHub()
  8212. .registerTest(
  8213. makeTestCase(
  8214. invoker,
  8215. extractClassName( classOrMethod ),
  8216. nameAndTags.name,
  8217. nameAndTags.tags,
  8218. lineInfo));
  8219. } catch (...) {
  8220. // Do not throw when constructing global objects, instead register the exception to be processed later
  8221. getMutableRegistryHub().registerStartupException();
  8222. }
  8223. }
  8224. AutoReg::~AutoReg() = default;
  8225. }
  8226. // end catch_test_registry.cpp
  8227. // start catch_test_spec.cpp
  8228. #include <algorithm>
  8229. #include <string>
  8230. #include <vector>
  8231. #include <memory>
  8232. namespace Catch {
  8233. TestSpec::Pattern::~Pattern() = default;
  8234. TestSpec::NamePattern::~NamePattern() = default;
  8235. TestSpec::TagPattern::~TagPattern() = default;
  8236. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  8237. TestSpec::NamePattern::NamePattern( std::string const& name )
  8238. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  8239. {}
  8240. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  8241. return m_wildcardPattern.matches( toLower( testCase.name ) );
  8242. }
  8243. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  8244. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  8245. return std::find(begin(testCase.lcaseTags),
  8246. end(testCase.lcaseTags),
  8247. m_tag) != end(testCase.lcaseTags);
  8248. }
  8249. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  8250. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  8251. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  8252. // All patterns in a filter must match for the filter to be a match
  8253. for( auto const& pattern : m_patterns ) {
  8254. if( !pattern->matches( testCase ) )
  8255. return false;
  8256. }
  8257. return true;
  8258. }
  8259. bool TestSpec::hasFilters() const {
  8260. return !m_filters.empty();
  8261. }
  8262. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  8263. // A TestSpec matches if any filter matches
  8264. for( auto const& filter : m_filters )
  8265. if( filter.matches( testCase ) )
  8266. return true;
  8267. return false;
  8268. }
  8269. }
  8270. // end catch_test_spec.cpp
  8271. // start catch_test_spec_parser.cpp
  8272. namespace Catch {
  8273. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  8274. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  8275. m_mode = None;
  8276. m_exclusion = false;
  8277. m_start = std::string::npos;
  8278. m_arg = m_tagAliases->expandAliases( arg );
  8279. m_escapeChars.clear();
  8280. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  8281. visitChar( m_arg[m_pos] );
  8282. if( m_mode == Name )
  8283. addPattern<TestSpec::NamePattern>();
  8284. return *this;
  8285. }
  8286. TestSpec TestSpecParser::testSpec() {
  8287. addFilter();
  8288. return m_testSpec;
  8289. }
  8290. void TestSpecParser::visitChar( char c ) {
  8291. if( m_mode == None ) {
  8292. switch( c ) {
  8293. case ' ': return;
  8294. case '~': m_exclusion = true; return;
  8295. case '[': return startNewMode( Tag, ++m_pos );
  8296. case '"': return startNewMode( QuotedName, ++m_pos );
  8297. case '\\': return escape();
  8298. default: startNewMode( Name, m_pos ); break;
  8299. }
  8300. }
  8301. if( m_mode == Name ) {
  8302. if( c == ',' ) {
  8303. addPattern<TestSpec::NamePattern>();
  8304. addFilter();
  8305. }
  8306. else if( c == '[' ) {
  8307. if( subString() == "exclude:" )
  8308. m_exclusion = true;
  8309. else
  8310. addPattern<TestSpec::NamePattern>();
  8311. startNewMode( Tag, ++m_pos );
  8312. }
  8313. else if( c == '\\' )
  8314. escape();
  8315. }
  8316. else if( m_mode == EscapedName )
  8317. m_mode = Name;
  8318. else if( m_mode == QuotedName && c == '"' )
  8319. addPattern<TestSpec::NamePattern>();
  8320. else if( m_mode == Tag && c == ']' )
  8321. addPattern<TestSpec::TagPattern>();
  8322. }
  8323. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  8324. m_mode = mode;
  8325. m_start = start;
  8326. }
  8327. void TestSpecParser::escape() {
  8328. if( m_mode == None )
  8329. m_start = m_pos;
  8330. m_mode = EscapedName;
  8331. m_escapeChars.push_back( m_pos );
  8332. }
  8333. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  8334. void TestSpecParser::addFilter() {
  8335. if( !m_currentFilter.m_patterns.empty() ) {
  8336. m_testSpec.m_filters.push_back( m_currentFilter );
  8337. m_currentFilter = TestSpec::Filter();
  8338. }
  8339. }
  8340. TestSpec parseTestSpec( std::string const& arg ) {
  8341. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  8342. }
  8343. } // namespace Catch
  8344. // end catch_test_spec_parser.cpp
  8345. // start catch_timer.cpp
  8346. #include <chrono>
  8347. namespace Catch {
  8348. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  8349. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  8350. }
  8351. auto estimateClockResolution() -> uint64_t {
  8352. uint64_t sum = 0;
  8353. static const uint64_t iterations = 1000000;
  8354. for( std::size_t i = 0; i < iterations; ++i ) {
  8355. uint64_t ticks;
  8356. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  8357. do {
  8358. ticks = getCurrentNanosecondsSinceEpoch();
  8359. }
  8360. while( ticks == baseTicks );
  8361. auto delta = ticks - baseTicks;
  8362. sum += delta;
  8363. }
  8364. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  8365. // - and potentially do more iterations if there's a high variance.
  8366. return sum/iterations;
  8367. }
  8368. auto getEstimatedClockResolution() -> uint64_t {
  8369. static auto s_resolution = estimateClockResolution();
  8370. return s_resolution;
  8371. }
  8372. void Timer::start() {
  8373. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  8374. }
  8375. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  8376. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  8377. }
  8378. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  8379. return getElapsedNanoseconds()/1000;
  8380. }
  8381. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  8382. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  8383. }
  8384. auto Timer::getElapsedSeconds() const -> double {
  8385. return getElapsedMicroseconds()/1000000.0;
  8386. }
  8387. } // namespace Catch
  8388. // end catch_timer.cpp
  8389. // start catch_tostring.cpp
  8390. #if defined(__clang__)
  8391. # pragma clang diagnostic push
  8392. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8393. # pragma clang diagnostic ignored "-Wglobal-constructors"
  8394. #endif
  8395. // Enable specific decls locally
  8396. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  8397. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  8398. #endif
  8399. #include <cmath>
  8400. #include <iomanip>
  8401. namespace Catch {
  8402. namespace Detail {
  8403. const std::string unprintableString = "{?}";
  8404. namespace {
  8405. const int hexThreshold = 255;
  8406. struct Endianness {
  8407. enum Arch { Big, Little };
  8408. static Arch which() {
  8409. union _{
  8410. int asInt;
  8411. char asChar[sizeof (int)];
  8412. } u;
  8413. u.asInt = 1;
  8414. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  8415. }
  8416. };
  8417. }
  8418. std::string rawMemoryToString( const void *object, std::size_t size ) {
  8419. // Reverse order for little endian architectures
  8420. int i = 0, end = static_cast<int>( size ), inc = 1;
  8421. if( Endianness::which() == Endianness::Little ) {
  8422. i = end-1;
  8423. end = inc = -1;
  8424. }
  8425. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  8426. ReusableStringStream rss;
  8427. rss << "0x" << std::setfill('0') << std::hex;
  8428. for( ; i != end; i += inc )
  8429. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  8430. return rss.str();
  8431. }
  8432. }
  8433. template<typename T>
  8434. std::string fpToString( T value, int precision ) {
  8435. if (std::isnan(value)) {
  8436. return "nan";
  8437. }
  8438. ReusableStringStream rss;
  8439. rss << std::setprecision( precision )
  8440. << std::fixed
  8441. << value;
  8442. std::string d = rss.str();
  8443. std::size_t i = d.find_last_not_of( '0' );
  8444. if( i != std::string::npos && i != d.size()-1 ) {
  8445. if( d[i] == '.' )
  8446. i++;
  8447. d = d.substr( 0, i+1 );
  8448. }
  8449. return d;
  8450. }
  8451. //// ======================================================= ////
  8452. //
  8453. // Out-of-line defs for full specialization of StringMaker
  8454. //
  8455. //// ======================================================= ////
  8456. std::string StringMaker<std::string>::convert(const std::string& str) {
  8457. if (!getCurrentContext().getConfig()->showInvisibles()) {
  8458. return '"' + str + '"';
  8459. }
  8460. std::string s("\"");
  8461. for (char c : str) {
  8462. switch (c) {
  8463. case '\n':
  8464. s.append("\\n");
  8465. break;
  8466. case '\t':
  8467. s.append("\\t");
  8468. break;
  8469. default:
  8470. s.push_back(c);
  8471. break;
  8472. }
  8473. }
  8474. s.append("\"");
  8475. return s;
  8476. }
  8477. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  8478. std::string s;
  8479. s.reserve(wstr.size());
  8480. for (auto c : wstr) {
  8481. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  8482. }
  8483. return ::Catch::Detail::stringify(s);
  8484. }
  8485. std::string StringMaker<char const*>::convert(char const* str) {
  8486. if (str) {
  8487. return ::Catch::Detail::stringify(std::string{ str });
  8488. } else {
  8489. return{ "{null string}" };
  8490. }
  8491. }
  8492. std::string StringMaker<char*>::convert(char* str) {
  8493. if (str) {
  8494. return ::Catch::Detail::stringify(std::string{ str });
  8495. } else {
  8496. return{ "{null string}" };
  8497. }
  8498. }
  8499. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  8500. if (str) {
  8501. return ::Catch::Detail::stringify(std::wstring{ str });
  8502. } else {
  8503. return{ "{null string}" };
  8504. }
  8505. }
  8506. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  8507. if (str) {
  8508. return ::Catch::Detail::stringify(std::wstring{ str });
  8509. } else {
  8510. return{ "{null string}" };
  8511. }
  8512. }
  8513. std::string StringMaker<int>::convert(int value) {
  8514. return ::Catch::Detail::stringify(static_cast<long long>(value));
  8515. }
  8516. std::string StringMaker<long>::convert(long value) {
  8517. return ::Catch::Detail::stringify(static_cast<long long>(value));
  8518. }
  8519. std::string StringMaker<long long>::convert(long long value) {
  8520. ReusableStringStream rss;
  8521. rss << value;
  8522. if (value > Detail::hexThreshold) {
  8523. rss << " (0x" << std::hex << value << ')';
  8524. }
  8525. return rss.str();
  8526. }
  8527. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  8528. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  8529. }
  8530. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  8531. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  8532. }
  8533. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  8534. ReusableStringStream rss;
  8535. rss << value;
  8536. if (value > Detail::hexThreshold) {
  8537. rss << " (0x" << std::hex << value << ')';
  8538. }
  8539. return rss.str();
  8540. }
  8541. std::string StringMaker<bool>::convert(bool b) {
  8542. return b ? "true" : "false";
  8543. }
  8544. std::string StringMaker<char>::convert(char value) {
  8545. if (value == '\r') {
  8546. return "'\\r'";
  8547. } else if (value == '\f') {
  8548. return "'\\f'";
  8549. } else if (value == '\n') {
  8550. return "'\\n'";
  8551. } else if (value == '\t') {
  8552. return "'\\t'";
  8553. } else if ('\0' <= value && value < ' ') {
  8554. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  8555. } else {
  8556. char chstr[] = "' '";
  8557. chstr[1] = value;
  8558. return chstr;
  8559. }
  8560. }
  8561. std::string StringMaker<signed char>::convert(signed char c) {
  8562. return ::Catch::Detail::stringify(static_cast<char>(c));
  8563. }
  8564. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  8565. return ::Catch::Detail::stringify(static_cast<char>(c));
  8566. }
  8567. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  8568. return "nullptr";
  8569. }
  8570. std::string StringMaker<float>::convert(float value) {
  8571. return fpToString(value, 5) + 'f';
  8572. }
  8573. std::string StringMaker<double>::convert(double value) {
  8574. return fpToString(value, 10);
  8575. }
  8576. std::string ratio_string<std::atto>::symbol() { return "a"; }
  8577. std::string ratio_string<std::femto>::symbol() { return "f"; }
  8578. std::string ratio_string<std::pico>::symbol() { return "p"; }
  8579. std::string ratio_string<std::nano>::symbol() { return "n"; }
  8580. std::string ratio_string<std::micro>::symbol() { return "u"; }
  8581. std::string ratio_string<std::milli>::symbol() { return "m"; }
  8582. } // end namespace Catch
  8583. #if defined(__clang__)
  8584. # pragma clang diagnostic pop
  8585. #endif
  8586. // end catch_tostring.cpp
  8587. // start catch_totals.cpp
  8588. namespace Catch {
  8589. Counts Counts::operator - ( Counts const& other ) const {
  8590. Counts diff;
  8591. diff.passed = passed - other.passed;
  8592. diff.failed = failed - other.failed;
  8593. diff.failedButOk = failedButOk - other.failedButOk;
  8594. return diff;
  8595. }
  8596. Counts& Counts::operator += ( Counts const& other ) {
  8597. passed += other.passed;
  8598. failed += other.failed;
  8599. failedButOk += other.failedButOk;
  8600. return *this;
  8601. }
  8602. std::size_t Counts::total() const {
  8603. return passed + failed + failedButOk;
  8604. }
  8605. bool Counts::allPassed() const {
  8606. return failed == 0 && failedButOk == 0;
  8607. }
  8608. bool Counts::allOk() const {
  8609. return failed == 0;
  8610. }
  8611. Totals Totals::operator - ( Totals const& other ) const {
  8612. Totals diff;
  8613. diff.assertions = assertions - other.assertions;
  8614. diff.testCases = testCases - other.testCases;
  8615. return diff;
  8616. }
  8617. Totals& Totals::operator += ( Totals const& other ) {
  8618. assertions += other.assertions;
  8619. testCases += other.testCases;
  8620. return *this;
  8621. }
  8622. Totals Totals::delta( Totals const& prevTotals ) const {
  8623. Totals diff = *this - prevTotals;
  8624. if( diff.assertions.failed > 0 )
  8625. ++diff.testCases.failed;
  8626. else if( diff.assertions.failedButOk > 0 )
  8627. ++diff.testCases.failedButOk;
  8628. else
  8629. ++diff.testCases.passed;
  8630. return diff;
  8631. }
  8632. }
  8633. // end catch_totals.cpp
  8634. // start catch_uncaught_exceptions.cpp
  8635. #include <exception>
  8636. namespace Catch {
  8637. bool uncaught_exceptions() {
  8638. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  8639. return std::uncaught_exceptions() > 0;
  8640. #else
  8641. return std::uncaught_exception();
  8642. #endif
  8643. }
  8644. } // end namespace Catch
  8645. // end catch_uncaught_exceptions.cpp
  8646. // start catch_version.cpp
  8647. #include <ostream>
  8648. namespace Catch {
  8649. Version::Version
  8650. ( unsigned int _majorVersion,
  8651. unsigned int _minorVersion,
  8652. unsigned int _patchNumber,
  8653. char const * const _branchName,
  8654. unsigned int _buildNumber )
  8655. : majorVersion( _majorVersion ),
  8656. minorVersion( _minorVersion ),
  8657. patchNumber( _patchNumber ),
  8658. branchName( _branchName ),
  8659. buildNumber( _buildNumber )
  8660. {}
  8661. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  8662. os << version.majorVersion << '.'
  8663. << version.minorVersion << '.'
  8664. << version.patchNumber;
  8665. // branchName is never null -> 0th char is \0 if it is empty
  8666. if (version.branchName[0]) {
  8667. os << '-' << version.branchName
  8668. << '.' << version.buildNumber;
  8669. }
  8670. return os;
  8671. }
  8672. Version const& libraryVersion() {
  8673. static Version version( 2, 1, 2, "", 0 );
  8674. return version;
  8675. }
  8676. }
  8677. // end catch_version.cpp
  8678. // start catch_wildcard_pattern.cpp
  8679. #include <sstream>
  8680. namespace Catch {
  8681. WildcardPattern::WildcardPattern( std::string const& pattern,
  8682. CaseSensitive::Choice caseSensitivity )
  8683. : m_caseSensitivity( caseSensitivity ),
  8684. m_pattern( adjustCase( pattern ) )
  8685. {
  8686. if( startsWith( m_pattern, '*' ) ) {
  8687. m_pattern = m_pattern.substr( 1 );
  8688. m_wildcard = WildcardAtStart;
  8689. }
  8690. if( endsWith( m_pattern, '*' ) ) {
  8691. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  8692. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  8693. }
  8694. }
  8695. bool WildcardPattern::matches( std::string const& str ) const {
  8696. switch( m_wildcard ) {
  8697. case NoWildcard:
  8698. return m_pattern == adjustCase( str );
  8699. case WildcardAtStart:
  8700. return endsWith( adjustCase( str ), m_pattern );
  8701. case WildcardAtEnd:
  8702. return startsWith( adjustCase( str ), m_pattern );
  8703. case WildcardAtBothEnds:
  8704. return contains( adjustCase( str ), m_pattern );
  8705. default:
  8706. CATCH_INTERNAL_ERROR( "Unknown enum" );
  8707. }
  8708. }
  8709. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  8710. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  8711. }
  8712. }
  8713. // end catch_wildcard_pattern.cpp
  8714. // start catch_xmlwriter.cpp
  8715. #include <iomanip>
  8716. namespace Catch {
  8717. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  8718. : m_str( str ),
  8719. m_forWhat( forWhat )
  8720. {}
  8721. void XmlEncode::encodeTo( std::ostream& os ) const {
  8722. // Apostrophe escaping not necessary if we always use " to write attributes
  8723. // (see: http://www.w3.org/TR/xml/#syntax)
  8724. for( std::size_t i = 0; i < m_str.size(); ++ i ) {
  8725. char c = m_str[i];
  8726. switch( c ) {
  8727. case '<': os << "&lt;"; break;
  8728. case '&': os << "&amp;"; break;
  8729. case '>':
  8730. // See: http://www.w3.org/TR/xml/#syntax
  8731. if( i > 2 && m_str[i-1] == ']' && m_str[i-2] == ']' )
  8732. os << "&gt;";
  8733. else
  8734. os << c;
  8735. break;
  8736. case '\"':
  8737. if( m_forWhat == ForAttributes )
  8738. os << "&quot;";
  8739. else
  8740. os << c;
  8741. break;
  8742. default:
  8743. // Escape control chars - based on contribution by @espenalb in PR #465 and
  8744. // by @mrpi PR #588
  8745. if ( ( c >= 0 && c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) {
  8746. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  8747. os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  8748. << static_cast<int>( c );
  8749. }
  8750. else
  8751. os << c;
  8752. }
  8753. }
  8754. }
  8755. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  8756. xmlEncode.encodeTo( os );
  8757. return os;
  8758. }
  8759. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  8760. : m_writer( writer )
  8761. {}
  8762. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  8763. : m_writer( other.m_writer ){
  8764. other.m_writer = nullptr;
  8765. }
  8766. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  8767. if ( m_writer ) {
  8768. m_writer->endElement();
  8769. }
  8770. m_writer = other.m_writer;
  8771. other.m_writer = nullptr;
  8772. return *this;
  8773. }
  8774. XmlWriter::ScopedElement::~ScopedElement() {
  8775. if( m_writer )
  8776. m_writer->endElement();
  8777. }
  8778. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  8779. m_writer->writeText( text, indent );
  8780. return *this;
  8781. }
  8782. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  8783. {
  8784. writeDeclaration();
  8785. }
  8786. XmlWriter::~XmlWriter() {
  8787. while( !m_tags.empty() )
  8788. endElement();
  8789. }
  8790. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  8791. ensureTagClosed();
  8792. newlineIfNecessary();
  8793. m_os << m_indent << '<' << name;
  8794. m_tags.push_back( name );
  8795. m_indent += " ";
  8796. m_tagIsOpen = true;
  8797. return *this;
  8798. }
  8799. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  8800. ScopedElement scoped( this );
  8801. startElement( name );
  8802. return scoped;
  8803. }
  8804. XmlWriter& XmlWriter::endElement() {
  8805. newlineIfNecessary();
  8806. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  8807. if( m_tagIsOpen ) {
  8808. m_os << "/>";
  8809. m_tagIsOpen = false;
  8810. }
  8811. else {
  8812. m_os << m_indent << "</" << m_tags.back() << ">";
  8813. }
  8814. m_os << std::endl;
  8815. m_tags.pop_back();
  8816. return *this;
  8817. }
  8818. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  8819. if( !name.empty() && !attribute.empty() )
  8820. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  8821. return *this;
  8822. }
  8823. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  8824. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  8825. return *this;
  8826. }
  8827. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  8828. if( !text.empty() ){
  8829. bool tagWasOpen = m_tagIsOpen;
  8830. ensureTagClosed();
  8831. if( tagWasOpen && indent )
  8832. m_os << m_indent;
  8833. m_os << XmlEncode( text );
  8834. m_needsNewline = true;
  8835. }
  8836. return *this;
  8837. }
  8838. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  8839. ensureTagClosed();
  8840. m_os << m_indent << "<!--" << text << "-->";
  8841. m_needsNewline = true;
  8842. return *this;
  8843. }
  8844. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  8845. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  8846. }
  8847. XmlWriter& XmlWriter::writeBlankLine() {
  8848. ensureTagClosed();
  8849. m_os << '\n';
  8850. return *this;
  8851. }
  8852. void XmlWriter::ensureTagClosed() {
  8853. if( m_tagIsOpen ) {
  8854. m_os << ">" << std::endl;
  8855. m_tagIsOpen = false;
  8856. }
  8857. }
  8858. void XmlWriter::writeDeclaration() {
  8859. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  8860. }
  8861. void XmlWriter::newlineIfNecessary() {
  8862. if( m_needsNewline ) {
  8863. m_os << std::endl;
  8864. m_needsNewline = false;
  8865. }
  8866. }
  8867. }
  8868. // end catch_xmlwriter.cpp
  8869. // start catch_reporter_bases.cpp
  8870. #include <cstring>
  8871. #include <cfloat>
  8872. #include <cstdio>
  8873. #include <assert.h>
  8874. #include <memory>
  8875. namespace Catch {
  8876. void prepareExpandedExpression(AssertionResult& result) {
  8877. result.getExpandedExpression();
  8878. }
  8879. // Because formatting using c++ streams is stateful, drop down to C is required
  8880. // Alternatively we could use stringstream, but its performance is... not good.
  8881. std::string getFormattedDuration( double duration ) {
  8882. // Max exponent + 1 is required to represent the whole part
  8883. // + 1 for decimal point
  8884. // + 3 for the 3 decimal places
  8885. // + 1 for null terminator
  8886. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  8887. char buffer[maxDoubleSize];
  8888. // Save previous errno, to prevent sprintf from overwriting it
  8889. ErrnoGuard guard;
  8890. #ifdef _MSC_VER
  8891. sprintf_s(buffer, "%.3f", duration);
  8892. #else
  8893. sprintf(buffer, "%.3f", duration);
  8894. #endif
  8895. return std::string(buffer);
  8896. }
  8897. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  8898. :StreamingReporterBase(_config) {}
  8899. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  8900. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  8901. return false;
  8902. }
  8903. } // end namespace Catch
  8904. // end catch_reporter_bases.cpp
  8905. // start catch_reporter_compact.cpp
  8906. namespace {
  8907. #ifdef CATCH_PLATFORM_MAC
  8908. const char* failedString() { return "FAILED"; }
  8909. const char* passedString() { return "PASSED"; }
  8910. #else
  8911. const char* failedString() { return "failed"; }
  8912. const char* passedString() { return "passed"; }
  8913. #endif
  8914. // Colour::LightGrey
  8915. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  8916. std::string bothOrAll( std::size_t count ) {
  8917. return count == 1 ? std::string() :
  8918. count == 2 ? "both " : "all " ;
  8919. }
  8920. } // anon namespace
  8921. namespace Catch {
  8922. namespace {
  8923. // Colour, message variants:
  8924. // - white: No tests ran.
  8925. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  8926. // - white: Passed [both/all] N test cases (no assertions).
  8927. // - red: Failed N tests cases, failed M assertions.
  8928. // - green: Passed [both/all] N tests cases with M assertions.
  8929. void printTotals(std::ostream& out, const Totals& totals) {
  8930. if (totals.testCases.total() == 0) {
  8931. out << "No tests ran.";
  8932. } else if (totals.testCases.failed == totals.testCases.total()) {
  8933. Colour colour(Colour::ResultError);
  8934. const std::string qualify_assertions_failed =
  8935. totals.assertions.failed == totals.assertions.total() ?
  8936. bothOrAll(totals.assertions.failed) : std::string();
  8937. out <<
  8938. "Failed " << bothOrAll(totals.testCases.failed)
  8939. << pluralise(totals.testCases.failed, "test case") << ", "
  8940. "failed " << qualify_assertions_failed <<
  8941. pluralise(totals.assertions.failed, "assertion") << '.';
  8942. } else if (totals.assertions.total() == 0) {
  8943. out <<
  8944. "Passed " << bothOrAll(totals.testCases.total())
  8945. << pluralise(totals.testCases.total(), "test case")
  8946. << " (no assertions).";
  8947. } else if (totals.assertions.failed) {
  8948. Colour colour(Colour::ResultError);
  8949. out <<
  8950. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  8951. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  8952. } else {
  8953. Colour colour(Colour::ResultSuccess);
  8954. out <<
  8955. "Passed " << bothOrAll(totals.testCases.passed)
  8956. << pluralise(totals.testCases.passed, "test case") <<
  8957. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  8958. }
  8959. }
  8960. // Implementation of CompactReporter formatting
  8961. class AssertionPrinter {
  8962. public:
  8963. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  8964. AssertionPrinter(AssertionPrinter const&) = delete;
  8965. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  8966. : stream(_stream)
  8967. , result(_stats.assertionResult)
  8968. , messages(_stats.infoMessages)
  8969. , itMessage(_stats.infoMessages.begin())
  8970. , printInfoMessages(_printInfoMessages) {}
  8971. void print() {
  8972. printSourceInfo();
  8973. itMessage = messages.begin();
  8974. switch (result.getResultType()) {
  8975. case ResultWas::Ok:
  8976. printResultType(Colour::ResultSuccess, passedString());
  8977. printOriginalExpression();
  8978. printReconstructedExpression();
  8979. if (!result.hasExpression())
  8980. printRemainingMessages(Colour::None);
  8981. else
  8982. printRemainingMessages();
  8983. break;
  8984. case ResultWas::ExpressionFailed:
  8985. if (result.isOk())
  8986. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  8987. else
  8988. printResultType(Colour::Error, failedString());
  8989. printOriginalExpression();
  8990. printReconstructedExpression();
  8991. printRemainingMessages();
  8992. break;
  8993. case ResultWas::ThrewException:
  8994. printResultType(Colour::Error, failedString());
  8995. printIssue("unexpected exception with message:");
  8996. printMessage();
  8997. printExpressionWas();
  8998. printRemainingMessages();
  8999. break;
  9000. case ResultWas::FatalErrorCondition:
  9001. printResultType(Colour::Error, failedString());
  9002. printIssue("fatal error condition with message:");
  9003. printMessage();
  9004. printExpressionWas();
  9005. printRemainingMessages();
  9006. break;
  9007. case ResultWas::DidntThrowException:
  9008. printResultType(Colour::Error, failedString());
  9009. printIssue("expected exception, got none");
  9010. printExpressionWas();
  9011. printRemainingMessages();
  9012. break;
  9013. case ResultWas::Info:
  9014. printResultType(Colour::None, "info");
  9015. printMessage();
  9016. printRemainingMessages();
  9017. break;
  9018. case ResultWas::Warning:
  9019. printResultType(Colour::None, "warning");
  9020. printMessage();
  9021. printRemainingMessages();
  9022. break;
  9023. case ResultWas::ExplicitFailure:
  9024. printResultType(Colour::Error, failedString());
  9025. printIssue("explicitly");
  9026. printRemainingMessages(Colour::None);
  9027. break;
  9028. // These cases are here to prevent compiler warnings
  9029. case ResultWas::Unknown:
  9030. case ResultWas::FailureBit:
  9031. case ResultWas::Exception:
  9032. printResultType(Colour::Error, "** internal error **");
  9033. break;
  9034. }
  9035. }
  9036. private:
  9037. void printSourceInfo() const {
  9038. Colour colourGuard(Colour::FileName);
  9039. stream << result.getSourceInfo() << ':';
  9040. }
  9041. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  9042. if (!passOrFail.empty()) {
  9043. {
  9044. Colour colourGuard(colour);
  9045. stream << ' ' << passOrFail;
  9046. }
  9047. stream << ':';
  9048. }
  9049. }
  9050. void printIssue(std::string const& issue) const {
  9051. stream << ' ' << issue;
  9052. }
  9053. void printExpressionWas() {
  9054. if (result.hasExpression()) {
  9055. stream << ';';
  9056. {
  9057. Colour colour(dimColour());
  9058. stream << " expression was:";
  9059. }
  9060. printOriginalExpression();
  9061. }
  9062. }
  9063. void printOriginalExpression() const {
  9064. if (result.hasExpression()) {
  9065. stream << ' ' << result.getExpression();
  9066. }
  9067. }
  9068. void printReconstructedExpression() const {
  9069. if (result.hasExpandedExpression()) {
  9070. {
  9071. Colour colour(dimColour());
  9072. stream << " for: ";
  9073. }
  9074. stream << result.getExpandedExpression();
  9075. }
  9076. }
  9077. void printMessage() {
  9078. if (itMessage != messages.end()) {
  9079. stream << " '" << itMessage->message << '\'';
  9080. ++itMessage;
  9081. }
  9082. }
  9083. void printRemainingMessages(Colour::Code colour = dimColour()) {
  9084. if (itMessage == messages.end())
  9085. return;
  9086. // using messages.end() directly yields (or auto) compilation error:
  9087. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  9088. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  9089. {
  9090. Colour colourGuard(colour);
  9091. stream << " with " << pluralise(N, "message") << ':';
  9092. }
  9093. for (; itMessage != itEnd; ) {
  9094. // If this assertion is a warning ignore any INFO messages
  9095. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  9096. stream << " '" << itMessage->message << '\'';
  9097. if (++itMessage != itEnd) {
  9098. Colour colourGuard(dimColour());
  9099. stream << " and";
  9100. }
  9101. }
  9102. }
  9103. }
  9104. private:
  9105. std::ostream& stream;
  9106. AssertionResult const& result;
  9107. std::vector<MessageInfo> messages;
  9108. std::vector<MessageInfo>::const_iterator itMessage;
  9109. bool printInfoMessages;
  9110. };
  9111. } // anon namespace
  9112. std::string CompactReporter::getDescription() {
  9113. return "Reports test results on a single line, suitable for IDEs";
  9114. }
  9115. ReporterPreferences CompactReporter::getPreferences() const {
  9116. ReporterPreferences prefs;
  9117. prefs.shouldRedirectStdOut = false;
  9118. return prefs;
  9119. }
  9120. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  9121. stream << "No test cases matched '" << spec << '\'' << std::endl;
  9122. }
  9123. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  9124. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  9125. AssertionResult const& result = _assertionStats.assertionResult;
  9126. bool printInfoMessages = true;
  9127. // Drop out if result was successful and we're not printing those
  9128. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  9129. if( result.getResultType() != ResultWas::Warning )
  9130. return false;
  9131. printInfoMessages = false;
  9132. }
  9133. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  9134. printer.print();
  9135. stream << std::endl;
  9136. return true;
  9137. }
  9138. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  9139. if (m_config->showDurations() == ShowDurations::Always) {
  9140. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  9141. }
  9142. }
  9143. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  9144. printTotals( stream, _testRunStats.totals );
  9145. stream << '\n' << std::endl;
  9146. StreamingReporterBase::testRunEnded( _testRunStats );
  9147. }
  9148. CompactReporter::~CompactReporter() {}
  9149. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  9150. } // end namespace Catch
  9151. // end catch_reporter_compact.cpp
  9152. // start catch_reporter_console.cpp
  9153. #include <cfloat>
  9154. #include <cstdio>
  9155. #if defined(_MSC_VER)
  9156. #pragma warning(push)
  9157. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  9158. // Note that 4062 (not all labels are handled
  9159. // and default is missing) is enabled
  9160. #endif
  9161. namespace Catch {
  9162. namespace {
  9163. // Formatter impl for ConsoleReporter
  9164. class ConsoleAssertionPrinter {
  9165. public:
  9166. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  9167. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  9168. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  9169. : stream(_stream),
  9170. stats(_stats),
  9171. result(_stats.assertionResult),
  9172. colour(Colour::None),
  9173. message(result.getMessage()),
  9174. messages(_stats.infoMessages),
  9175. printInfoMessages(_printInfoMessages) {
  9176. switch (result.getResultType()) {
  9177. case ResultWas::Ok:
  9178. colour = Colour::Success;
  9179. passOrFail = "PASSED";
  9180. //if( result.hasMessage() )
  9181. if (_stats.infoMessages.size() == 1)
  9182. messageLabel = "with message";
  9183. if (_stats.infoMessages.size() > 1)
  9184. messageLabel = "with messages";
  9185. break;
  9186. case ResultWas::ExpressionFailed:
  9187. if (result.isOk()) {
  9188. colour = Colour::Success;
  9189. passOrFail = "FAILED - but was ok";
  9190. } else {
  9191. colour = Colour::Error;
  9192. passOrFail = "FAILED";
  9193. }
  9194. if (_stats.infoMessages.size() == 1)
  9195. messageLabel = "with message";
  9196. if (_stats.infoMessages.size() > 1)
  9197. messageLabel = "with messages";
  9198. break;
  9199. case ResultWas::ThrewException:
  9200. colour = Colour::Error;
  9201. passOrFail = "FAILED";
  9202. messageLabel = "due to unexpected exception with ";
  9203. if (_stats.infoMessages.size() == 1)
  9204. messageLabel += "message";
  9205. if (_stats.infoMessages.size() > 1)
  9206. messageLabel += "messages";
  9207. break;
  9208. case ResultWas::FatalErrorCondition:
  9209. colour = Colour::Error;
  9210. passOrFail = "FAILED";
  9211. messageLabel = "due to a fatal error condition";
  9212. break;
  9213. case ResultWas::DidntThrowException:
  9214. colour = Colour::Error;
  9215. passOrFail = "FAILED";
  9216. messageLabel = "because no exception was thrown where one was expected";
  9217. break;
  9218. case ResultWas::Info:
  9219. messageLabel = "info";
  9220. break;
  9221. case ResultWas::Warning:
  9222. messageLabel = "warning";
  9223. break;
  9224. case ResultWas::ExplicitFailure:
  9225. passOrFail = "FAILED";
  9226. colour = Colour::Error;
  9227. if (_stats.infoMessages.size() == 1)
  9228. messageLabel = "explicitly with message";
  9229. if (_stats.infoMessages.size() > 1)
  9230. messageLabel = "explicitly with messages";
  9231. break;
  9232. // These cases are here to prevent compiler warnings
  9233. case ResultWas::Unknown:
  9234. case ResultWas::FailureBit:
  9235. case ResultWas::Exception:
  9236. passOrFail = "** internal error **";
  9237. colour = Colour::Error;
  9238. break;
  9239. }
  9240. }
  9241. void print() const {
  9242. printSourceInfo();
  9243. if (stats.totals.assertions.total() > 0) {
  9244. if (result.isOk())
  9245. stream << '\n';
  9246. printResultType();
  9247. printOriginalExpression();
  9248. printReconstructedExpression();
  9249. } else {
  9250. stream << '\n';
  9251. }
  9252. printMessage();
  9253. }
  9254. private:
  9255. void printResultType() const {
  9256. if (!passOrFail.empty()) {
  9257. Colour colourGuard(colour);
  9258. stream << passOrFail << ":\n";
  9259. }
  9260. }
  9261. void printOriginalExpression() const {
  9262. if (result.hasExpression()) {
  9263. Colour colourGuard(Colour::OriginalExpression);
  9264. stream << " ";
  9265. stream << result.getExpressionInMacro();
  9266. stream << '\n';
  9267. }
  9268. }
  9269. void printReconstructedExpression() const {
  9270. if (result.hasExpandedExpression()) {
  9271. stream << "with expansion:\n";
  9272. Colour colourGuard(Colour::ReconstructedExpression);
  9273. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  9274. }
  9275. }
  9276. void printMessage() const {
  9277. if (!messageLabel.empty())
  9278. stream << messageLabel << ':' << '\n';
  9279. for (auto const& msg : messages) {
  9280. // If this assertion is a warning ignore any INFO messages
  9281. if (printInfoMessages || msg.type != ResultWas::Info)
  9282. stream << Column(msg.message).indent(2) << '\n';
  9283. }
  9284. }
  9285. void printSourceInfo() const {
  9286. Colour colourGuard(Colour::FileName);
  9287. stream << result.getSourceInfo() << ": ";
  9288. }
  9289. std::ostream& stream;
  9290. AssertionStats const& stats;
  9291. AssertionResult const& result;
  9292. Colour::Code colour;
  9293. std::string passOrFail;
  9294. std::string messageLabel;
  9295. std::string message;
  9296. std::vector<MessageInfo> messages;
  9297. bool printInfoMessages;
  9298. };
  9299. std::size_t makeRatio(std::size_t number, std::size_t total) {
  9300. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  9301. return (ratio == 0 && number > 0) ? 1 : ratio;
  9302. }
  9303. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  9304. if (i > j && i > k)
  9305. return i;
  9306. else if (j > k)
  9307. return j;
  9308. else
  9309. return k;
  9310. }
  9311. struct ColumnInfo {
  9312. enum Justification { Left, Right };
  9313. std::string name;
  9314. int width;
  9315. Justification justification;
  9316. };
  9317. struct ColumnBreak {};
  9318. struct RowBreak {};
  9319. class Duration {
  9320. enum class Unit {
  9321. Auto,
  9322. Nanoseconds,
  9323. Microseconds,
  9324. Milliseconds,
  9325. Seconds,
  9326. Minutes
  9327. };
  9328. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  9329. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  9330. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  9331. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  9332. uint64_t m_inNanoseconds;
  9333. Unit m_units;
  9334. public:
  9335. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  9336. : m_inNanoseconds(inNanoseconds),
  9337. m_units(units) {
  9338. if (m_units == Unit::Auto) {
  9339. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  9340. m_units = Unit::Nanoseconds;
  9341. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  9342. m_units = Unit::Microseconds;
  9343. else if (m_inNanoseconds < s_nanosecondsInASecond)
  9344. m_units = Unit::Milliseconds;
  9345. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  9346. m_units = Unit::Seconds;
  9347. else
  9348. m_units = Unit::Minutes;
  9349. }
  9350. }
  9351. auto value() const -> double {
  9352. switch (m_units) {
  9353. case Unit::Microseconds:
  9354. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  9355. case Unit::Milliseconds:
  9356. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  9357. case Unit::Seconds:
  9358. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  9359. case Unit::Minutes:
  9360. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  9361. default:
  9362. return static_cast<double>(m_inNanoseconds);
  9363. }
  9364. }
  9365. auto unitsAsString() const -> std::string {
  9366. switch (m_units) {
  9367. case Unit::Nanoseconds:
  9368. return "ns";
  9369. case Unit::Microseconds:
  9370. return "µs";
  9371. case Unit::Milliseconds:
  9372. return "ms";
  9373. case Unit::Seconds:
  9374. return "s";
  9375. case Unit::Minutes:
  9376. return "m";
  9377. default:
  9378. return "** internal error **";
  9379. }
  9380. }
  9381. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  9382. return os << duration.value() << " " << duration.unitsAsString();
  9383. }
  9384. };
  9385. } // end anon namespace
  9386. class TablePrinter {
  9387. std::ostream& m_os;
  9388. std::vector<ColumnInfo> m_columnInfos;
  9389. std::ostringstream m_oss;
  9390. int m_currentColumn = -1;
  9391. bool m_isOpen = false;
  9392. public:
  9393. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  9394. : m_os( os ),
  9395. m_columnInfos( std::move( columnInfos ) ) {}
  9396. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  9397. return m_columnInfos;
  9398. }
  9399. void open() {
  9400. if (!m_isOpen) {
  9401. m_isOpen = true;
  9402. *this << RowBreak();
  9403. for (auto const& info : m_columnInfos)
  9404. *this << info.name << ColumnBreak();
  9405. *this << RowBreak();
  9406. m_os << Catch::getLineOfChars<'-'>() << "\n";
  9407. }
  9408. }
  9409. void close() {
  9410. if (m_isOpen) {
  9411. *this << RowBreak();
  9412. m_os << std::endl;
  9413. m_isOpen = false;
  9414. }
  9415. }
  9416. template<typename T>
  9417. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  9418. tp.m_oss << value;
  9419. return tp;
  9420. }
  9421. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  9422. auto colStr = tp.m_oss.str();
  9423. // This takes account of utf8 encodings
  9424. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  9425. tp.m_oss.str("");
  9426. tp.open();
  9427. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  9428. tp.m_currentColumn = -1;
  9429. tp.m_os << "\n";
  9430. }
  9431. tp.m_currentColumn++;
  9432. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  9433. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  9434. ? std::string(colInfo.width - (strSize + 2), ' ')
  9435. : std::string();
  9436. if (colInfo.justification == ColumnInfo::Left)
  9437. tp.m_os << colStr << padding << " ";
  9438. else
  9439. tp.m_os << padding << colStr << " ";
  9440. return tp;
  9441. }
  9442. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  9443. if (tp.m_currentColumn > 0) {
  9444. tp.m_os << "\n";
  9445. tp.m_currentColumn = -1;
  9446. }
  9447. return tp;
  9448. }
  9449. };
  9450. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  9451. : StreamingReporterBase(config),
  9452. m_tablePrinter(new TablePrinter(config.stream(),
  9453. {
  9454. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  9455. { "iters", 8, ColumnInfo::Right },
  9456. { "elapsed ns", 14, ColumnInfo::Right },
  9457. { "average", 14, ColumnInfo::Right }
  9458. })) {}
  9459. ConsoleReporter::~ConsoleReporter() = default;
  9460. std::string ConsoleReporter::getDescription() {
  9461. return "Reports test results as plain lines of text";
  9462. }
  9463. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  9464. stream << "No test cases matched '" << spec << '\'' << std::endl;
  9465. }
  9466. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  9467. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  9468. AssertionResult const& result = _assertionStats.assertionResult;
  9469. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  9470. // Drop out if result was successful but we're not printing them.
  9471. if (!includeResults && result.getResultType() != ResultWas::Warning)
  9472. return false;
  9473. lazyPrint();
  9474. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  9475. printer.print();
  9476. stream << std::endl;
  9477. return true;
  9478. }
  9479. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  9480. m_headerPrinted = false;
  9481. StreamingReporterBase::sectionStarting(_sectionInfo);
  9482. }
  9483. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  9484. m_tablePrinter->close();
  9485. if (_sectionStats.missingAssertions) {
  9486. lazyPrint();
  9487. Colour colour(Colour::ResultError);
  9488. if (m_sectionStack.size() > 1)
  9489. stream << "\nNo assertions in section";
  9490. else
  9491. stream << "\nNo assertions in test case";
  9492. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  9493. }
  9494. if (m_config->showDurations() == ShowDurations::Always) {
  9495. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  9496. }
  9497. if (m_headerPrinted) {
  9498. m_headerPrinted = false;
  9499. }
  9500. StreamingReporterBase::sectionEnded(_sectionStats);
  9501. }
  9502. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  9503. lazyPrintWithoutClosingBenchmarkTable();
  9504. auto nameCol = Column( info.name ).width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) );
  9505. bool firstLine = true;
  9506. for (auto line : nameCol) {
  9507. if (!firstLine)
  9508. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  9509. else
  9510. firstLine = false;
  9511. (*m_tablePrinter) << line << ColumnBreak();
  9512. }
  9513. }
  9514. void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) {
  9515. Duration average(stats.elapsedTimeInNanoseconds / stats.iterations);
  9516. (*m_tablePrinter)
  9517. << stats.iterations << ColumnBreak()
  9518. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  9519. << average << ColumnBreak();
  9520. }
  9521. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  9522. m_tablePrinter->close();
  9523. StreamingReporterBase::testCaseEnded(_testCaseStats);
  9524. m_headerPrinted = false;
  9525. }
  9526. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  9527. if (currentGroupInfo.used) {
  9528. printSummaryDivider();
  9529. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  9530. printTotals(_testGroupStats.totals);
  9531. stream << '\n' << std::endl;
  9532. }
  9533. StreamingReporterBase::testGroupEnded(_testGroupStats);
  9534. }
  9535. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  9536. printTotalsDivider(_testRunStats.totals);
  9537. printTotals(_testRunStats.totals);
  9538. stream << std::endl;
  9539. StreamingReporterBase::testRunEnded(_testRunStats);
  9540. }
  9541. void ConsoleReporter::lazyPrint() {
  9542. m_tablePrinter->close();
  9543. lazyPrintWithoutClosingBenchmarkTable();
  9544. }
  9545. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  9546. if (!currentTestRunInfo.used)
  9547. lazyPrintRunInfo();
  9548. if (!currentGroupInfo.used)
  9549. lazyPrintGroupInfo();
  9550. if (!m_headerPrinted) {
  9551. printTestCaseAndSectionHeader();
  9552. m_headerPrinted = true;
  9553. }
  9554. }
  9555. void ConsoleReporter::lazyPrintRunInfo() {
  9556. stream << '\n' << getLineOfChars<'~'>() << '\n';
  9557. Colour colour(Colour::SecondaryText);
  9558. stream << currentTestRunInfo->name
  9559. << " is a Catch v" << libraryVersion() << " host application.\n"
  9560. << "Run with -? for options\n\n";
  9561. if (m_config->rngSeed() != 0)
  9562. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  9563. currentTestRunInfo.used = true;
  9564. }
  9565. void ConsoleReporter::lazyPrintGroupInfo() {
  9566. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  9567. printClosedHeader("Group: " + currentGroupInfo->name);
  9568. currentGroupInfo.used = true;
  9569. }
  9570. }
  9571. void ConsoleReporter::printTestCaseAndSectionHeader() {
  9572. assert(!m_sectionStack.empty());
  9573. printOpenHeader(currentTestCaseInfo->name);
  9574. if (m_sectionStack.size() > 1) {
  9575. Colour colourGuard(Colour::Headers);
  9576. auto
  9577. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  9578. itEnd = m_sectionStack.end();
  9579. for (; it != itEnd; ++it)
  9580. printHeaderString(it->name, 2);
  9581. }
  9582. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  9583. if (!lineInfo.empty()) {
  9584. stream << getLineOfChars<'-'>() << '\n';
  9585. Colour colourGuard(Colour::FileName);
  9586. stream << lineInfo << '\n';
  9587. }
  9588. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  9589. }
  9590. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  9591. printOpenHeader(_name);
  9592. stream << getLineOfChars<'.'>() << '\n';
  9593. }
  9594. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  9595. stream << getLineOfChars<'-'>() << '\n';
  9596. {
  9597. Colour colourGuard(Colour::Headers);
  9598. printHeaderString(_name);
  9599. }
  9600. }
  9601. // if string has a : in first line will set indent to follow it on
  9602. // subsequent lines
  9603. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  9604. std::size_t i = _string.find(": ");
  9605. if (i != std::string::npos)
  9606. i += 2;
  9607. else
  9608. i = 0;
  9609. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  9610. }
  9611. struct SummaryColumn {
  9612. SummaryColumn( std::string _label, Colour::Code _colour )
  9613. : label( std::move( _label ) ),
  9614. colour( _colour ) {}
  9615. SummaryColumn addRow( std::size_t count ) {
  9616. ReusableStringStream rss;
  9617. rss << count;
  9618. std::string row = rss.str();
  9619. for (auto& oldRow : rows) {
  9620. while (oldRow.size() < row.size())
  9621. oldRow = ' ' + oldRow;
  9622. while (oldRow.size() > row.size())
  9623. row = ' ' + row;
  9624. }
  9625. rows.push_back(row);
  9626. return *this;
  9627. }
  9628. std::string label;
  9629. Colour::Code colour;
  9630. std::vector<std::string> rows;
  9631. };
  9632. void ConsoleReporter::printTotals( Totals const& totals ) {
  9633. if (totals.testCases.total() == 0) {
  9634. stream << Colour(Colour::Warning) << "No tests ran\n";
  9635. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  9636. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  9637. stream << " ("
  9638. << pluralise(totals.assertions.passed, "assertion") << " in "
  9639. << pluralise(totals.testCases.passed, "test case") << ')'
  9640. << '\n';
  9641. } else {
  9642. std::vector<SummaryColumn> columns;
  9643. columns.push_back(SummaryColumn("", Colour::None)
  9644. .addRow(totals.testCases.total())
  9645. .addRow(totals.assertions.total()));
  9646. columns.push_back(SummaryColumn("passed", Colour::Success)
  9647. .addRow(totals.testCases.passed)
  9648. .addRow(totals.assertions.passed));
  9649. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  9650. .addRow(totals.testCases.failed)
  9651. .addRow(totals.assertions.failed));
  9652. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  9653. .addRow(totals.testCases.failedButOk)
  9654. .addRow(totals.assertions.failedButOk));
  9655. printSummaryRow("test cases", columns, 0);
  9656. printSummaryRow("assertions", columns, 1);
  9657. }
  9658. }
  9659. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  9660. for (auto col : cols) {
  9661. std::string value = col.rows[row];
  9662. if (col.label.empty()) {
  9663. stream << label << ": ";
  9664. if (value != "0")
  9665. stream << value;
  9666. else
  9667. stream << Colour(Colour::Warning) << "- none -";
  9668. } else if (value != "0") {
  9669. stream << Colour(Colour::LightGrey) << " | ";
  9670. stream << Colour(col.colour)
  9671. << value << ' ' << col.label;
  9672. }
  9673. }
  9674. stream << '\n';
  9675. }
  9676. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  9677. if (totals.testCases.total() > 0) {
  9678. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  9679. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  9680. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  9681. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  9682. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  9683. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  9684. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  9685. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  9686. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  9687. if (totals.testCases.allPassed())
  9688. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  9689. else
  9690. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  9691. } else {
  9692. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  9693. }
  9694. stream << '\n';
  9695. }
  9696. void ConsoleReporter::printSummaryDivider() {
  9697. stream << getLineOfChars<'-'>() << '\n';
  9698. }
  9699. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  9700. } // end namespace Catch
  9701. #if defined(_MSC_VER)
  9702. #pragma warning(pop)
  9703. #endif
  9704. // end catch_reporter_console.cpp
  9705. // start catch_reporter_junit.cpp
  9706. #include <assert.h>
  9707. #include <sstream>
  9708. #include <ctime>
  9709. #include <algorithm>
  9710. namespace Catch {
  9711. namespace {
  9712. std::string getCurrentTimestamp() {
  9713. // Beware, this is not reentrant because of backward compatibility issues
  9714. // Also, UTC only, again because of backward compatibility (%z is C++11)
  9715. time_t rawtime;
  9716. std::time(&rawtime);
  9717. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  9718. #ifdef _MSC_VER
  9719. std::tm timeInfo = {};
  9720. gmtime_s(&timeInfo, &rawtime);
  9721. #else
  9722. std::tm* timeInfo;
  9723. timeInfo = std::gmtime(&rawtime);
  9724. #endif
  9725. char timeStamp[timeStampSize];
  9726. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  9727. #ifdef _MSC_VER
  9728. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  9729. #else
  9730. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  9731. #endif
  9732. return std::string(timeStamp);
  9733. }
  9734. std::string fileNameTag(const std::vector<std::string> &tags) {
  9735. auto it = std::find_if(begin(tags),
  9736. end(tags),
  9737. [] (std::string const& tag) {return tag.front() == '#'; });
  9738. if (it != tags.end())
  9739. return it->substr(1);
  9740. return std::string();
  9741. }
  9742. } // anonymous namespace
  9743. JunitReporter::JunitReporter( ReporterConfig const& _config )
  9744. : CumulativeReporterBase( _config ),
  9745. xml( _config.stream() )
  9746. {
  9747. m_reporterPrefs.shouldRedirectStdOut = true;
  9748. }
  9749. JunitReporter::~JunitReporter() {}
  9750. std::string JunitReporter::getDescription() {
  9751. return "Reports test results in an XML format that looks like Ant's junitreport target";
  9752. }
  9753. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  9754. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  9755. CumulativeReporterBase::testRunStarting( runInfo );
  9756. xml.startElement( "testsuites" );
  9757. }
  9758. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  9759. suiteTimer.start();
  9760. stdOutForSuite.clear();
  9761. stdErrForSuite.clear();
  9762. unexpectedExceptions = 0;
  9763. CumulativeReporterBase::testGroupStarting( groupInfo );
  9764. }
  9765. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  9766. m_okToFail = testCaseInfo.okToFail();
  9767. }
  9768. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  9769. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  9770. unexpectedExceptions++;
  9771. return CumulativeReporterBase::assertionEnded( assertionStats );
  9772. }
  9773. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  9774. stdOutForSuite += testCaseStats.stdOut;
  9775. stdErrForSuite += testCaseStats.stdErr;
  9776. CumulativeReporterBase::testCaseEnded( testCaseStats );
  9777. }
  9778. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  9779. double suiteTime = suiteTimer.getElapsedSeconds();
  9780. CumulativeReporterBase::testGroupEnded( testGroupStats );
  9781. writeGroup( *m_testGroups.back(), suiteTime );
  9782. }
  9783. void JunitReporter::testRunEndedCumulative() {
  9784. xml.endElement();
  9785. }
  9786. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  9787. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  9788. TestGroupStats const& stats = groupNode.value;
  9789. xml.writeAttribute( "name", stats.groupInfo.name );
  9790. xml.writeAttribute( "errors", unexpectedExceptions );
  9791. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  9792. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  9793. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  9794. if( m_config->showDurations() == ShowDurations::Never )
  9795. xml.writeAttribute( "time", "" );
  9796. else
  9797. xml.writeAttribute( "time", suiteTime );
  9798. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  9799. // Write test cases
  9800. for( auto const& child : groupNode.children )
  9801. writeTestCase( *child );
  9802. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  9803. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  9804. }
  9805. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  9806. TestCaseStats const& stats = testCaseNode.value;
  9807. // All test cases have exactly one section - which represents the
  9808. // test case itself. That section may have 0-n nested sections
  9809. assert( testCaseNode.children.size() == 1 );
  9810. SectionNode const& rootSection = *testCaseNode.children.front();
  9811. std::string className = stats.testInfo.className;
  9812. if( className.empty() ) {
  9813. className = fileNameTag(stats.testInfo.tags);
  9814. if ( className.empty() )
  9815. className = "global";
  9816. }
  9817. if ( !m_config->name().empty() )
  9818. className = m_config->name() + "." + className;
  9819. writeSection( className, "", rootSection );
  9820. }
  9821. void JunitReporter::writeSection( std::string const& className,
  9822. std::string const& rootName,
  9823. SectionNode const& sectionNode ) {
  9824. std::string name = trim( sectionNode.stats.sectionInfo.name );
  9825. if( !rootName.empty() )
  9826. name = rootName + '/' + name;
  9827. if( !sectionNode.assertions.empty() ||
  9828. !sectionNode.stdOut.empty() ||
  9829. !sectionNode.stdErr.empty() ) {
  9830. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  9831. if( className.empty() ) {
  9832. xml.writeAttribute( "classname", name );
  9833. xml.writeAttribute( "name", "root" );
  9834. }
  9835. else {
  9836. xml.writeAttribute( "classname", className );
  9837. xml.writeAttribute( "name", name );
  9838. }
  9839. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  9840. writeAssertions( sectionNode );
  9841. if( !sectionNode.stdOut.empty() )
  9842. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  9843. if( !sectionNode.stdErr.empty() )
  9844. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  9845. }
  9846. for( auto const& childNode : sectionNode.childSections )
  9847. if( className.empty() )
  9848. writeSection( name, "", *childNode );
  9849. else
  9850. writeSection( className, name, *childNode );
  9851. }
  9852. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  9853. for( auto const& assertion : sectionNode.assertions )
  9854. writeAssertion( assertion );
  9855. }
  9856. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  9857. AssertionResult const& result = stats.assertionResult;
  9858. if( !result.isOk() ) {
  9859. std::string elementName;
  9860. switch( result.getResultType() ) {
  9861. case ResultWas::ThrewException:
  9862. case ResultWas::FatalErrorCondition:
  9863. elementName = "error";
  9864. break;
  9865. case ResultWas::ExplicitFailure:
  9866. elementName = "failure";
  9867. break;
  9868. case ResultWas::ExpressionFailed:
  9869. elementName = "failure";
  9870. break;
  9871. case ResultWas::DidntThrowException:
  9872. elementName = "failure";
  9873. break;
  9874. // We should never see these here:
  9875. case ResultWas::Info:
  9876. case ResultWas::Warning:
  9877. case ResultWas::Ok:
  9878. case ResultWas::Unknown:
  9879. case ResultWas::FailureBit:
  9880. case ResultWas::Exception:
  9881. elementName = "internalError";
  9882. break;
  9883. }
  9884. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  9885. xml.writeAttribute( "message", result.getExpandedExpression() );
  9886. xml.writeAttribute( "type", result.getTestMacroName() );
  9887. ReusableStringStream rss;
  9888. if( !result.getMessage().empty() )
  9889. rss << result.getMessage() << '\n';
  9890. for( auto const& msg : stats.infoMessages )
  9891. if( msg.type == ResultWas::Info )
  9892. rss << msg.message << '\n';
  9893. rss << "at " << result.getSourceInfo();
  9894. xml.writeText( rss.str(), false );
  9895. }
  9896. }
  9897. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  9898. } // end namespace Catch
  9899. // end catch_reporter_junit.cpp
  9900. // start catch_reporter_multi.cpp
  9901. namespace Catch {
  9902. void MultipleReporters::add( IStreamingReporterPtr&& reporter ) {
  9903. m_reporters.push_back( std::move( reporter ) );
  9904. }
  9905. ReporterPreferences MultipleReporters::getPreferences() const {
  9906. return m_reporters[0]->getPreferences();
  9907. }
  9908. std::set<Verbosity> MultipleReporters::getSupportedVerbosities() {
  9909. return std::set<Verbosity>{ };
  9910. }
  9911. void MultipleReporters::noMatchingTestCases( std::string const& spec ) {
  9912. for( auto const& reporter : m_reporters )
  9913. reporter->noMatchingTestCases( spec );
  9914. }
  9915. void MultipleReporters::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  9916. for( auto const& reporter : m_reporters )
  9917. reporter->benchmarkStarting( benchmarkInfo );
  9918. }
  9919. void MultipleReporters::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
  9920. for( auto const& reporter : m_reporters )
  9921. reporter->benchmarkEnded( benchmarkStats );
  9922. }
  9923. void MultipleReporters::testRunStarting( TestRunInfo const& testRunInfo ) {
  9924. for( auto const& reporter : m_reporters )
  9925. reporter->testRunStarting( testRunInfo );
  9926. }
  9927. void MultipleReporters::testGroupStarting( GroupInfo const& groupInfo ) {
  9928. for( auto const& reporter : m_reporters )
  9929. reporter->testGroupStarting( groupInfo );
  9930. }
  9931. void MultipleReporters::testCaseStarting( TestCaseInfo const& testInfo ) {
  9932. for( auto const& reporter : m_reporters )
  9933. reporter->testCaseStarting( testInfo );
  9934. }
  9935. void MultipleReporters::sectionStarting( SectionInfo const& sectionInfo ) {
  9936. for( auto const& reporter : m_reporters )
  9937. reporter->sectionStarting( sectionInfo );
  9938. }
  9939. void MultipleReporters::assertionStarting( AssertionInfo const& assertionInfo ) {
  9940. for( auto const& reporter : m_reporters )
  9941. reporter->assertionStarting( assertionInfo );
  9942. }
  9943. // The return value indicates if the messages buffer should be cleared:
  9944. bool MultipleReporters::assertionEnded( AssertionStats const& assertionStats ) {
  9945. bool clearBuffer = false;
  9946. for( auto const& reporter : m_reporters )
  9947. clearBuffer |= reporter->assertionEnded( assertionStats );
  9948. return clearBuffer;
  9949. }
  9950. void MultipleReporters::sectionEnded( SectionStats const& sectionStats ) {
  9951. for( auto const& reporter : m_reporters )
  9952. reporter->sectionEnded( sectionStats );
  9953. }
  9954. void MultipleReporters::testCaseEnded( TestCaseStats const& testCaseStats ) {
  9955. for( auto const& reporter : m_reporters )
  9956. reporter->testCaseEnded( testCaseStats );
  9957. }
  9958. void MultipleReporters::testGroupEnded( TestGroupStats const& testGroupStats ) {
  9959. for( auto const& reporter : m_reporters )
  9960. reporter->testGroupEnded( testGroupStats );
  9961. }
  9962. void MultipleReporters::testRunEnded( TestRunStats const& testRunStats ) {
  9963. for( auto const& reporter : m_reporters )
  9964. reporter->testRunEnded( testRunStats );
  9965. }
  9966. void MultipleReporters::skipTest( TestCaseInfo const& testInfo ) {
  9967. for( auto const& reporter : m_reporters )
  9968. reporter->skipTest( testInfo );
  9969. }
  9970. bool MultipleReporters::isMulti() const {
  9971. return true;
  9972. }
  9973. } // end namespace Catch
  9974. // end catch_reporter_multi.cpp
  9975. // start catch_reporter_xml.cpp
  9976. #if defined(_MSC_VER)
  9977. #pragma warning(push)
  9978. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  9979. // Note that 4062 (not all labels are handled
  9980. // and default is missing) is enabled
  9981. #endif
  9982. namespace Catch {
  9983. XmlReporter::XmlReporter( ReporterConfig const& _config )
  9984. : StreamingReporterBase( _config ),
  9985. m_xml(_config.stream())
  9986. {
  9987. m_reporterPrefs.shouldRedirectStdOut = true;
  9988. }
  9989. XmlReporter::~XmlReporter() = default;
  9990. std::string XmlReporter::getDescription() {
  9991. return "Reports test results as an XML document";
  9992. }
  9993. std::string XmlReporter::getStylesheetRef() const {
  9994. return std::string();
  9995. }
  9996. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  9997. m_xml
  9998. .writeAttribute( "filename", sourceInfo.file )
  9999. .writeAttribute( "line", sourceInfo.line );
  10000. }
  10001. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  10002. StreamingReporterBase::noMatchingTestCases( s );
  10003. }
  10004. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  10005. StreamingReporterBase::testRunStarting( testInfo );
  10006. std::string stylesheetRef = getStylesheetRef();
  10007. if( !stylesheetRef.empty() )
  10008. m_xml.writeStylesheetRef( stylesheetRef );
  10009. m_xml.startElement( "Catch" );
  10010. if( !m_config->name().empty() )
  10011. m_xml.writeAttribute( "name", m_config->name() );
  10012. }
  10013. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  10014. StreamingReporterBase::testGroupStarting( groupInfo );
  10015. m_xml.startElement( "Group" )
  10016. .writeAttribute( "name", groupInfo.name );
  10017. }
  10018. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  10019. StreamingReporterBase::testCaseStarting(testInfo);
  10020. m_xml.startElement( "TestCase" )
  10021. .writeAttribute( "name", trim( testInfo.name ) )
  10022. .writeAttribute( "description", testInfo.description )
  10023. .writeAttribute( "tags", testInfo.tagsAsString() );
  10024. writeSourceInfo( testInfo.lineInfo );
  10025. if ( m_config->showDurations() == ShowDurations::Always )
  10026. m_testCaseTimer.start();
  10027. m_xml.ensureTagClosed();
  10028. }
  10029. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  10030. StreamingReporterBase::sectionStarting( sectionInfo );
  10031. if( m_sectionDepth++ > 0 ) {
  10032. m_xml.startElement( "Section" )
  10033. .writeAttribute( "name", trim( sectionInfo.name ) )
  10034. .writeAttribute( "description", sectionInfo.description );
  10035. writeSourceInfo( sectionInfo.lineInfo );
  10036. m_xml.ensureTagClosed();
  10037. }
  10038. }
  10039. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  10040. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10041. AssertionResult const& result = assertionStats.assertionResult;
  10042. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  10043. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  10044. // Print any info messages in <Info> tags.
  10045. for( auto const& msg : assertionStats.infoMessages ) {
  10046. if( msg.type == ResultWas::Info && includeResults ) {
  10047. m_xml.scopedElement( "Info" )
  10048. .writeText( msg.message );
  10049. } else if ( msg.type == ResultWas::Warning ) {
  10050. m_xml.scopedElement( "Warning" )
  10051. .writeText( msg.message );
  10052. }
  10053. }
  10054. }
  10055. // Drop out if result was successful but we're not printing them.
  10056. if( !includeResults && result.getResultType() != ResultWas::Warning )
  10057. return true;
  10058. // Print the expression if there is one.
  10059. if( result.hasExpression() ) {
  10060. m_xml.startElement( "Expression" )
  10061. .writeAttribute( "success", result.succeeded() )
  10062. .writeAttribute( "type", result.getTestMacroName() );
  10063. writeSourceInfo( result.getSourceInfo() );
  10064. m_xml.scopedElement( "Original" )
  10065. .writeText( result.getExpression() );
  10066. m_xml.scopedElement( "Expanded" )
  10067. .writeText( result.getExpandedExpression() );
  10068. }
  10069. // And... Print a result applicable to each result type.
  10070. switch( result.getResultType() ) {
  10071. case ResultWas::ThrewException:
  10072. m_xml.startElement( "Exception" );
  10073. writeSourceInfo( result.getSourceInfo() );
  10074. m_xml.writeText( result.getMessage() );
  10075. m_xml.endElement();
  10076. break;
  10077. case ResultWas::FatalErrorCondition:
  10078. m_xml.startElement( "FatalErrorCondition" );
  10079. writeSourceInfo( result.getSourceInfo() );
  10080. m_xml.writeText( result.getMessage() );
  10081. m_xml.endElement();
  10082. break;
  10083. case ResultWas::Info:
  10084. m_xml.scopedElement( "Info" )
  10085. .writeText( result.getMessage() );
  10086. break;
  10087. case ResultWas::Warning:
  10088. // Warning will already have been written
  10089. break;
  10090. case ResultWas::ExplicitFailure:
  10091. m_xml.startElement( "Failure" );
  10092. writeSourceInfo( result.getSourceInfo() );
  10093. m_xml.writeText( result.getMessage() );
  10094. m_xml.endElement();
  10095. break;
  10096. default:
  10097. break;
  10098. }
  10099. if( result.hasExpression() )
  10100. m_xml.endElement();
  10101. return true;
  10102. }
  10103. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  10104. StreamingReporterBase::sectionEnded( sectionStats );
  10105. if( --m_sectionDepth > 0 ) {
  10106. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  10107. e.writeAttribute( "successes", sectionStats.assertions.passed );
  10108. e.writeAttribute( "failures", sectionStats.assertions.failed );
  10109. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  10110. if ( m_config->showDurations() == ShowDurations::Always )
  10111. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  10112. m_xml.endElement();
  10113. }
  10114. }
  10115. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10116. StreamingReporterBase::testCaseEnded( testCaseStats );
  10117. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  10118. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  10119. if ( m_config->showDurations() == ShowDurations::Always )
  10120. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  10121. if( !testCaseStats.stdOut.empty() )
  10122. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  10123. if( !testCaseStats.stdErr.empty() )
  10124. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  10125. m_xml.endElement();
  10126. }
  10127. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10128. StreamingReporterBase::testGroupEnded( testGroupStats );
  10129. // TODO: Check testGroupStats.aborting and act accordingly.
  10130. m_xml.scopedElement( "OverallResults" )
  10131. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  10132. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  10133. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  10134. m_xml.endElement();
  10135. }
  10136. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  10137. StreamingReporterBase::testRunEnded( testRunStats );
  10138. m_xml.scopedElement( "OverallResults" )
  10139. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  10140. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  10141. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  10142. m_xml.endElement();
  10143. }
  10144. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  10145. } // end namespace Catch
  10146. #if defined(_MSC_VER)
  10147. #pragma warning(pop)
  10148. #endif
  10149. // end catch_reporter_xml.cpp
  10150. namespace Catch {
  10151. LeakDetector leakDetector;
  10152. }
  10153. #ifdef __clang__
  10154. #pragma clang diagnostic pop
  10155. #endif
  10156. // end catch_impl.hpp
  10157. #endif
  10158. #ifdef CATCH_CONFIG_MAIN
  10159. // start catch_default_main.hpp
  10160. #ifndef __OBJC__
  10161. #if defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  10162. // Standard C/C++ Win32 Unicode wmain entry point
  10163. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  10164. #else
  10165. // Standard C/C++ main entry point
  10166. int main (int argc, char * argv[]) {
  10167. #endif
  10168. return Catch::Session().run( argc, argv );
  10169. }
  10170. #else // __OBJC__
  10171. // Objective-C entry point
  10172. int main (int argc, char * const argv[]) {
  10173. #if !CATCH_ARC_ENABLED
  10174. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  10175. #endif
  10176. Catch::registerTestMethods();
  10177. int result = Catch::Session().run( argc, (char**)argv );
  10178. #if !CATCH_ARC_ENABLED
  10179. [pool drain];
  10180. #endif
  10181. return result;
  10182. }
  10183. #endif // __OBJC__
  10184. // end catch_default_main.hpp
  10185. #endif
  10186. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  10187. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  10188. # undef CLARA_CONFIG_MAIN
  10189. #endif
  10190. #if !defined(CATCH_CONFIG_DISABLE)
  10191. //////
  10192. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  10193. #ifdef CATCH_CONFIG_PREFIX_ALL
  10194. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10195. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10196. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", __VA_ARGS__ )
  10197. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  10198. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  10199. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10200. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  10201. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  10202. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10203. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10204. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10205. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10206. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10207. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  10208. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", __VA_ARGS__ )
  10209. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  10210. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10211. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10212. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10213. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10214. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10215. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10216. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  10217. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  10218. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10219. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  10220. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  10221. #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  10222. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  10223. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  10224. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  10225. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  10226. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  10227. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10228. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10229. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10230. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  10231. // "BDD-style" convenience wrappers
  10232. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  10233. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  10234. #define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( "Given: ") + desc )
  10235. #define CATCH_WHEN( desc ) CATCH_SECTION( std::string( " When: ") + desc )
  10236. #define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  10237. #define CATCH_THEN( desc ) CATCH_SECTION( std::string( " Then: ") + desc )
  10238. #define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  10239. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  10240. #else
  10241. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10242. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10243. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10244. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  10245. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  10246. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10247. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  10248. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10249. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10250. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10251. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10252. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10253. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10254. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  10255. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10256. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  10257. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10258. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10259. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10260. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10261. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10262. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10263. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  10264. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  10265. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10266. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  10267. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  10268. #define CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  10269. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  10270. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  10271. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  10272. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  10273. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  10274. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10275. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10276. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10277. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  10278. #endif
  10279. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  10280. // "BDD-style" convenience wrappers
  10281. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  10282. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  10283. #define GIVEN( desc ) SECTION( std::string(" Given: ") + desc )
  10284. #define WHEN( desc ) SECTION( std::string(" When: ") + desc )
  10285. #define AND_WHEN( desc ) SECTION( std::string("And when: ") + desc )
  10286. #define THEN( desc ) SECTION( std::string(" Then: ") + desc )
  10287. #define AND_THEN( desc ) SECTION( std::string(" And: ") + desc )
  10288. using Catch::Detail::Approx;
  10289. #else
  10290. //////
  10291. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  10292. #ifdef CATCH_CONFIG_PREFIX_ALL
  10293. #define CATCH_REQUIRE( ... ) (void)(0)
  10294. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  10295. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  10296. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  10297. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  10298. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10299. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10300. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  10301. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  10302. #define CATCH_CHECK( ... ) (void)(0)
  10303. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  10304. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  10305. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  10306. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  10307. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  10308. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  10309. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  10310. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10311. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10312. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10313. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  10314. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10315. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  10316. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  10317. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10318. #define CATCH_INFO( msg ) (void)(0)
  10319. #define CATCH_WARN( msg ) (void)(0)
  10320. #define CATCH_CAPTURE( msg ) (void)(0)
  10321. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10322. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10323. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  10324. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  10325. #define CATCH_SECTION( ... )
  10326. #define CATCH_FAIL( ... ) (void)(0)
  10327. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  10328. #define CATCH_SUCCEED( ... ) (void)(0)
  10329. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10330. // "BDD-style" convenience wrappers
  10331. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10332. #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 )
  10333. #define CATCH_GIVEN( desc )
  10334. #define CATCH_WHEN( desc )
  10335. #define CATCH_AND_WHEN( desc )
  10336. #define CATCH_THEN( desc )
  10337. #define CATCH_AND_THEN( desc )
  10338. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  10339. #else
  10340. #define REQUIRE( ... ) (void)(0)
  10341. #define REQUIRE_FALSE( ... ) (void)(0)
  10342. #define REQUIRE_THROWS( ... ) (void)(0)
  10343. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  10344. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  10345. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10346. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10347. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10348. #define REQUIRE_NOTHROW( ... ) (void)(0)
  10349. #define CHECK( ... ) (void)(0)
  10350. #define CHECK_FALSE( ... ) (void)(0)
  10351. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  10352. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  10353. #define CHECK_NOFAIL( ... ) (void)(0)
  10354. #define CHECK_THROWS( ... ) (void)(0)
  10355. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  10356. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  10357. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10358. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10359. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10360. #define CHECK_NOTHROW( ... ) (void)(0)
  10361. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10362. #define CHECK_THAT( arg, matcher ) (void)(0)
  10363. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  10364. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10365. #define INFO( msg ) (void)(0)
  10366. #define WARN( msg ) (void)(0)
  10367. #define CAPTURE( msg ) (void)(0)
  10368. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10369. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10370. #define METHOD_AS_TEST_CASE( method, ... )
  10371. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  10372. #define SECTION( ... )
  10373. #define FAIL( ... ) (void)(0)
  10374. #define FAIL_CHECK( ... ) (void)(0)
  10375. #define SUCCEED( ... ) (void)(0)
  10376. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10377. #endif
  10378. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  10379. // "BDD-style" convenience wrappers
  10380. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  10381. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  10382. #define GIVEN( desc )
  10383. #define WHEN( desc )
  10384. #define AND_WHEN( desc )
  10385. #define THEN( desc )
  10386. #define AND_THEN( desc )
  10387. using Catch::Detail::Approx;
  10388. #endif
  10389. #endif // ! CATCH_CONFIG_IMPL_ONLY
  10390. // start catch_reenable_warnings.h
  10391. #ifdef __clang__
  10392. # ifdef __ICC // icpc defines the __clang__ macro
  10393. # pragma warning(pop)
  10394. # else
  10395. # pragma clang diagnostic pop
  10396. # endif
  10397. #elif defined __GNUC__
  10398. # pragma GCC diagnostic pop
  10399. #endif
  10400. // end catch_reenable_warnings.h
  10401. // end catch.hpp
  10402. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED