You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

12853 lines
427KB

  1. /*
  2. * Catch v2.2.1
  3. * Generated: 2018-03-11 12:01:31.654719
  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 2
  16. #define CATCH_VERSION_PATCH 1
  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. // Assume that non-Windows platforms support posix signals by default
  123. #if !defined(CATCH_PLATFORM_WINDOWS)
  124. #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
  125. #endif
  126. ////////////////////////////////////////////////////////////////////////////////
  127. // We know some environments not to support full POSIX signals
  128. #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
  129. #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  130. #endif
  131. #ifdef __OS400__
  132. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  133. # define CATCH_CONFIG_COLOUR_NONE
  134. #endif
  135. ////////////////////////////////////////////////////////////////////////////////
  136. // Cygwin
  137. #ifdef __CYGWIN__
  138. // Required for some versions of Cygwin to declare gettimeofday
  139. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  140. # define _BSD_SOURCE
  141. #endif // __CYGWIN__
  142. ////////////////////////////////////////////////////////////////////////////////
  143. // Visual C++
  144. #ifdef _MSC_VER
  145. # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
  146. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  147. # endif
  148. // Universal Windows platform does not support SEH
  149. // Or console colours (or console at all...)
  150. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  151. # define CATCH_CONFIG_COLOUR_NONE
  152. # else
  153. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  154. # endif
  155. #endif // _MSC_VER
  156. ////////////////////////////////////////////////////////////////////////////////
  157. // DJGPP
  158. #ifdef __DJGPP__
  159. # define CATCH_INTERNAL_CONFIG_NO_WCHAR
  160. #endif // __DJGPP__
  161. ////////////////////////////////////////////////////////////////////////////////
  162. // Use of __COUNTER__ is suppressed during code analysis in
  163. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  164. // handled by it.
  165. // Otherwise all supported compilers support COUNTER macro,
  166. // but user still might want to turn it off
  167. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  168. #define CATCH_INTERNAL_CONFIG_COUNTER
  169. #endif
  170. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  171. # define CATCH_CONFIG_COUNTER
  172. #endif
  173. #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH)
  174. # define CATCH_CONFIG_WINDOWS_SEH
  175. #endif
  176. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  177. #if defined(CATCH_INTERNAL_CONFIG_POSIX_SIGNALS) && !defined(CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_NO_POSIX_SIGNALS) && !defined(CATCH_CONFIG_POSIX_SIGNALS)
  178. # define CATCH_CONFIG_POSIX_SIGNALS
  179. #endif
  180. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  181. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  182. # define CATCH_CONFIG_WCHAR
  183. #endif
  184. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  185. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  186. #endif
  187. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  188. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  189. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  190. #endif
  191. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  192. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  193. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  194. #endif
  195. // end catch_compiler_capabilities.h
  196. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  197. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  198. #ifdef CATCH_CONFIG_COUNTER
  199. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  200. #else
  201. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  202. #endif
  203. #include <iosfwd>
  204. #include <string>
  205. #include <cstdint>
  206. namespace Catch {
  207. struct CaseSensitive { enum Choice {
  208. Yes,
  209. No
  210. }; };
  211. class NonCopyable {
  212. NonCopyable( NonCopyable const& ) = delete;
  213. NonCopyable( NonCopyable && ) = delete;
  214. NonCopyable& operator = ( NonCopyable const& ) = delete;
  215. NonCopyable& operator = ( NonCopyable && ) = delete;
  216. protected:
  217. NonCopyable();
  218. virtual ~NonCopyable();
  219. };
  220. struct SourceLineInfo {
  221. SourceLineInfo() = delete;
  222. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  223. : file( _file ),
  224. line( _line )
  225. {}
  226. SourceLineInfo( SourceLineInfo const& other ) = default;
  227. SourceLineInfo( SourceLineInfo && ) = default;
  228. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  229. SourceLineInfo& operator = ( SourceLineInfo && ) = default;
  230. bool empty() const noexcept;
  231. bool operator == ( SourceLineInfo const& other ) const noexcept;
  232. bool operator < ( SourceLineInfo const& other ) const noexcept;
  233. char const* file;
  234. std::size_t line;
  235. };
  236. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  237. // Use this in variadic streaming macros to allow
  238. // >> +StreamEndStop
  239. // as well as
  240. // >> stuff +StreamEndStop
  241. struct StreamEndStop {
  242. std::string operator+() const;
  243. };
  244. template<typename T>
  245. T const& operator + ( T const& value, StreamEndStop ) {
  246. return value;
  247. }
  248. }
  249. #define CATCH_INTERNAL_LINEINFO \
  250. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  251. // end catch_common.h
  252. namespace Catch {
  253. struct RegistrarForTagAliases {
  254. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  255. };
  256. } // end namespace Catch
  257. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  258. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  259. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  260. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  261. // end catch_tag_alias_autoregistrar.h
  262. // start catch_test_registry.h
  263. // start catch_interfaces_testcase.h
  264. #include <vector>
  265. #include <memory>
  266. namespace Catch {
  267. class TestSpec;
  268. struct ITestInvoker {
  269. virtual void invoke () const = 0;
  270. virtual ~ITestInvoker();
  271. };
  272. using ITestCasePtr = std::shared_ptr<ITestInvoker>;
  273. class TestCase;
  274. struct IConfig;
  275. struct ITestCaseRegistry {
  276. virtual ~ITestCaseRegistry();
  277. virtual std::vector<TestCase> const& getAllTests() const = 0;
  278. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  279. };
  280. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  281. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  282. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  283. }
  284. // end catch_interfaces_testcase.h
  285. // start catch_stringref.h
  286. #include <cstddef>
  287. #include <string>
  288. #include <iosfwd>
  289. namespace Catch {
  290. class StringData;
  291. /// A non-owning string class (similar to the forthcoming std::string_view)
  292. /// Note that, because a StringRef may be a substring of another string,
  293. /// it may not be null terminated. c_str() must return a null terminated
  294. /// string, however, and so the StringRef will internally take ownership
  295. /// (taking a copy), if necessary. In theory this ownership is not externally
  296. /// visible - but it does mean (substring) StringRefs should not be shared between
  297. /// threads.
  298. class StringRef {
  299. public:
  300. using size_type = std::size_t;
  301. private:
  302. friend struct StringRefTestAccess;
  303. char const* m_start;
  304. size_type m_size;
  305. char* m_data = nullptr;
  306. void takeOwnership();
  307. static constexpr char const* const s_empty = "";
  308. public: // construction/ assignment
  309. StringRef() noexcept
  310. : StringRef( s_empty, 0 )
  311. {}
  312. StringRef( StringRef const& other ) noexcept
  313. : m_start( other.m_start ),
  314. m_size( other.m_size )
  315. {}
  316. StringRef( StringRef&& other ) noexcept
  317. : m_start( other.m_start ),
  318. m_size( other.m_size ),
  319. m_data( other.m_data )
  320. {
  321. other.m_data = nullptr;
  322. }
  323. StringRef( char const* rawChars ) noexcept;
  324. StringRef( char const* rawChars, size_type size ) noexcept
  325. : m_start( rawChars ),
  326. m_size( size )
  327. {}
  328. StringRef( std::string const& stdString ) noexcept
  329. : m_start( stdString.c_str() ),
  330. m_size( stdString.size() )
  331. {}
  332. ~StringRef() noexcept {
  333. delete[] m_data;
  334. }
  335. auto operator = ( StringRef const &other ) noexcept -> StringRef& {
  336. delete[] m_data;
  337. m_data = nullptr;
  338. m_start = other.m_start;
  339. m_size = other.m_size;
  340. return *this;
  341. }
  342. operator std::string() const;
  343. void swap( StringRef& other ) noexcept;
  344. public: // operators
  345. auto operator == ( StringRef const& other ) const noexcept -> bool;
  346. auto operator != ( StringRef const& other ) const noexcept -> bool;
  347. auto operator[] ( size_type index ) const noexcept -> char;
  348. public: // named queries
  349. auto empty() const noexcept -> bool {
  350. return m_size == 0;
  351. }
  352. auto size() const noexcept -> size_type {
  353. return m_size;
  354. }
  355. auto numberOfCharacters() const noexcept -> size_type;
  356. auto c_str() const -> char const*;
  357. public: // substrings and searches
  358. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  359. // Returns the current start pointer.
  360. // Note that the pointer can change when if the StringRef is a substring
  361. auto currentData() const noexcept -> char const*;
  362. private: // ownership queries - may not be consistent between calls
  363. auto isOwned() const noexcept -> bool;
  364. auto isSubstring() const noexcept -> bool;
  365. };
  366. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  367. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  368. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  369. auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
  370. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  371. inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  372. return StringRef( rawChars, size );
  373. }
  374. } // namespace Catch
  375. // end catch_stringref.h
  376. namespace Catch {
  377. template<typename C>
  378. class TestInvokerAsMethod : public ITestInvoker {
  379. void (C::*m_testAsMethod)();
  380. public:
  381. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  382. void invoke() const override {
  383. C obj;
  384. (obj.*m_testAsMethod)();
  385. }
  386. };
  387. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  388. template<typename C>
  389. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  390. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  391. }
  392. struct NameAndTags {
  393. NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
  394. StringRef name;
  395. StringRef tags;
  396. };
  397. struct AutoReg : NonCopyable {
  398. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  399. ~AutoReg();
  400. };
  401. } // end namespace Catch
  402. #if defined(CATCH_CONFIG_DISABLE)
  403. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  404. static void TestName()
  405. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  406. namespace{ \
  407. struct TestName : ClassName { \
  408. void test(); \
  409. }; \
  410. } \
  411. void TestName::test()
  412. #endif
  413. ///////////////////////////////////////////////////////////////////////////////
  414. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  415. static void TestName(); \
  416. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  417. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  418. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  419. static void TestName()
  420. #define INTERNAL_CATCH_TESTCASE( ... ) \
  421. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  422. ///////////////////////////////////////////////////////////////////////////////
  423. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  424. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  425. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  426. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  427. ///////////////////////////////////////////////////////////////////////////////
  428. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  429. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  430. namespace{ \
  431. struct TestName : ClassName{ \
  432. void test(); \
  433. }; \
  434. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  435. } \
  436. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  437. void TestName::test()
  438. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  439. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  440. ///////////////////////////////////////////////////////////////////////////////
  441. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  442. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  443. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, "", Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  444. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  445. // end catch_test_registry.h
  446. // start catch_capture.hpp
  447. // start catch_assertionhandler.h
  448. // start catch_assertioninfo.h
  449. // start catch_result_type.h
  450. namespace Catch {
  451. // ResultWas::OfType enum
  452. struct ResultWas { enum OfType {
  453. Unknown = -1,
  454. Ok = 0,
  455. Info = 1,
  456. Warning = 2,
  457. FailureBit = 0x10,
  458. ExpressionFailed = FailureBit | 1,
  459. ExplicitFailure = FailureBit | 2,
  460. Exception = 0x100 | FailureBit,
  461. ThrewException = Exception | 1,
  462. DidntThrowException = Exception | 2,
  463. FatalErrorCondition = 0x200 | FailureBit
  464. }; };
  465. bool isOk( ResultWas::OfType resultType );
  466. bool isJustInfo( int flags );
  467. // ResultDisposition::Flags enum
  468. struct ResultDisposition { enum Flags {
  469. Normal = 0x01,
  470. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  471. FalseTest = 0x04, // Prefix expression with !
  472. SuppressFail = 0x08 // Failures are reported but do not fail the test
  473. }; };
  474. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  475. bool shouldContinueOnFailure( int flags );
  476. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  477. bool shouldSuppressFailure( int flags );
  478. } // end namespace Catch
  479. // end catch_result_type.h
  480. namespace Catch {
  481. struct AssertionInfo
  482. {
  483. StringRef macroName;
  484. SourceLineInfo lineInfo;
  485. StringRef capturedExpression;
  486. ResultDisposition::Flags resultDisposition;
  487. // We want to delete this constructor but a compiler bug in 4.8 means
  488. // the struct is then treated as non-aggregate
  489. //AssertionInfo() = delete;
  490. };
  491. } // end namespace Catch
  492. // end catch_assertioninfo.h
  493. // start catch_decomposer.h
  494. // start catch_tostring.h
  495. #include <vector>
  496. #include <cstddef>
  497. #include <type_traits>
  498. #include <string>
  499. // start catch_stream.h
  500. #include <iosfwd>
  501. #include <cstddef>
  502. #include <ostream>
  503. namespace Catch {
  504. std::ostream& cout();
  505. std::ostream& cerr();
  506. std::ostream& clog();
  507. class StringRef;
  508. struct IStream {
  509. virtual ~IStream();
  510. virtual std::ostream& stream() const = 0;
  511. };
  512. auto makeStream( StringRef const &filename ) -> IStream const*;
  513. class ReusableStringStream {
  514. std::size_t m_index;
  515. std::ostream* m_oss;
  516. public:
  517. ReusableStringStream();
  518. ~ReusableStringStream();
  519. auto str() const -> std::string;
  520. template<typename T>
  521. auto operator << ( T const& value ) -> ReusableStringStream& {
  522. *m_oss << value;
  523. return *this;
  524. }
  525. auto get() -> std::ostream& { return *m_oss; }
  526. static void cleanup();
  527. };
  528. }
  529. // end catch_stream.h
  530. #ifdef __OBJC__
  531. // start catch_objc_arc.hpp
  532. #import <Foundation/Foundation.h>
  533. #ifdef __has_feature
  534. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  535. #else
  536. #define CATCH_ARC_ENABLED 0
  537. #endif
  538. void arcSafeRelease( NSObject* obj );
  539. id performOptionalSelector( id obj, SEL sel );
  540. #if !CATCH_ARC_ENABLED
  541. inline void arcSafeRelease( NSObject* obj ) {
  542. [obj release];
  543. }
  544. inline id performOptionalSelector( id obj, SEL sel ) {
  545. if( [obj respondsToSelector: sel] )
  546. return [obj performSelector: sel];
  547. return nil;
  548. }
  549. #define CATCH_UNSAFE_UNRETAINED
  550. #define CATCH_ARC_STRONG
  551. #else
  552. inline void arcSafeRelease( NSObject* ){}
  553. inline id performOptionalSelector( id obj, SEL sel ) {
  554. #ifdef __clang__
  555. #pragma clang diagnostic push
  556. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  557. #endif
  558. if( [obj respondsToSelector: sel] )
  559. return [obj performSelector: sel];
  560. #ifdef __clang__
  561. #pragma clang diagnostic pop
  562. #endif
  563. return nil;
  564. }
  565. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  566. #define CATCH_ARC_STRONG __strong
  567. #endif
  568. // end catch_objc_arc.hpp
  569. #endif
  570. #ifdef _MSC_VER
  571. #pragma warning(push)
  572. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  573. #endif
  574. // We need a dummy global operator<< so we can bring it into Catch namespace later
  575. struct Catch_global_namespace_dummy {};
  576. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  577. namespace Catch {
  578. // Bring in operator<< from global namespace into Catch namespace
  579. using ::operator<<;
  580. namespace Detail {
  581. extern const std::string unprintableString;
  582. std::string rawMemoryToString( const void *object, std::size_t size );
  583. template<typename T>
  584. std::string rawMemoryToString( const T& object ) {
  585. return rawMemoryToString( &object, sizeof(object) );
  586. }
  587. template<typename T>
  588. class IsStreamInsertable {
  589. template<typename SS, typename TT>
  590. static auto test(int)
  591. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  592. template<typename, typename>
  593. static auto test(...)->std::false_type;
  594. public:
  595. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  596. };
  597. template<typename E>
  598. std::string convertUnknownEnumToString( E e );
  599. template<typename T>
  600. typename std::enable_if<!std::is_enum<T>::value, std::string>::type convertUnstreamable( T const& value ) {
  601. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  602. (void)value;
  603. return Detail::unprintableString;
  604. #else
  605. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  606. #endif
  607. }
  608. template<typename T>
  609. typename std::enable_if<std::is_enum<T>::value, std::string>::type convertUnstreamable( T const& value ) {
  610. return convertUnknownEnumToString( value );
  611. }
  612. } // namespace Detail
  613. // If we decide for C++14, change these to enable_if_ts
  614. template <typename T, typename = void>
  615. struct StringMaker {
  616. template <typename Fake = T>
  617. static
  618. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  619. convert(const Fake& value) {
  620. ReusableStringStream rss;
  621. rss << value;
  622. return rss.str();
  623. }
  624. template <typename Fake = T>
  625. static
  626. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  627. convert( const Fake& value ) {
  628. return Detail::convertUnstreamable( value );
  629. }
  630. };
  631. namespace Detail {
  632. // This function dispatches all stringification requests inside of Catch.
  633. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  634. template <typename T>
  635. std::string stringify(const T& e) {
  636. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  637. }
  638. template<typename E>
  639. std::string convertUnknownEnumToString( E e ) {
  640. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  641. }
  642. } // namespace Detail
  643. // Some predefined specializations
  644. template<>
  645. struct StringMaker<std::string> {
  646. static std::string convert(const std::string& str);
  647. };
  648. #ifdef CATCH_CONFIG_WCHAR
  649. template<>
  650. struct StringMaker<std::wstring> {
  651. static std::string convert(const std::wstring& wstr);
  652. };
  653. #endif
  654. template<>
  655. struct StringMaker<char const *> {
  656. static std::string convert(char const * str);
  657. };
  658. template<>
  659. struct StringMaker<char *> {
  660. static std::string convert(char * str);
  661. };
  662. #ifdef CATCH_CONFIG_WCHAR
  663. template<>
  664. struct StringMaker<wchar_t const *> {
  665. static std::string convert(wchar_t const * str);
  666. };
  667. template<>
  668. struct StringMaker<wchar_t *> {
  669. static std::string convert(wchar_t * str);
  670. };
  671. #endif
  672. template<int SZ>
  673. struct StringMaker<char[SZ]> {
  674. static std::string convert(const char* str) {
  675. return ::Catch::Detail::stringify(std::string{ str });
  676. }
  677. };
  678. template<int SZ>
  679. struct StringMaker<signed char[SZ]> {
  680. static std::string convert(const char* str) {
  681. return ::Catch::Detail::stringify(std::string{ str });
  682. }
  683. };
  684. template<int SZ>
  685. struct StringMaker<unsigned char[SZ]> {
  686. static std::string convert(const char* str) {
  687. return ::Catch::Detail::stringify(std::string{ str });
  688. }
  689. };
  690. template<>
  691. struct StringMaker<int> {
  692. static std::string convert(int value);
  693. };
  694. template<>
  695. struct StringMaker<long> {
  696. static std::string convert(long value);
  697. };
  698. template<>
  699. struct StringMaker<long long> {
  700. static std::string convert(long long value);
  701. };
  702. template<>
  703. struct StringMaker<unsigned int> {
  704. static std::string convert(unsigned int value);
  705. };
  706. template<>
  707. struct StringMaker<unsigned long> {
  708. static std::string convert(unsigned long value);
  709. };
  710. template<>
  711. struct StringMaker<unsigned long long> {
  712. static std::string convert(unsigned long long value);
  713. };
  714. template<>
  715. struct StringMaker<bool> {
  716. static std::string convert(bool b);
  717. };
  718. template<>
  719. struct StringMaker<char> {
  720. static std::string convert(char c);
  721. };
  722. template<>
  723. struct StringMaker<signed char> {
  724. static std::string convert(signed char c);
  725. };
  726. template<>
  727. struct StringMaker<unsigned char> {
  728. static std::string convert(unsigned char c);
  729. };
  730. template<>
  731. struct StringMaker<std::nullptr_t> {
  732. static std::string convert(std::nullptr_t);
  733. };
  734. template<>
  735. struct StringMaker<float> {
  736. static std::string convert(float value);
  737. };
  738. template<>
  739. struct StringMaker<double> {
  740. static std::string convert(double value);
  741. };
  742. template <typename T>
  743. struct StringMaker<T*> {
  744. template <typename U>
  745. static std::string convert(U* p) {
  746. if (p) {
  747. return ::Catch::Detail::rawMemoryToString(p);
  748. } else {
  749. return "nullptr";
  750. }
  751. }
  752. };
  753. template <typename R, typename C>
  754. struct StringMaker<R C::*> {
  755. static std::string convert(R C::* p) {
  756. if (p) {
  757. return ::Catch::Detail::rawMemoryToString(p);
  758. } else {
  759. return "nullptr";
  760. }
  761. }
  762. };
  763. namespace Detail {
  764. template<typename InputIterator>
  765. std::string rangeToString(InputIterator first, InputIterator last) {
  766. ReusableStringStream rss;
  767. rss << "{ ";
  768. if (first != last) {
  769. rss << ::Catch::Detail::stringify(*first);
  770. for (++first; first != last; ++first)
  771. rss << ", " << ::Catch::Detail::stringify(*first);
  772. }
  773. rss << " }";
  774. return rss.str();
  775. }
  776. }
  777. #ifdef __OBJC__
  778. template<>
  779. struct StringMaker<NSString*> {
  780. static std::string convert(NSString * nsstring) {
  781. if (!nsstring)
  782. return "nil";
  783. return std::string("@") + [nsstring UTF8String];
  784. }
  785. };
  786. template<>
  787. struct StringMaker<NSObject*> {
  788. static std::string convert(NSObject* nsObject) {
  789. return ::Catch::Detail::stringify([nsObject description]);
  790. }
  791. };
  792. namespace Detail {
  793. inline std::string stringify( NSString* nsstring ) {
  794. return StringMaker<NSString*>::convert( nsstring );
  795. }
  796. } // namespace Detail
  797. #endif // __OBJC__
  798. } // namespace Catch
  799. //////////////////////////////////////////////////////
  800. // Separate std-lib types stringification, so it can be selectively enabled
  801. // This means that we do not bring in
  802. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  803. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  804. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  805. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  806. #endif
  807. // Separate std::pair specialization
  808. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  809. #include <utility>
  810. namespace Catch {
  811. template<typename T1, typename T2>
  812. struct StringMaker<std::pair<T1, T2> > {
  813. static std::string convert(const std::pair<T1, T2>& pair) {
  814. ReusableStringStream rss;
  815. rss << "{ "
  816. << ::Catch::Detail::stringify(pair.first)
  817. << ", "
  818. << ::Catch::Detail::stringify(pair.second)
  819. << " }";
  820. return rss.str();
  821. }
  822. };
  823. }
  824. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  825. // Separate std::tuple specialization
  826. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  827. #include <tuple>
  828. namespace Catch {
  829. namespace Detail {
  830. template<
  831. typename Tuple,
  832. std::size_t N = 0,
  833. bool = (N < std::tuple_size<Tuple>::value)
  834. >
  835. struct TupleElementPrinter {
  836. static void print(const Tuple& tuple, std::ostream& os) {
  837. os << (N ? ", " : " ")
  838. << ::Catch::Detail::stringify(std::get<N>(tuple));
  839. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  840. }
  841. };
  842. template<
  843. typename Tuple,
  844. std::size_t N
  845. >
  846. struct TupleElementPrinter<Tuple, N, false> {
  847. static void print(const Tuple&, std::ostream&) {}
  848. };
  849. }
  850. template<typename ...Types>
  851. struct StringMaker<std::tuple<Types...>> {
  852. static std::string convert(const std::tuple<Types...>& tuple) {
  853. ReusableStringStream rss;
  854. rss << '{';
  855. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  856. rss << " }";
  857. return rss.str();
  858. }
  859. };
  860. }
  861. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  862. namespace Catch {
  863. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  864. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  865. using std::begin;
  866. using std::end;
  867. not_this_one begin( ... );
  868. not_this_one end( ... );
  869. template <typename T>
  870. struct is_range {
  871. static const bool value =
  872. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  873. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  874. };
  875. template<typename Range>
  876. std::string rangeToString( Range const& range ) {
  877. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  878. }
  879. // Handle vector<bool> specially
  880. template<typename Allocator>
  881. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  882. ReusableStringStream rss;
  883. rss << "{ ";
  884. bool first = true;
  885. for( bool b : v ) {
  886. if( first )
  887. first = false;
  888. else
  889. rss << ", ";
  890. rss << ::Catch::Detail::stringify( b );
  891. }
  892. rss << " }";
  893. return rss.str();
  894. }
  895. template<typename R>
  896. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  897. static std::string convert( R const& range ) {
  898. return rangeToString( range );
  899. }
  900. };
  901. template <typename T, int SZ>
  902. struct StringMaker<T[SZ]> {
  903. static std::string convert(T const(&arr)[SZ]) {
  904. return rangeToString(arr);
  905. }
  906. };
  907. } // namespace Catch
  908. // Separate std::chrono::duration specialization
  909. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  910. #include <ctime>
  911. #include <ratio>
  912. #include <chrono>
  913. namespace Catch {
  914. template <class Ratio>
  915. struct ratio_string {
  916. static std::string symbol();
  917. };
  918. template <class Ratio>
  919. std::string ratio_string<Ratio>::symbol() {
  920. Catch::ReusableStringStream rss;
  921. rss << '[' << Ratio::num << '/'
  922. << Ratio::den << ']';
  923. return rss.str();
  924. }
  925. template <>
  926. struct ratio_string<std::atto> {
  927. static std::string symbol();
  928. };
  929. template <>
  930. struct ratio_string<std::femto> {
  931. static std::string symbol();
  932. };
  933. template <>
  934. struct ratio_string<std::pico> {
  935. static std::string symbol();
  936. };
  937. template <>
  938. struct ratio_string<std::nano> {
  939. static std::string symbol();
  940. };
  941. template <>
  942. struct ratio_string<std::micro> {
  943. static std::string symbol();
  944. };
  945. template <>
  946. struct ratio_string<std::milli> {
  947. static std::string symbol();
  948. };
  949. ////////////
  950. // std::chrono::duration specializations
  951. template<typename Value, typename Ratio>
  952. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  953. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  954. ReusableStringStream rss;
  955. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  956. return rss.str();
  957. }
  958. };
  959. template<typename Value>
  960. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  961. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  962. ReusableStringStream rss;
  963. rss << duration.count() << " s";
  964. return rss.str();
  965. }
  966. };
  967. template<typename Value>
  968. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  969. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  970. ReusableStringStream rss;
  971. rss << duration.count() << " m";
  972. return rss.str();
  973. }
  974. };
  975. template<typename Value>
  976. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  977. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  978. ReusableStringStream rss;
  979. rss << duration.count() << " h";
  980. return rss.str();
  981. }
  982. };
  983. ////////////
  984. // std::chrono::time_point specialization
  985. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  986. template<typename Clock, typename Duration>
  987. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  988. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  989. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  990. }
  991. };
  992. // std::chrono::time_point<system_clock> specialization
  993. template<typename Duration>
  994. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  995. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  996. auto converted = std::chrono::system_clock::to_time_t(time_point);
  997. #ifdef _MSC_VER
  998. std::tm timeInfo = {};
  999. gmtime_s(&timeInfo, &converted);
  1000. #else
  1001. std::tm* timeInfo = std::gmtime(&converted);
  1002. #endif
  1003. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1004. char timeStamp[timeStampSize];
  1005. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1006. #ifdef _MSC_VER
  1007. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1008. #else
  1009. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1010. #endif
  1011. return std::string(timeStamp);
  1012. }
  1013. };
  1014. }
  1015. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1016. #ifdef _MSC_VER
  1017. #pragma warning(pop)
  1018. #endif
  1019. // end catch_tostring.h
  1020. #include <iosfwd>
  1021. #ifdef _MSC_VER
  1022. #pragma warning(push)
  1023. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1024. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1025. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1026. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1027. #endif
  1028. namespace Catch {
  1029. struct ITransientExpression {
  1030. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1031. auto getResult() const -> bool { return m_result; }
  1032. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1033. ITransientExpression( bool isBinaryExpression, bool result )
  1034. : m_isBinaryExpression( isBinaryExpression ),
  1035. m_result( result )
  1036. {}
  1037. // We don't actually need a virtual destructor, but many static analysers
  1038. // complain if it's not here :-(
  1039. virtual ~ITransientExpression();
  1040. bool m_isBinaryExpression;
  1041. bool m_result;
  1042. };
  1043. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1044. template<typename LhsT, typename RhsT>
  1045. class BinaryExpr : public ITransientExpression {
  1046. LhsT m_lhs;
  1047. StringRef m_op;
  1048. RhsT m_rhs;
  1049. void streamReconstructedExpression( std::ostream &os ) const override {
  1050. formatReconstructedExpression
  1051. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1052. }
  1053. public:
  1054. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1055. : ITransientExpression{ true, comparisonResult },
  1056. m_lhs( lhs ),
  1057. m_op( op ),
  1058. m_rhs( rhs )
  1059. {}
  1060. };
  1061. template<typename LhsT>
  1062. class UnaryExpr : public ITransientExpression {
  1063. LhsT m_lhs;
  1064. void streamReconstructedExpression( std::ostream &os ) const override {
  1065. os << Catch::Detail::stringify( m_lhs );
  1066. }
  1067. public:
  1068. explicit UnaryExpr( LhsT lhs )
  1069. : ITransientExpression{ false, lhs ? true : false },
  1070. m_lhs( lhs )
  1071. {}
  1072. };
  1073. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1074. template<typename LhsT, typename RhsT>
  1075. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1076. template<typename T>
  1077. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1078. template<typename T>
  1079. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1080. template<typename T>
  1081. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1082. template<typename T>
  1083. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1084. template<typename LhsT, typename RhsT>
  1085. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1086. template<typename T>
  1087. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1088. template<typename T>
  1089. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1090. template<typename T>
  1091. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1092. template<typename T>
  1093. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1094. template<typename LhsT>
  1095. class ExprLhs {
  1096. LhsT m_lhs;
  1097. public:
  1098. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1099. template<typename RhsT>
  1100. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1101. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1102. }
  1103. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1104. return { m_lhs == rhs, m_lhs, "==", rhs };
  1105. }
  1106. template<typename RhsT>
  1107. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1108. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1109. }
  1110. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1111. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1112. }
  1113. template<typename RhsT>
  1114. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1115. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1116. }
  1117. template<typename RhsT>
  1118. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1119. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  1120. }
  1121. template<typename RhsT>
  1122. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1123. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  1124. }
  1125. template<typename RhsT>
  1126. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1127. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  1128. }
  1129. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  1130. return UnaryExpr<LhsT>{ m_lhs };
  1131. }
  1132. };
  1133. void handleExpression( ITransientExpression const& expr );
  1134. template<typename T>
  1135. void handleExpression( ExprLhs<T> const& expr ) {
  1136. handleExpression( expr.makeUnaryExpr() );
  1137. }
  1138. struct Decomposer {
  1139. template<typename T>
  1140. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  1141. return ExprLhs<T const&>{ lhs };
  1142. }
  1143. auto operator <=( bool value ) -> ExprLhs<bool> {
  1144. return ExprLhs<bool>{ value };
  1145. }
  1146. };
  1147. } // end namespace Catch
  1148. #ifdef _MSC_VER
  1149. #pragma warning(pop)
  1150. #endif
  1151. // end catch_decomposer.h
  1152. // start catch_interfaces_capture.h
  1153. #include <string>
  1154. namespace Catch {
  1155. class AssertionResult;
  1156. struct AssertionInfo;
  1157. struct SectionInfo;
  1158. struct SectionEndInfo;
  1159. struct MessageInfo;
  1160. struct Counts;
  1161. struct BenchmarkInfo;
  1162. struct BenchmarkStats;
  1163. struct AssertionReaction;
  1164. struct ITransientExpression;
  1165. struct IResultCapture {
  1166. virtual ~IResultCapture();
  1167. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  1168. Counts& assertions ) = 0;
  1169. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  1170. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  1171. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  1172. virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;
  1173. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  1174. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  1175. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  1176. virtual void handleExpr
  1177. ( AssertionInfo const& info,
  1178. ITransientExpression const& expr,
  1179. AssertionReaction& reaction ) = 0;
  1180. virtual void handleMessage
  1181. ( AssertionInfo const& info,
  1182. ResultWas::OfType resultType,
  1183. StringRef const& message,
  1184. AssertionReaction& reaction ) = 0;
  1185. virtual void handleUnexpectedExceptionNotThrown
  1186. ( AssertionInfo const& info,
  1187. AssertionReaction& reaction ) = 0;
  1188. virtual void handleUnexpectedInflightException
  1189. ( AssertionInfo const& info,
  1190. std::string const& message,
  1191. AssertionReaction& reaction ) = 0;
  1192. virtual void handleIncomplete
  1193. ( AssertionInfo const& info ) = 0;
  1194. virtual void handleNonExpr
  1195. ( AssertionInfo const &info,
  1196. ResultWas::OfType resultType,
  1197. AssertionReaction &reaction ) = 0;
  1198. virtual bool lastAssertionPassed() = 0;
  1199. virtual void assertionPassed() = 0;
  1200. // Deprecated, do not use:
  1201. virtual std::string getCurrentTestName() const = 0;
  1202. virtual const AssertionResult* getLastResult() const = 0;
  1203. virtual void exceptionEarlyReported() = 0;
  1204. };
  1205. IResultCapture& getResultCapture();
  1206. }
  1207. // end catch_interfaces_capture.h
  1208. namespace Catch {
  1209. struct TestFailureException{};
  1210. struct AssertionResultData;
  1211. struct IResultCapture;
  1212. class RunContext;
  1213. class LazyExpression {
  1214. friend class AssertionHandler;
  1215. friend struct AssertionStats;
  1216. friend class RunContext;
  1217. ITransientExpression const* m_transientExpression = nullptr;
  1218. bool m_isNegated;
  1219. public:
  1220. LazyExpression( bool isNegated );
  1221. LazyExpression( LazyExpression const& other );
  1222. LazyExpression& operator = ( LazyExpression const& ) = delete;
  1223. explicit operator bool() const;
  1224. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  1225. };
  1226. struct AssertionReaction {
  1227. bool shouldDebugBreak = false;
  1228. bool shouldThrow = false;
  1229. };
  1230. class AssertionHandler {
  1231. AssertionInfo m_assertionInfo;
  1232. AssertionReaction m_reaction;
  1233. bool m_completed = false;
  1234. IResultCapture& m_resultCapture;
  1235. public:
  1236. AssertionHandler
  1237. ( StringRef macroName,
  1238. SourceLineInfo const& lineInfo,
  1239. StringRef capturedExpression,
  1240. ResultDisposition::Flags resultDisposition );
  1241. ~AssertionHandler() {
  1242. if ( !m_completed ) {
  1243. m_resultCapture.handleIncomplete( m_assertionInfo );
  1244. }
  1245. }
  1246. template<typename T>
  1247. void handleExpr( ExprLhs<T> const& expr ) {
  1248. handleExpr( expr.makeUnaryExpr() );
  1249. }
  1250. void handleExpr( ITransientExpression const& expr );
  1251. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  1252. void handleExceptionThrownAsExpected();
  1253. void handleUnexpectedExceptionNotThrown();
  1254. void handleExceptionNotThrownAsExpected();
  1255. void handleThrowingCallSkipped();
  1256. void handleUnexpectedInflightException();
  1257. void complete();
  1258. void setCompleted();
  1259. // query
  1260. auto allowThrows() const -> bool;
  1261. };
  1262. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString );
  1263. } // namespace Catch
  1264. // end catch_assertionhandler.h
  1265. // start catch_message.h
  1266. #include <string>
  1267. namespace Catch {
  1268. struct MessageInfo {
  1269. MessageInfo( std::string const& _macroName,
  1270. SourceLineInfo const& _lineInfo,
  1271. ResultWas::OfType _type );
  1272. std::string macroName;
  1273. std::string message;
  1274. SourceLineInfo lineInfo;
  1275. ResultWas::OfType type;
  1276. unsigned int sequence;
  1277. bool operator == ( MessageInfo const& other ) const;
  1278. bool operator < ( MessageInfo const& other ) const;
  1279. private:
  1280. static unsigned int globalCount;
  1281. };
  1282. struct MessageStream {
  1283. template<typename T>
  1284. MessageStream& operator << ( T const& value ) {
  1285. m_stream << value;
  1286. return *this;
  1287. }
  1288. ReusableStringStream m_stream;
  1289. };
  1290. struct MessageBuilder : MessageStream {
  1291. MessageBuilder( std::string const& macroName,
  1292. SourceLineInfo const& lineInfo,
  1293. ResultWas::OfType type );
  1294. template<typename T>
  1295. MessageBuilder& operator << ( T const& value ) {
  1296. m_stream << value;
  1297. return *this;
  1298. }
  1299. MessageInfo m_info;
  1300. };
  1301. class ScopedMessage {
  1302. public:
  1303. explicit ScopedMessage( MessageBuilder const& builder );
  1304. ~ScopedMessage();
  1305. MessageInfo m_info;
  1306. };
  1307. } // end namespace Catch
  1308. // end catch_message.h
  1309. #if !defined(CATCH_CONFIG_DISABLE)
  1310. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  1311. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  1312. #else
  1313. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  1314. #endif
  1315. #if defined(CATCH_CONFIG_FAST_COMPILE)
  1316. ///////////////////////////////////////////////////////////////////////////////
  1317. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  1318. // macros.
  1319. #define INTERNAL_CATCH_TRY
  1320. #define INTERNAL_CATCH_CATCH( capturer )
  1321. #else // CATCH_CONFIG_FAST_COMPILE
  1322. #define INTERNAL_CATCH_TRY try
  1323. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  1324. #endif
  1325. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  1326. ///////////////////////////////////////////////////////////////////////////////
  1327. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  1328. do { \
  1329. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1330. INTERNAL_CATCH_TRY { \
  1331. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  1332. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  1333. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  1334. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1335. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1336. } 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
  1337. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  1338. ///////////////////////////////////////////////////////////////////////////////
  1339. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  1340. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1341. if( Catch::getResultCapture().lastAssertionPassed() )
  1342. ///////////////////////////////////////////////////////////////////////////////
  1343. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  1344. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1345. if( !Catch::getResultCapture().lastAssertionPassed() )
  1346. ///////////////////////////////////////////////////////////////////////////////
  1347. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  1348. do { \
  1349. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1350. try { \
  1351. static_cast<void>(__VA_ARGS__); \
  1352. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  1353. } \
  1354. catch( ... ) { \
  1355. catchAssertionHandler.handleUnexpectedInflightException(); \
  1356. } \
  1357. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1358. } while( false )
  1359. ///////////////////////////////////////////////////////////////////////////////
  1360. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  1361. do { \
  1362. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  1363. if( catchAssertionHandler.allowThrows() ) \
  1364. try { \
  1365. static_cast<void>(__VA_ARGS__); \
  1366. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1367. } \
  1368. catch( ... ) { \
  1369. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1370. } \
  1371. else \
  1372. catchAssertionHandler.handleThrowingCallSkipped(); \
  1373. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1374. } while( false )
  1375. ///////////////////////////////////////////////////////////////////////////////
  1376. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  1377. do { \
  1378. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  1379. if( catchAssertionHandler.allowThrows() ) \
  1380. try { \
  1381. static_cast<void>(expr); \
  1382. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1383. } \
  1384. catch( exceptionType const& ) { \
  1385. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1386. } \
  1387. catch( ... ) { \
  1388. catchAssertionHandler.handleUnexpectedInflightException(); \
  1389. } \
  1390. else \
  1391. catchAssertionHandler.handleThrowingCallSkipped(); \
  1392. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1393. } while( false )
  1394. ///////////////////////////////////////////////////////////////////////////////
  1395. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  1396. do { \
  1397. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, "", resultDisposition ); \
  1398. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  1399. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1400. } while( false )
  1401. ///////////////////////////////////////////////////////////////////////////////
  1402. #define INTERNAL_CATCH_INFO( macroName, log ) \
  1403. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  1404. ///////////////////////////////////////////////////////////////////////////////
  1405. // Although this is matcher-based, it can be used with just a string
  1406. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  1407. do { \
  1408. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1409. if( catchAssertionHandler.allowThrows() ) \
  1410. try { \
  1411. static_cast<void>(__VA_ARGS__); \
  1412. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1413. } \
  1414. catch( ... ) { \
  1415. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher ); \
  1416. } \
  1417. else \
  1418. catchAssertionHandler.handleThrowingCallSkipped(); \
  1419. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1420. } while( false )
  1421. #endif // CATCH_CONFIG_DISABLE
  1422. // end catch_capture.hpp
  1423. // start catch_section.h
  1424. // start catch_section_info.h
  1425. // start catch_totals.h
  1426. #include <cstddef>
  1427. namespace Catch {
  1428. struct Counts {
  1429. Counts operator - ( Counts const& other ) const;
  1430. Counts& operator += ( Counts const& other );
  1431. std::size_t total() const;
  1432. bool allPassed() const;
  1433. bool allOk() const;
  1434. std::size_t passed = 0;
  1435. std::size_t failed = 0;
  1436. std::size_t failedButOk = 0;
  1437. };
  1438. struct Totals {
  1439. Totals operator - ( Totals const& other ) const;
  1440. Totals& operator += ( Totals const& other );
  1441. Totals delta( Totals const& prevTotals ) const;
  1442. int error = 0;
  1443. Counts assertions;
  1444. Counts testCases;
  1445. };
  1446. }
  1447. // end catch_totals.h
  1448. #include <string>
  1449. namespace Catch {
  1450. struct SectionInfo {
  1451. SectionInfo
  1452. ( SourceLineInfo const& _lineInfo,
  1453. std::string const& _name,
  1454. std::string const& _description = std::string() );
  1455. std::string name;
  1456. std::string description;
  1457. SourceLineInfo lineInfo;
  1458. };
  1459. struct SectionEndInfo {
  1460. SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds );
  1461. SectionInfo sectionInfo;
  1462. Counts prevAssertions;
  1463. double durationInSeconds;
  1464. };
  1465. } // end namespace Catch
  1466. // end catch_section_info.h
  1467. // start catch_timer.h
  1468. #include <cstdint>
  1469. namespace Catch {
  1470. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  1471. auto getEstimatedClockResolution() -> uint64_t;
  1472. class Timer {
  1473. uint64_t m_nanoseconds = 0;
  1474. public:
  1475. void start();
  1476. auto getElapsedNanoseconds() const -> uint64_t;
  1477. auto getElapsedMicroseconds() const -> uint64_t;
  1478. auto getElapsedMilliseconds() const -> unsigned int;
  1479. auto getElapsedSeconds() const -> double;
  1480. };
  1481. } // namespace Catch
  1482. // end catch_timer.h
  1483. #include <string>
  1484. namespace Catch {
  1485. class Section : NonCopyable {
  1486. public:
  1487. Section( SectionInfo const& info );
  1488. ~Section();
  1489. // This indicates whether the section should be executed or not
  1490. explicit operator bool() const;
  1491. private:
  1492. SectionInfo m_info;
  1493. std::string m_name;
  1494. Counts m_assertions;
  1495. bool m_sectionIncluded;
  1496. Timer m_timer;
  1497. };
  1498. } // end namespace Catch
  1499. #define INTERNAL_CATCH_SECTION( ... ) \
  1500. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) )
  1501. // end catch_section.h
  1502. // start catch_benchmark.h
  1503. #include <cstdint>
  1504. #include <string>
  1505. namespace Catch {
  1506. class BenchmarkLooper {
  1507. std::string m_name;
  1508. std::size_t m_count = 0;
  1509. std::size_t m_iterationsToRun = 1;
  1510. uint64_t m_resolution;
  1511. Timer m_timer;
  1512. static auto getResolution() -> uint64_t;
  1513. public:
  1514. // Keep most of this inline as it's on the code path that is being timed
  1515. BenchmarkLooper( StringRef name )
  1516. : m_name( name ),
  1517. m_resolution( getResolution() )
  1518. {
  1519. reportStart();
  1520. m_timer.start();
  1521. }
  1522. explicit operator bool() {
  1523. if( m_count < m_iterationsToRun )
  1524. return true;
  1525. return needsMoreIterations();
  1526. }
  1527. void increment() {
  1528. ++m_count;
  1529. }
  1530. void reportStart();
  1531. auto needsMoreIterations() -> bool;
  1532. };
  1533. } // end namespace Catch
  1534. #define BENCHMARK( name ) \
  1535. for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )
  1536. // end catch_benchmark.h
  1537. // start catch_interfaces_exception.h
  1538. // start catch_interfaces_registry_hub.h
  1539. #include <string>
  1540. #include <memory>
  1541. namespace Catch {
  1542. class TestCase;
  1543. struct ITestCaseRegistry;
  1544. struct IExceptionTranslatorRegistry;
  1545. struct IExceptionTranslator;
  1546. struct IReporterRegistry;
  1547. struct IReporterFactory;
  1548. struct ITagAliasRegistry;
  1549. class StartupExceptionRegistry;
  1550. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  1551. struct IRegistryHub {
  1552. virtual ~IRegistryHub();
  1553. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  1554. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  1555. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  1556. virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0;
  1557. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  1558. };
  1559. struct IMutableRegistryHub {
  1560. virtual ~IMutableRegistryHub();
  1561. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  1562. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  1563. virtual void registerTest( TestCase const& testInfo ) = 0;
  1564. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  1565. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  1566. virtual void registerStartupException() noexcept = 0;
  1567. };
  1568. IRegistryHub& getRegistryHub();
  1569. IMutableRegistryHub& getMutableRegistryHub();
  1570. void cleanUp();
  1571. std::string translateActiveException();
  1572. }
  1573. // end catch_interfaces_registry_hub.h
  1574. #if defined(CATCH_CONFIG_DISABLE)
  1575. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  1576. static std::string translatorName( signature )
  1577. #endif
  1578. #include <exception>
  1579. #include <string>
  1580. #include <vector>
  1581. namespace Catch {
  1582. using exceptionTranslateFunction = std::string(*)();
  1583. struct IExceptionTranslator;
  1584. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  1585. struct IExceptionTranslator {
  1586. virtual ~IExceptionTranslator();
  1587. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  1588. };
  1589. struct IExceptionTranslatorRegistry {
  1590. virtual ~IExceptionTranslatorRegistry();
  1591. virtual std::string translateActiveException() const = 0;
  1592. };
  1593. class ExceptionTranslatorRegistrar {
  1594. template<typename T>
  1595. class ExceptionTranslator : public IExceptionTranslator {
  1596. public:
  1597. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  1598. : m_translateFunction( translateFunction )
  1599. {}
  1600. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  1601. try {
  1602. if( it == itEnd )
  1603. std::rethrow_exception(std::current_exception());
  1604. else
  1605. return (*it)->translate( it+1, itEnd );
  1606. }
  1607. catch( T& ex ) {
  1608. return m_translateFunction( ex );
  1609. }
  1610. }
  1611. protected:
  1612. std::string(*m_translateFunction)( T& );
  1613. };
  1614. public:
  1615. template<typename T>
  1616. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  1617. getMutableRegistryHub().registerTranslator
  1618. ( new ExceptionTranslator<T>( translateFunction ) );
  1619. }
  1620. };
  1621. }
  1622. ///////////////////////////////////////////////////////////////////////////////
  1623. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  1624. static std::string translatorName( signature ); \
  1625. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1626. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  1627. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1628. static std::string translatorName( signature )
  1629. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  1630. // end catch_interfaces_exception.h
  1631. // start catch_approx.h
  1632. #include <type_traits>
  1633. #include <stdexcept>
  1634. namespace Catch {
  1635. namespace Detail {
  1636. class Approx {
  1637. private:
  1638. bool equalityComparisonImpl(double other) const;
  1639. public:
  1640. explicit Approx ( double value );
  1641. static Approx custom();
  1642. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1643. Approx operator()( T const& value ) {
  1644. Approx approx( static_cast<double>(value) );
  1645. approx.epsilon( m_epsilon );
  1646. approx.margin( m_margin );
  1647. approx.scale( m_scale );
  1648. return approx;
  1649. }
  1650. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1651. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  1652. {}
  1653. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1654. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  1655. auto lhs_v = static_cast<double>(lhs);
  1656. return rhs.equalityComparisonImpl(lhs_v);
  1657. }
  1658. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1659. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  1660. return operator==( rhs, lhs );
  1661. }
  1662. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1663. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  1664. return !operator==( lhs, rhs );
  1665. }
  1666. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1667. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  1668. return !operator==( rhs, lhs );
  1669. }
  1670. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1671. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  1672. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  1673. }
  1674. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1675. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  1676. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  1677. }
  1678. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1679. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  1680. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  1681. }
  1682. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1683. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  1684. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  1685. }
  1686. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1687. Approx& epsilon( T const& newEpsilon ) {
  1688. double epsilonAsDouble = static_cast<double>(newEpsilon);
  1689. if( epsilonAsDouble < 0 || epsilonAsDouble > 1.0 ) {
  1690. throw std::domain_error
  1691. ( "Invalid Approx::epsilon: " +
  1692. Catch::Detail::stringify( epsilonAsDouble ) +
  1693. ", Approx::epsilon has to be between 0 and 1" );
  1694. }
  1695. m_epsilon = epsilonAsDouble;
  1696. return *this;
  1697. }
  1698. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1699. Approx& margin( T const& newMargin ) {
  1700. double marginAsDouble = static_cast<double>(newMargin);
  1701. if( marginAsDouble < 0 ) {
  1702. throw std::domain_error
  1703. ( "Invalid Approx::margin: " +
  1704. Catch::Detail::stringify( marginAsDouble ) +
  1705. ", Approx::Margin has to be non-negative." );
  1706. }
  1707. m_margin = marginAsDouble;
  1708. return *this;
  1709. }
  1710. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1711. Approx& scale( T const& newScale ) {
  1712. m_scale = static_cast<double>(newScale);
  1713. return *this;
  1714. }
  1715. std::string toString() const;
  1716. private:
  1717. double m_epsilon;
  1718. double m_margin;
  1719. double m_scale;
  1720. double m_value;
  1721. };
  1722. }
  1723. template<>
  1724. struct StringMaker<Catch::Detail::Approx> {
  1725. static std::string convert(Catch::Detail::Approx const& value);
  1726. };
  1727. } // end namespace Catch
  1728. // end catch_approx.h
  1729. // start catch_string_manip.h
  1730. #include <string>
  1731. #include <iosfwd>
  1732. namespace Catch {
  1733. bool startsWith( std::string const& s, std::string const& prefix );
  1734. bool startsWith( std::string const& s, char prefix );
  1735. bool endsWith( std::string const& s, std::string const& suffix );
  1736. bool endsWith( std::string const& s, char suffix );
  1737. bool contains( std::string const& s, std::string const& infix );
  1738. void toLowerInPlace( std::string& s );
  1739. std::string toLower( std::string const& s );
  1740. std::string trim( std::string const& str );
  1741. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  1742. struct pluralise {
  1743. pluralise( std::size_t count, std::string const& label );
  1744. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  1745. std::size_t m_count;
  1746. std::string m_label;
  1747. };
  1748. }
  1749. // end catch_string_manip.h
  1750. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  1751. // start catch_capture_matchers.h
  1752. // start catch_matchers.h
  1753. #include <string>
  1754. #include <vector>
  1755. namespace Catch {
  1756. namespace Matchers {
  1757. namespace Impl {
  1758. template<typename ArgT> struct MatchAllOf;
  1759. template<typename ArgT> struct MatchAnyOf;
  1760. template<typename ArgT> struct MatchNotOf;
  1761. class MatcherUntypedBase {
  1762. public:
  1763. MatcherUntypedBase() = default;
  1764. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  1765. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  1766. std::string toString() const;
  1767. protected:
  1768. virtual ~MatcherUntypedBase();
  1769. virtual std::string describe() const = 0;
  1770. mutable std::string m_cachedToString;
  1771. };
  1772. template<typename ObjectT>
  1773. struct MatcherMethod {
  1774. virtual bool match( ObjectT const& arg ) const = 0;
  1775. };
  1776. template<typename PtrT>
  1777. struct MatcherMethod<PtrT*> {
  1778. virtual bool match( PtrT* arg ) const = 0;
  1779. };
  1780. template<typename T>
  1781. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  1782. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  1783. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  1784. MatchNotOf<T> operator ! () const;
  1785. };
  1786. template<typename ArgT>
  1787. struct MatchAllOf : MatcherBase<ArgT> {
  1788. bool match( ArgT const& arg ) const override {
  1789. for( auto matcher : m_matchers ) {
  1790. if (!matcher->match(arg))
  1791. return false;
  1792. }
  1793. return true;
  1794. }
  1795. std::string describe() const override {
  1796. std::string description;
  1797. description.reserve( 4 + m_matchers.size()*32 );
  1798. description += "( ";
  1799. bool first = true;
  1800. for( auto matcher : m_matchers ) {
  1801. if( first )
  1802. first = false;
  1803. else
  1804. description += " and ";
  1805. description += matcher->toString();
  1806. }
  1807. description += " )";
  1808. return description;
  1809. }
  1810. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  1811. m_matchers.push_back( &other );
  1812. return *this;
  1813. }
  1814. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1815. };
  1816. template<typename ArgT>
  1817. struct MatchAnyOf : MatcherBase<ArgT> {
  1818. bool match( ArgT const& arg ) const override {
  1819. for( auto matcher : m_matchers ) {
  1820. if (matcher->match(arg))
  1821. return true;
  1822. }
  1823. return false;
  1824. }
  1825. std::string describe() const override {
  1826. std::string description;
  1827. description.reserve( 4 + m_matchers.size()*32 );
  1828. description += "( ";
  1829. bool first = true;
  1830. for( auto matcher : m_matchers ) {
  1831. if( first )
  1832. first = false;
  1833. else
  1834. description += " or ";
  1835. description += matcher->toString();
  1836. }
  1837. description += " )";
  1838. return description;
  1839. }
  1840. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  1841. m_matchers.push_back( &other );
  1842. return *this;
  1843. }
  1844. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1845. };
  1846. template<typename ArgT>
  1847. struct MatchNotOf : MatcherBase<ArgT> {
  1848. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  1849. bool match( ArgT const& arg ) const override {
  1850. return !m_underlyingMatcher.match( arg );
  1851. }
  1852. std::string describe() const override {
  1853. return "not " + m_underlyingMatcher.toString();
  1854. }
  1855. MatcherBase<ArgT> const& m_underlyingMatcher;
  1856. };
  1857. template<typename T>
  1858. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  1859. return MatchAllOf<T>() && *this && other;
  1860. }
  1861. template<typename T>
  1862. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  1863. return MatchAnyOf<T>() || *this || other;
  1864. }
  1865. template<typename T>
  1866. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  1867. return MatchNotOf<T>( *this );
  1868. }
  1869. } // namespace Impl
  1870. } // namespace Matchers
  1871. using namespace Matchers;
  1872. using Matchers::Impl::MatcherBase;
  1873. } // namespace Catch
  1874. // end catch_matchers.h
  1875. // start catch_matchers_floating.h
  1876. #include <type_traits>
  1877. #include <cmath>
  1878. namespace Catch {
  1879. namespace Matchers {
  1880. namespace Floating {
  1881. enum class FloatingPointKind : uint8_t;
  1882. struct WithinAbsMatcher : MatcherBase<double> {
  1883. WithinAbsMatcher(double target, double margin);
  1884. bool match(double const& matchee) const override;
  1885. std::string describe() const override;
  1886. private:
  1887. double m_target;
  1888. double m_margin;
  1889. };
  1890. struct WithinUlpsMatcher : MatcherBase<double> {
  1891. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  1892. bool match(double const& matchee) const override;
  1893. std::string describe() const override;
  1894. private:
  1895. double m_target;
  1896. int m_ulps;
  1897. FloatingPointKind m_type;
  1898. };
  1899. } // namespace Floating
  1900. // The following functions create the actual matcher objects.
  1901. // This allows the types to be inferred
  1902. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  1903. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  1904. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  1905. } // namespace Matchers
  1906. } // namespace Catch
  1907. // end catch_matchers_floating.h
  1908. // start catch_matchers_string.h
  1909. #include <string>
  1910. namespace Catch {
  1911. namespace Matchers {
  1912. namespace StdString {
  1913. struct CasedString
  1914. {
  1915. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  1916. std::string adjustString( std::string const& str ) const;
  1917. std::string caseSensitivitySuffix() const;
  1918. CaseSensitive::Choice m_caseSensitivity;
  1919. std::string m_str;
  1920. };
  1921. struct StringMatcherBase : MatcherBase<std::string> {
  1922. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  1923. std::string describe() const override;
  1924. CasedString m_comparator;
  1925. std::string m_operation;
  1926. };
  1927. struct EqualsMatcher : StringMatcherBase {
  1928. EqualsMatcher( CasedString const& comparator );
  1929. bool match( std::string const& source ) const override;
  1930. };
  1931. struct ContainsMatcher : StringMatcherBase {
  1932. ContainsMatcher( CasedString const& comparator );
  1933. bool match( std::string const& source ) const override;
  1934. };
  1935. struct StartsWithMatcher : StringMatcherBase {
  1936. StartsWithMatcher( CasedString const& comparator );
  1937. bool match( std::string const& source ) const override;
  1938. };
  1939. struct EndsWithMatcher : StringMatcherBase {
  1940. EndsWithMatcher( CasedString const& comparator );
  1941. bool match( std::string const& source ) const override;
  1942. };
  1943. struct RegexMatcher : MatcherBase<std::string> {
  1944. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  1945. bool match( std::string const& matchee ) const override;
  1946. std::string describe() const override;
  1947. private:
  1948. std::string m_regex;
  1949. CaseSensitive::Choice m_caseSensitivity;
  1950. };
  1951. } // namespace StdString
  1952. // The following functions create the actual matcher objects.
  1953. // This allows the types to be inferred
  1954. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1955. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1956. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1957. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1958. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  1959. } // namespace Matchers
  1960. } // namespace Catch
  1961. // end catch_matchers_string.h
  1962. // start catch_matchers_vector.h
  1963. #include <algorithm>
  1964. namespace Catch {
  1965. namespace Matchers {
  1966. namespace Vector {
  1967. namespace Detail {
  1968. template <typename InputIterator, typename T>
  1969. size_t count(InputIterator first, InputIterator last, T const& item) {
  1970. size_t cnt = 0;
  1971. for (; first != last; ++first) {
  1972. if (*first == item) {
  1973. ++cnt;
  1974. }
  1975. }
  1976. return cnt;
  1977. }
  1978. template <typename InputIterator, typename T>
  1979. bool contains(InputIterator first, InputIterator last, T const& item) {
  1980. for (; first != last; ++first) {
  1981. if (*first == item) {
  1982. return true;
  1983. }
  1984. }
  1985. return false;
  1986. }
  1987. }
  1988. template<typename T>
  1989. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  1990. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  1991. bool match(std::vector<T> const &v) const override {
  1992. for (auto const& el : v) {
  1993. if (el == m_comparator) {
  1994. return true;
  1995. }
  1996. }
  1997. return false;
  1998. }
  1999. std::string describe() const override {
  2000. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2001. }
  2002. T const& m_comparator;
  2003. };
  2004. template<typename T>
  2005. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  2006. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2007. bool match(std::vector<T> const &v) const override {
  2008. // !TBD: see note in EqualsMatcher
  2009. if (m_comparator.size() > v.size())
  2010. return false;
  2011. for (auto const& comparator : m_comparator) {
  2012. auto present = false;
  2013. for (const auto& el : v) {
  2014. if (el == comparator) {
  2015. present = true;
  2016. break;
  2017. }
  2018. }
  2019. if (!present) {
  2020. return false;
  2021. }
  2022. }
  2023. return true;
  2024. }
  2025. std::string describe() const override {
  2026. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2027. }
  2028. std::vector<T> const& m_comparator;
  2029. };
  2030. template<typename T>
  2031. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  2032. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2033. bool match(std::vector<T> const &v) const override {
  2034. // !TBD: This currently works if all elements can be compared using !=
  2035. // - a more general approach would be via a compare template that defaults
  2036. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  2037. // - then just call that directly
  2038. if (m_comparator.size() != v.size())
  2039. return false;
  2040. for (std::size_t i = 0; i < v.size(); ++i)
  2041. if (m_comparator[i] != v[i])
  2042. return false;
  2043. return true;
  2044. }
  2045. std::string describe() const override {
  2046. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2047. }
  2048. std::vector<T> const& m_comparator;
  2049. };
  2050. template<typename T>
  2051. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2052. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2053. bool match(std::vector<T> const& vec) const override {
  2054. // Note: This is a reimplementation of std::is_permutation,
  2055. // because I don't want to include <algorithm> inside the common path
  2056. if (m_target.size() != vec.size()) {
  2057. return false;
  2058. }
  2059. auto lfirst = m_target.begin(), llast = m_target.end();
  2060. auto rfirst = vec.begin(), rlast = vec.end();
  2061. // Cut common prefix to optimize checking of permuted parts
  2062. while (lfirst != llast && *lfirst != *rfirst) {
  2063. ++lfirst; ++rfirst;
  2064. }
  2065. if (lfirst == llast) {
  2066. return true;
  2067. }
  2068. for (auto mid = lfirst; mid != llast; ++mid) {
  2069. // Skip already counted items
  2070. if (Detail::contains(lfirst, mid, *mid)) {
  2071. continue;
  2072. }
  2073. size_t num_vec = Detail::count(rfirst, rlast, *mid);
  2074. if (num_vec == 0 || Detail::count(lfirst, llast, *mid) != num_vec) {
  2075. return false;
  2076. }
  2077. }
  2078. return true;
  2079. }
  2080. std::string describe() const override {
  2081. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  2082. }
  2083. private:
  2084. std::vector<T> const& m_target;
  2085. };
  2086. } // namespace Vector
  2087. // The following functions create the actual matcher objects.
  2088. // This allows the types to be inferred
  2089. template<typename T>
  2090. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  2091. return Vector::ContainsMatcher<T>( comparator );
  2092. }
  2093. template<typename T>
  2094. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  2095. return Vector::ContainsElementMatcher<T>( comparator );
  2096. }
  2097. template<typename T>
  2098. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  2099. return Vector::EqualsMatcher<T>( comparator );
  2100. }
  2101. template<typename T>
  2102. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  2103. return Vector::UnorderedEqualsMatcher<T>(target);
  2104. }
  2105. } // namespace Matchers
  2106. } // namespace Catch
  2107. // end catch_matchers_vector.h
  2108. namespace Catch {
  2109. template<typename ArgT, typename MatcherT>
  2110. class MatchExpr : public ITransientExpression {
  2111. ArgT const& m_arg;
  2112. MatcherT m_matcher;
  2113. StringRef m_matcherString;
  2114. public:
  2115. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString )
  2116. : ITransientExpression{ true, matcher.match( arg ) },
  2117. m_arg( arg ),
  2118. m_matcher( matcher ),
  2119. m_matcherString( matcherString )
  2120. {}
  2121. void streamReconstructedExpression( std::ostream &os ) const override {
  2122. auto matcherAsString = m_matcher.toString();
  2123. os << Catch::Detail::stringify( m_arg ) << ' ';
  2124. if( matcherAsString == Detail::unprintableString )
  2125. os << m_matcherString;
  2126. else
  2127. os << matcherAsString;
  2128. }
  2129. };
  2130. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  2131. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString );
  2132. template<typename ArgT, typename MatcherT>
  2133. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString ) -> MatchExpr<ArgT, MatcherT> {
  2134. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  2135. }
  2136. } // namespace Catch
  2137. ///////////////////////////////////////////////////////////////////////////////
  2138. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  2139. do { \
  2140. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2141. INTERNAL_CATCH_TRY { \
  2142. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher ) ); \
  2143. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2144. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2145. } while( false )
  2146. ///////////////////////////////////////////////////////////////////////////////
  2147. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  2148. do { \
  2149. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2150. if( catchAssertionHandler.allowThrows() ) \
  2151. try { \
  2152. static_cast<void>(__VA_ARGS__ ); \
  2153. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2154. } \
  2155. catch( exceptionType const& ex ) { \
  2156. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher ) ); \
  2157. } \
  2158. catch( ... ) { \
  2159. catchAssertionHandler.handleUnexpectedInflightException(); \
  2160. } \
  2161. else \
  2162. catchAssertionHandler.handleThrowingCallSkipped(); \
  2163. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2164. } while( false )
  2165. // end catch_capture_matchers.h
  2166. #endif
  2167. // These files are included here so the single_include script doesn't put them
  2168. // in the conditionally compiled sections
  2169. // start catch_test_case_info.h
  2170. #include <string>
  2171. #include <vector>
  2172. #include <memory>
  2173. #ifdef __clang__
  2174. #pragma clang diagnostic push
  2175. #pragma clang diagnostic ignored "-Wpadded"
  2176. #endif
  2177. namespace Catch {
  2178. struct ITestInvoker;
  2179. struct TestCaseInfo {
  2180. enum SpecialProperties{
  2181. None = 0,
  2182. IsHidden = 1 << 1,
  2183. ShouldFail = 1 << 2,
  2184. MayFail = 1 << 3,
  2185. Throws = 1 << 4,
  2186. NonPortable = 1 << 5,
  2187. Benchmark = 1 << 6
  2188. };
  2189. TestCaseInfo( std::string const& _name,
  2190. std::string const& _className,
  2191. std::string const& _description,
  2192. std::vector<std::string> const& _tags,
  2193. SourceLineInfo const& _lineInfo );
  2194. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  2195. bool isHidden() const;
  2196. bool throws() const;
  2197. bool okToFail() const;
  2198. bool expectedToFail() const;
  2199. std::string tagsAsString() const;
  2200. std::string name;
  2201. std::string className;
  2202. std::string description;
  2203. std::vector<std::string> tags;
  2204. std::vector<std::string> lcaseTags;
  2205. SourceLineInfo lineInfo;
  2206. SpecialProperties properties;
  2207. };
  2208. class TestCase : public TestCaseInfo {
  2209. public:
  2210. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  2211. TestCase withName( std::string const& _newName ) const;
  2212. void invoke() const;
  2213. TestCaseInfo const& getTestCaseInfo() const;
  2214. bool operator == ( TestCase const& other ) const;
  2215. bool operator < ( TestCase const& other ) const;
  2216. private:
  2217. std::shared_ptr<ITestInvoker> test;
  2218. };
  2219. TestCase makeTestCase( ITestInvoker* testCase,
  2220. std::string const& className,
  2221. NameAndTags const& nameAndTags,
  2222. SourceLineInfo const& lineInfo );
  2223. }
  2224. #ifdef __clang__
  2225. #pragma clang diagnostic pop
  2226. #endif
  2227. // end catch_test_case_info.h
  2228. // start catch_interfaces_runner.h
  2229. namespace Catch {
  2230. struct IRunner {
  2231. virtual ~IRunner();
  2232. virtual bool aborting() const = 0;
  2233. };
  2234. }
  2235. // end catch_interfaces_runner.h
  2236. #ifdef __OBJC__
  2237. // start catch_objc.hpp
  2238. #import <objc/runtime.h>
  2239. #include <string>
  2240. // NB. Any general catch headers included here must be included
  2241. // in catch.hpp first to make sure they are included by the single
  2242. // header for non obj-usage
  2243. ///////////////////////////////////////////////////////////////////////////////
  2244. // This protocol is really only here for (self) documenting purposes, since
  2245. // all its methods are optional.
  2246. @protocol OcFixture
  2247. @optional
  2248. -(void) setUp;
  2249. -(void) tearDown;
  2250. @end
  2251. namespace Catch {
  2252. class OcMethod : public ITestInvoker {
  2253. public:
  2254. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  2255. virtual void invoke() const {
  2256. id obj = [[m_cls alloc] init];
  2257. performOptionalSelector( obj, @selector(setUp) );
  2258. performOptionalSelector( obj, m_sel );
  2259. performOptionalSelector( obj, @selector(tearDown) );
  2260. arcSafeRelease( obj );
  2261. }
  2262. private:
  2263. virtual ~OcMethod() {}
  2264. Class m_cls;
  2265. SEL m_sel;
  2266. };
  2267. namespace Detail{
  2268. inline std::string getAnnotation( Class cls,
  2269. std::string const& annotationName,
  2270. std::string const& testCaseName ) {
  2271. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  2272. SEL sel = NSSelectorFromString( selStr );
  2273. arcSafeRelease( selStr );
  2274. id value = performOptionalSelector( cls, sel );
  2275. if( value )
  2276. return [(NSString*)value UTF8String];
  2277. return "";
  2278. }
  2279. }
  2280. inline std::size_t registerTestMethods() {
  2281. std::size_t noTestMethods = 0;
  2282. int noClasses = objc_getClassList( nullptr, 0 );
  2283. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  2284. objc_getClassList( classes, noClasses );
  2285. for( int c = 0; c < noClasses; c++ ) {
  2286. Class cls = classes[c];
  2287. {
  2288. u_int count;
  2289. Method* methods = class_copyMethodList( cls, &count );
  2290. for( u_int m = 0; m < count ; m++ ) {
  2291. SEL selector = method_getName(methods[m]);
  2292. std::string methodName = sel_getName(selector);
  2293. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  2294. std::string testCaseName = methodName.substr( 15 );
  2295. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  2296. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  2297. const char* className = class_getName( cls );
  2298. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo("",0) ) );
  2299. noTestMethods++;
  2300. }
  2301. }
  2302. free(methods);
  2303. }
  2304. }
  2305. return noTestMethods;
  2306. }
  2307. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  2308. namespace Matchers {
  2309. namespace Impl {
  2310. namespace NSStringMatchers {
  2311. struct StringHolder : MatcherBase<NSString*>{
  2312. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  2313. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  2314. StringHolder() {
  2315. arcSafeRelease( m_substr );
  2316. }
  2317. bool match( NSString* arg ) const override {
  2318. return false;
  2319. }
  2320. NSString* CATCH_ARC_STRONG m_substr;
  2321. };
  2322. struct Equals : StringHolder {
  2323. Equals( NSString* substr ) : StringHolder( substr ){}
  2324. bool match( NSString* str ) const override {
  2325. return (str != nil || m_substr == nil ) &&
  2326. [str isEqualToString:m_substr];
  2327. }
  2328. std::string describe() const override {
  2329. return "equals string: " + Catch::Detail::stringify( m_substr );
  2330. }
  2331. };
  2332. struct Contains : StringHolder {
  2333. Contains( NSString* substr ) : StringHolder( substr ){}
  2334. bool match( NSString* str ) const {
  2335. return (str != nil || m_substr == nil ) &&
  2336. [str rangeOfString:m_substr].location != NSNotFound;
  2337. }
  2338. std::string describe() const override {
  2339. return "contains string: " + Catch::Detail::stringify( m_substr );
  2340. }
  2341. };
  2342. struct StartsWith : StringHolder {
  2343. StartsWith( NSString* substr ) : StringHolder( substr ){}
  2344. bool match( NSString* str ) const override {
  2345. return (str != nil || m_substr == nil ) &&
  2346. [str rangeOfString:m_substr].location == 0;
  2347. }
  2348. std::string describe() const override {
  2349. return "starts with: " + Catch::Detail::stringify( m_substr );
  2350. }
  2351. };
  2352. struct EndsWith : StringHolder {
  2353. EndsWith( NSString* substr ) : StringHolder( substr ){}
  2354. bool match( NSString* str ) const override {
  2355. return (str != nil || m_substr == nil ) &&
  2356. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  2357. }
  2358. std::string describe() const override {
  2359. return "ends with: " + Catch::Detail::stringify( m_substr );
  2360. }
  2361. };
  2362. } // namespace NSStringMatchers
  2363. } // namespace Impl
  2364. inline Impl::NSStringMatchers::Equals
  2365. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  2366. inline Impl::NSStringMatchers::Contains
  2367. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  2368. inline Impl::NSStringMatchers::StartsWith
  2369. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  2370. inline Impl::NSStringMatchers::EndsWith
  2371. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  2372. } // namespace Matchers
  2373. using namespace Matchers;
  2374. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  2375. } // namespace Catch
  2376. ///////////////////////////////////////////////////////////////////////////////
  2377. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  2378. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  2379. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  2380. { \
  2381. return @ name; \
  2382. } \
  2383. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  2384. { \
  2385. return @ desc; \
  2386. } \
  2387. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  2388. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  2389. // end catch_objc.hpp
  2390. #endif
  2391. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  2392. // start catch_external_interfaces.h
  2393. // start catch_reporter_bases.hpp
  2394. // start catch_interfaces_reporter.h
  2395. // start catch_config.hpp
  2396. // start catch_test_spec_parser.h
  2397. #ifdef __clang__
  2398. #pragma clang diagnostic push
  2399. #pragma clang diagnostic ignored "-Wpadded"
  2400. #endif
  2401. // start catch_test_spec.h
  2402. #ifdef __clang__
  2403. #pragma clang diagnostic push
  2404. #pragma clang diagnostic ignored "-Wpadded"
  2405. #endif
  2406. // start catch_wildcard_pattern.h
  2407. namespace Catch
  2408. {
  2409. class WildcardPattern {
  2410. enum WildcardPosition {
  2411. NoWildcard = 0,
  2412. WildcardAtStart = 1,
  2413. WildcardAtEnd = 2,
  2414. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  2415. };
  2416. public:
  2417. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  2418. virtual ~WildcardPattern() = default;
  2419. virtual bool matches( std::string const& str ) const;
  2420. private:
  2421. std::string adjustCase( std::string const& str ) const;
  2422. CaseSensitive::Choice m_caseSensitivity;
  2423. WildcardPosition m_wildcard = NoWildcard;
  2424. std::string m_pattern;
  2425. };
  2426. }
  2427. // end catch_wildcard_pattern.h
  2428. #include <string>
  2429. #include <vector>
  2430. #include <memory>
  2431. namespace Catch {
  2432. class TestSpec {
  2433. struct Pattern {
  2434. virtual ~Pattern();
  2435. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  2436. };
  2437. using PatternPtr = std::shared_ptr<Pattern>;
  2438. class NamePattern : public Pattern {
  2439. public:
  2440. NamePattern( std::string const& name );
  2441. virtual ~NamePattern();
  2442. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2443. private:
  2444. WildcardPattern m_wildcardPattern;
  2445. };
  2446. class TagPattern : public Pattern {
  2447. public:
  2448. TagPattern( std::string const& tag );
  2449. virtual ~TagPattern();
  2450. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2451. private:
  2452. std::string m_tag;
  2453. };
  2454. class ExcludedPattern : public Pattern {
  2455. public:
  2456. ExcludedPattern( PatternPtr const& underlyingPattern );
  2457. virtual ~ExcludedPattern();
  2458. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2459. private:
  2460. PatternPtr m_underlyingPattern;
  2461. };
  2462. struct Filter {
  2463. std::vector<PatternPtr> m_patterns;
  2464. bool matches( TestCaseInfo const& testCase ) const;
  2465. };
  2466. public:
  2467. bool hasFilters() const;
  2468. bool matches( TestCaseInfo const& testCase ) const;
  2469. private:
  2470. std::vector<Filter> m_filters;
  2471. friend class TestSpecParser;
  2472. };
  2473. }
  2474. #ifdef __clang__
  2475. #pragma clang diagnostic pop
  2476. #endif
  2477. // end catch_test_spec.h
  2478. // start catch_interfaces_tag_alias_registry.h
  2479. #include <string>
  2480. namespace Catch {
  2481. struct TagAlias;
  2482. struct ITagAliasRegistry {
  2483. virtual ~ITagAliasRegistry();
  2484. // Nullptr if not present
  2485. virtual TagAlias const* find( std::string const& alias ) const = 0;
  2486. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  2487. static ITagAliasRegistry const& get();
  2488. };
  2489. } // end namespace Catch
  2490. // end catch_interfaces_tag_alias_registry.h
  2491. namespace Catch {
  2492. class TestSpecParser {
  2493. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  2494. Mode m_mode = None;
  2495. bool m_exclusion = false;
  2496. std::size_t m_start = std::string::npos, m_pos = 0;
  2497. std::string m_arg;
  2498. std::vector<std::size_t> m_escapeChars;
  2499. TestSpec::Filter m_currentFilter;
  2500. TestSpec m_testSpec;
  2501. ITagAliasRegistry const* m_tagAliases = nullptr;
  2502. public:
  2503. TestSpecParser( ITagAliasRegistry const& tagAliases );
  2504. TestSpecParser& parse( std::string const& arg );
  2505. TestSpec testSpec();
  2506. private:
  2507. void visitChar( char c );
  2508. void startNewMode( Mode mode, std::size_t start );
  2509. void escape();
  2510. std::string subString() const;
  2511. template<typename T>
  2512. void addPattern() {
  2513. std::string token = subString();
  2514. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  2515. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  2516. m_escapeChars.clear();
  2517. if( startsWith( token, "exclude:" ) ) {
  2518. m_exclusion = true;
  2519. token = token.substr( 8 );
  2520. }
  2521. if( !token.empty() ) {
  2522. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  2523. if( m_exclusion )
  2524. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  2525. m_currentFilter.m_patterns.push_back( pattern );
  2526. }
  2527. m_exclusion = false;
  2528. m_mode = None;
  2529. }
  2530. void addFilter();
  2531. };
  2532. TestSpec parseTestSpec( std::string const& arg );
  2533. } // namespace Catch
  2534. #ifdef __clang__
  2535. #pragma clang diagnostic pop
  2536. #endif
  2537. // end catch_test_spec_parser.h
  2538. // start catch_interfaces_config.h
  2539. #include <iosfwd>
  2540. #include <string>
  2541. #include <vector>
  2542. #include <memory>
  2543. namespace Catch {
  2544. enum class Verbosity {
  2545. Quiet = 0,
  2546. Normal,
  2547. High
  2548. };
  2549. struct WarnAbout { enum What {
  2550. Nothing = 0x00,
  2551. NoAssertions = 0x01,
  2552. NoTests = 0x02
  2553. }; };
  2554. struct ShowDurations { enum OrNot {
  2555. DefaultForReporter,
  2556. Always,
  2557. Never
  2558. }; };
  2559. struct RunTests { enum InWhatOrder {
  2560. InDeclarationOrder,
  2561. InLexicographicalOrder,
  2562. InRandomOrder
  2563. }; };
  2564. struct UseColour { enum YesOrNo {
  2565. Auto,
  2566. Yes,
  2567. No
  2568. }; };
  2569. struct WaitForKeypress { enum When {
  2570. Never,
  2571. BeforeStart = 1,
  2572. BeforeExit = 2,
  2573. BeforeStartAndExit = BeforeStart | BeforeExit
  2574. }; };
  2575. class TestSpec;
  2576. struct IConfig : NonCopyable {
  2577. virtual ~IConfig();
  2578. virtual bool allowThrows() const = 0;
  2579. virtual std::ostream& stream() const = 0;
  2580. virtual std::string name() const = 0;
  2581. virtual bool includeSuccessfulResults() const = 0;
  2582. virtual bool shouldDebugBreak() const = 0;
  2583. virtual bool warnAboutMissingAssertions() const = 0;
  2584. virtual bool warnAboutNoTests() const = 0;
  2585. virtual int abortAfter() const = 0;
  2586. virtual bool showInvisibles() const = 0;
  2587. virtual ShowDurations::OrNot showDurations() const = 0;
  2588. virtual TestSpec const& testSpec() const = 0;
  2589. virtual bool hasTestFilters() const = 0;
  2590. virtual RunTests::InWhatOrder runOrder() const = 0;
  2591. virtual unsigned int rngSeed() const = 0;
  2592. virtual int benchmarkResolutionMultiple() const = 0;
  2593. virtual UseColour::YesOrNo useColour() const = 0;
  2594. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  2595. virtual Verbosity verbosity() const = 0;
  2596. };
  2597. using IConfigPtr = std::shared_ptr<IConfig const>;
  2598. }
  2599. // end catch_interfaces_config.h
  2600. // Libstdc++ doesn't like incomplete classes for unique_ptr
  2601. #include <memory>
  2602. #include <vector>
  2603. #include <string>
  2604. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  2605. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  2606. #endif
  2607. namespace Catch {
  2608. struct IStream;
  2609. struct ConfigData {
  2610. bool listTests = false;
  2611. bool listTags = false;
  2612. bool listReporters = false;
  2613. bool listTestNamesOnly = false;
  2614. bool showSuccessfulTests = false;
  2615. bool shouldDebugBreak = false;
  2616. bool noThrow = false;
  2617. bool showHelp = false;
  2618. bool showInvisibles = false;
  2619. bool filenamesAsTags = false;
  2620. bool libIdentify = false;
  2621. int abortAfter = -1;
  2622. unsigned int rngSeed = 0;
  2623. int benchmarkResolutionMultiple = 100;
  2624. Verbosity verbosity = Verbosity::Normal;
  2625. WarnAbout::What warnings = WarnAbout::Nothing;
  2626. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  2627. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  2628. UseColour::YesOrNo useColour = UseColour::Auto;
  2629. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  2630. std::string outputFilename;
  2631. std::string name;
  2632. std::string processName;
  2633. std::vector<std::string> reporterNames;
  2634. std::vector<std::string> testsOrTags;
  2635. std::vector<std::string> sectionsToRun;
  2636. };
  2637. class Config : public IConfig {
  2638. public:
  2639. Config() = default;
  2640. Config( ConfigData const& data );
  2641. virtual ~Config() = default;
  2642. std::string const& getFilename() const;
  2643. bool listTests() const;
  2644. bool listTestNamesOnly() const;
  2645. bool listTags() const;
  2646. bool listReporters() const;
  2647. std::string getProcessName() const;
  2648. std::vector<std::string> const& getReporterNames() const;
  2649. std::vector<std::string> const& getTestsOrTags() const;
  2650. std::vector<std::string> const& getSectionsToRun() const override;
  2651. virtual TestSpec const& testSpec() const override;
  2652. bool hasTestFilters() const override;
  2653. bool showHelp() const;
  2654. // IConfig interface
  2655. bool allowThrows() const override;
  2656. std::ostream& stream() const override;
  2657. std::string name() const override;
  2658. bool includeSuccessfulResults() const override;
  2659. bool warnAboutMissingAssertions() const override;
  2660. bool warnAboutNoTests() const override;
  2661. ShowDurations::OrNot showDurations() const override;
  2662. RunTests::InWhatOrder runOrder() const override;
  2663. unsigned int rngSeed() const override;
  2664. int benchmarkResolutionMultiple() const override;
  2665. UseColour::YesOrNo useColour() const override;
  2666. bool shouldDebugBreak() const override;
  2667. int abortAfter() const override;
  2668. bool showInvisibles() const override;
  2669. Verbosity verbosity() const override;
  2670. private:
  2671. IStream const* openStream();
  2672. ConfigData m_data;
  2673. std::unique_ptr<IStream const> m_stream;
  2674. TestSpec m_testSpec;
  2675. bool m_hasTestFilters = false;
  2676. };
  2677. } // end namespace Catch
  2678. // end catch_config.hpp
  2679. // start catch_assertionresult.h
  2680. #include <string>
  2681. namespace Catch {
  2682. struct AssertionResultData
  2683. {
  2684. AssertionResultData() = delete;
  2685. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  2686. std::string message;
  2687. mutable std::string reconstructedExpression;
  2688. LazyExpression lazyExpression;
  2689. ResultWas::OfType resultType;
  2690. std::string reconstructExpression() const;
  2691. };
  2692. class AssertionResult {
  2693. public:
  2694. AssertionResult() = delete;
  2695. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  2696. bool isOk() const;
  2697. bool succeeded() const;
  2698. ResultWas::OfType getResultType() const;
  2699. bool hasExpression() const;
  2700. bool hasMessage() const;
  2701. std::string getExpression() const;
  2702. std::string getExpressionInMacro() const;
  2703. bool hasExpandedExpression() const;
  2704. std::string getExpandedExpression() const;
  2705. std::string getMessage() const;
  2706. SourceLineInfo getSourceInfo() const;
  2707. StringRef getTestMacroName() const;
  2708. //protected:
  2709. AssertionInfo m_info;
  2710. AssertionResultData m_resultData;
  2711. };
  2712. } // end namespace Catch
  2713. // end catch_assertionresult.h
  2714. // start catch_option.hpp
  2715. namespace Catch {
  2716. // An optional type
  2717. template<typename T>
  2718. class Option {
  2719. public:
  2720. Option() : nullableValue( nullptr ) {}
  2721. Option( T const& _value )
  2722. : nullableValue( new( storage ) T( _value ) )
  2723. {}
  2724. Option( Option const& _other )
  2725. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  2726. {}
  2727. ~Option() {
  2728. reset();
  2729. }
  2730. Option& operator= ( Option const& _other ) {
  2731. if( &_other != this ) {
  2732. reset();
  2733. if( _other )
  2734. nullableValue = new( storage ) T( *_other );
  2735. }
  2736. return *this;
  2737. }
  2738. Option& operator = ( T const& _value ) {
  2739. reset();
  2740. nullableValue = new( storage ) T( _value );
  2741. return *this;
  2742. }
  2743. void reset() {
  2744. if( nullableValue )
  2745. nullableValue->~T();
  2746. nullableValue = nullptr;
  2747. }
  2748. T& operator*() { return *nullableValue; }
  2749. T const& operator*() const { return *nullableValue; }
  2750. T* operator->() { return nullableValue; }
  2751. const T* operator->() const { return nullableValue; }
  2752. T valueOr( T const& defaultValue ) const {
  2753. return nullableValue ? *nullableValue : defaultValue;
  2754. }
  2755. bool some() const { return nullableValue != nullptr; }
  2756. bool none() const { return nullableValue == nullptr; }
  2757. bool operator !() const { return nullableValue == nullptr; }
  2758. explicit operator bool() const {
  2759. return some();
  2760. }
  2761. private:
  2762. T *nullableValue;
  2763. alignas(alignof(T)) char storage[sizeof(T)];
  2764. };
  2765. } // end namespace Catch
  2766. // end catch_option.hpp
  2767. #include <string>
  2768. #include <iosfwd>
  2769. #include <map>
  2770. #include <set>
  2771. #include <memory>
  2772. namespace Catch {
  2773. struct ReporterConfig {
  2774. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  2775. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  2776. std::ostream& stream() const;
  2777. IConfigPtr fullConfig() const;
  2778. private:
  2779. std::ostream* m_stream;
  2780. IConfigPtr m_fullConfig;
  2781. };
  2782. struct ReporterPreferences {
  2783. bool shouldRedirectStdOut = false;
  2784. };
  2785. template<typename T>
  2786. struct LazyStat : Option<T> {
  2787. LazyStat& operator=( T const& _value ) {
  2788. Option<T>::operator=( _value );
  2789. used = false;
  2790. return *this;
  2791. }
  2792. void reset() {
  2793. Option<T>::reset();
  2794. used = false;
  2795. }
  2796. bool used = false;
  2797. };
  2798. struct TestRunInfo {
  2799. TestRunInfo( std::string const& _name );
  2800. std::string name;
  2801. };
  2802. struct GroupInfo {
  2803. GroupInfo( std::string const& _name,
  2804. std::size_t _groupIndex,
  2805. std::size_t _groupsCount );
  2806. std::string name;
  2807. std::size_t groupIndex;
  2808. std::size_t groupsCounts;
  2809. };
  2810. struct AssertionStats {
  2811. AssertionStats( AssertionResult const& _assertionResult,
  2812. std::vector<MessageInfo> const& _infoMessages,
  2813. Totals const& _totals );
  2814. AssertionStats( AssertionStats const& ) = default;
  2815. AssertionStats( AssertionStats && ) = default;
  2816. AssertionStats& operator = ( AssertionStats const& ) = default;
  2817. AssertionStats& operator = ( AssertionStats && ) = default;
  2818. virtual ~AssertionStats();
  2819. AssertionResult assertionResult;
  2820. std::vector<MessageInfo> infoMessages;
  2821. Totals totals;
  2822. };
  2823. struct SectionStats {
  2824. SectionStats( SectionInfo const& _sectionInfo,
  2825. Counts const& _assertions,
  2826. double _durationInSeconds,
  2827. bool _missingAssertions );
  2828. SectionStats( SectionStats const& ) = default;
  2829. SectionStats( SectionStats && ) = default;
  2830. SectionStats& operator = ( SectionStats const& ) = default;
  2831. SectionStats& operator = ( SectionStats && ) = default;
  2832. virtual ~SectionStats();
  2833. SectionInfo sectionInfo;
  2834. Counts assertions;
  2835. double durationInSeconds;
  2836. bool missingAssertions;
  2837. };
  2838. struct TestCaseStats {
  2839. TestCaseStats( TestCaseInfo const& _testInfo,
  2840. Totals const& _totals,
  2841. std::string const& _stdOut,
  2842. std::string const& _stdErr,
  2843. bool _aborting );
  2844. TestCaseStats( TestCaseStats const& ) = default;
  2845. TestCaseStats( TestCaseStats && ) = default;
  2846. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  2847. TestCaseStats& operator = ( TestCaseStats && ) = default;
  2848. virtual ~TestCaseStats();
  2849. TestCaseInfo testInfo;
  2850. Totals totals;
  2851. std::string stdOut;
  2852. std::string stdErr;
  2853. bool aborting;
  2854. };
  2855. struct TestGroupStats {
  2856. TestGroupStats( GroupInfo const& _groupInfo,
  2857. Totals const& _totals,
  2858. bool _aborting );
  2859. TestGroupStats( GroupInfo const& _groupInfo );
  2860. TestGroupStats( TestGroupStats const& ) = default;
  2861. TestGroupStats( TestGroupStats && ) = default;
  2862. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  2863. TestGroupStats& operator = ( TestGroupStats && ) = default;
  2864. virtual ~TestGroupStats();
  2865. GroupInfo groupInfo;
  2866. Totals totals;
  2867. bool aborting;
  2868. };
  2869. struct TestRunStats {
  2870. TestRunStats( TestRunInfo const& _runInfo,
  2871. Totals const& _totals,
  2872. bool _aborting );
  2873. TestRunStats( TestRunStats const& ) = default;
  2874. TestRunStats( TestRunStats && ) = default;
  2875. TestRunStats& operator = ( TestRunStats const& ) = default;
  2876. TestRunStats& operator = ( TestRunStats && ) = default;
  2877. virtual ~TestRunStats();
  2878. TestRunInfo runInfo;
  2879. Totals totals;
  2880. bool aborting;
  2881. };
  2882. struct BenchmarkInfo {
  2883. std::string name;
  2884. };
  2885. struct BenchmarkStats {
  2886. BenchmarkInfo info;
  2887. std::size_t iterations;
  2888. uint64_t elapsedTimeInNanoseconds;
  2889. };
  2890. struct IStreamingReporter {
  2891. virtual ~IStreamingReporter() = default;
  2892. // Implementing class must also provide the following static methods:
  2893. // static std::string getDescription();
  2894. // static std::set<Verbosity> getSupportedVerbosities()
  2895. virtual ReporterPreferences getPreferences() const = 0;
  2896. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  2897. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  2898. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  2899. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  2900. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  2901. // *** experimental ***
  2902. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  2903. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  2904. // The return value indicates if the messages buffer should be cleared:
  2905. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  2906. // *** experimental ***
  2907. virtual void benchmarkEnded( BenchmarkStats const& ) {}
  2908. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  2909. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  2910. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  2911. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  2912. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  2913. // Default empty implementation provided
  2914. virtual void fatalErrorEncountered( StringRef name );
  2915. virtual bool isMulti() const;
  2916. };
  2917. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  2918. struct IReporterFactory {
  2919. virtual ~IReporterFactory();
  2920. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  2921. virtual std::string getDescription() const = 0;
  2922. };
  2923. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  2924. struct IReporterRegistry {
  2925. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  2926. using Listeners = std::vector<IReporterFactoryPtr>;
  2927. virtual ~IReporterRegistry();
  2928. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  2929. virtual FactoryMap const& getFactories() const = 0;
  2930. virtual Listeners const& getListeners() const = 0;
  2931. };
  2932. void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter );
  2933. } // end namespace Catch
  2934. // end catch_interfaces_reporter.h
  2935. #include <algorithm>
  2936. #include <cstring>
  2937. #include <cfloat>
  2938. #include <cstdio>
  2939. #include <assert.h>
  2940. #include <memory>
  2941. #include <ostream>
  2942. namespace Catch {
  2943. void prepareExpandedExpression(AssertionResult& result);
  2944. // Returns double formatted as %.3f (format expected on output)
  2945. std::string getFormattedDuration( double duration );
  2946. template<typename DerivedT>
  2947. struct StreamingReporterBase : IStreamingReporter {
  2948. StreamingReporterBase( ReporterConfig const& _config )
  2949. : m_config( _config.fullConfig() ),
  2950. stream( _config.stream() )
  2951. {
  2952. m_reporterPrefs.shouldRedirectStdOut = false;
  2953. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  2954. throw std::domain_error( "Verbosity level not supported by this reporter" );
  2955. }
  2956. ReporterPreferences getPreferences() const override {
  2957. return m_reporterPrefs;
  2958. }
  2959. static std::set<Verbosity> getSupportedVerbosities() {
  2960. return { Verbosity::Normal };
  2961. }
  2962. ~StreamingReporterBase() override = default;
  2963. void noMatchingTestCases(std::string const&) override {}
  2964. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  2965. currentTestRunInfo = _testRunInfo;
  2966. }
  2967. void testGroupStarting(GroupInfo const& _groupInfo) override {
  2968. currentGroupInfo = _groupInfo;
  2969. }
  2970. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  2971. currentTestCaseInfo = _testInfo;
  2972. }
  2973. void sectionStarting(SectionInfo const& _sectionInfo) override {
  2974. m_sectionStack.push_back(_sectionInfo);
  2975. }
  2976. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  2977. m_sectionStack.pop_back();
  2978. }
  2979. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  2980. currentTestCaseInfo.reset();
  2981. }
  2982. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  2983. currentGroupInfo.reset();
  2984. }
  2985. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  2986. currentTestCaseInfo.reset();
  2987. currentGroupInfo.reset();
  2988. currentTestRunInfo.reset();
  2989. }
  2990. void skipTest(TestCaseInfo const&) override {
  2991. // Don't do anything with this by default.
  2992. // It can optionally be overridden in the derived class.
  2993. }
  2994. IConfigPtr m_config;
  2995. std::ostream& stream;
  2996. LazyStat<TestRunInfo> currentTestRunInfo;
  2997. LazyStat<GroupInfo> currentGroupInfo;
  2998. LazyStat<TestCaseInfo> currentTestCaseInfo;
  2999. std::vector<SectionInfo> m_sectionStack;
  3000. ReporterPreferences m_reporterPrefs;
  3001. };
  3002. template<typename DerivedT>
  3003. struct CumulativeReporterBase : IStreamingReporter {
  3004. template<typename T, typename ChildNodeT>
  3005. struct Node {
  3006. explicit Node( T const& _value ) : value( _value ) {}
  3007. virtual ~Node() {}
  3008. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  3009. T value;
  3010. ChildNodes children;
  3011. };
  3012. struct SectionNode {
  3013. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  3014. virtual ~SectionNode() = default;
  3015. bool operator == (SectionNode const& other) const {
  3016. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  3017. }
  3018. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  3019. return operator==(*other);
  3020. }
  3021. SectionStats stats;
  3022. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  3023. using Assertions = std::vector<AssertionStats>;
  3024. ChildSections childSections;
  3025. Assertions assertions;
  3026. std::string stdOut;
  3027. std::string stdErr;
  3028. };
  3029. struct BySectionInfo {
  3030. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  3031. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  3032. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  3033. return ((node->stats.sectionInfo.name == m_other.name) &&
  3034. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  3035. }
  3036. void operator=(BySectionInfo const&) = delete;
  3037. private:
  3038. SectionInfo const& m_other;
  3039. };
  3040. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  3041. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  3042. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  3043. CumulativeReporterBase( ReporterConfig const& _config )
  3044. : m_config( _config.fullConfig() ),
  3045. stream( _config.stream() )
  3046. {
  3047. m_reporterPrefs.shouldRedirectStdOut = false;
  3048. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3049. throw std::domain_error( "Verbosity level not supported by this reporter" );
  3050. }
  3051. ~CumulativeReporterBase() override = default;
  3052. ReporterPreferences getPreferences() const override {
  3053. return m_reporterPrefs;
  3054. }
  3055. static std::set<Verbosity> getSupportedVerbosities() {
  3056. return { Verbosity::Normal };
  3057. }
  3058. void testRunStarting( TestRunInfo const& ) override {}
  3059. void testGroupStarting( GroupInfo const& ) override {}
  3060. void testCaseStarting( TestCaseInfo const& ) override {}
  3061. void sectionStarting( SectionInfo const& sectionInfo ) override {
  3062. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  3063. std::shared_ptr<SectionNode> node;
  3064. if( m_sectionStack.empty() ) {
  3065. if( !m_rootSection )
  3066. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  3067. node = m_rootSection;
  3068. }
  3069. else {
  3070. SectionNode& parentNode = *m_sectionStack.back();
  3071. auto it =
  3072. std::find_if( parentNode.childSections.begin(),
  3073. parentNode.childSections.end(),
  3074. BySectionInfo( sectionInfo ) );
  3075. if( it == parentNode.childSections.end() ) {
  3076. node = std::make_shared<SectionNode>( incompleteStats );
  3077. parentNode.childSections.push_back( node );
  3078. }
  3079. else
  3080. node = *it;
  3081. }
  3082. m_sectionStack.push_back( node );
  3083. m_deepestSection = std::move(node);
  3084. }
  3085. void assertionStarting(AssertionInfo const&) override {}
  3086. bool assertionEnded(AssertionStats const& assertionStats) override {
  3087. assert(!m_sectionStack.empty());
  3088. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  3089. // which getExpandedExpression() calls to build the expression string.
  3090. // Our section stack copy of the assertionResult will likely outlive the
  3091. // temporary, so it must be expanded or discarded now to avoid calling
  3092. // a destroyed object later.
  3093. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  3094. SectionNode& sectionNode = *m_sectionStack.back();
  3095. sectionNode.assertions.push_back(assertionStats);
  3096. return true;
  3097. }
  3098. void sectionEnded(SectionStats const& sectionStats) override {
  3099. assert(!m_sectionStack.empty());
  3100. SectionNode& node = *m_sectionStack.back();
  3101. node.stats = sectionStats;
  3102. m_sectionStack.pop_back();
  3103. }
  3104. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  3105. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  3106. assert(m_sectionStack.size() == 0);
  3107. node->children.push_back(m_rootSection);
  3108. m_testCases.push_back(node);
  3109. m_rootSection.reset();
  3110. assert(m_deepestSection);
  3111. m_deepestSection->stdOut = testCaseStats.stdOut;
  3112. m_deepestSection->stdErr = testCaseStats.stdErr;
  3113. }
  3114. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  3115. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  3116. node->children.swap(m_testCases);
  3117. m_testGroups.push_back(node);
  3118. }
  3119. void testRunEnded(TestRunStats const& testRunStats) override {
  3120. auto node = std::make_shared<TestRunNode>(testRunStats);
  3121. node->children.swap(m_testGroups);
  3122. m_testRuns.push_back(node);
  3123. testRunEndedCumulative();
  3124. }
  3125. virtual void testRunEndedCumulative() = 0;
  3126. void skipTest(TestCaseInfo const&) override {}
  3127. IConfigPtr m_config;
  3128. std::ostream& stream;
  3129. std::vector<AssertionStats> m_assertions;
  3130. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  3131. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  3132. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  3133. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  3134. std::shared_ptr<SectionNode> m_rootSection;
  3135. std::shared_ptr<SectionNode> m_deepestSection;
  3136. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  3137. ReporterPreferences m_reporterPrefs;
  3138. };
  3139. template<char C>
  3140. char const* getLineOfChars() {
  3141. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  3142. if( !*line ) {
  3143. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  3144. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  3145. }
  3146. return line;
  3147. }
  3148. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  3149. TestEventListenerBase( ReporterConfig const& _config );
  3150. void assertionStarting(AssertionInfo const&) override;
  3151. bool assertionEnded(AssertionStats const&) override;
  3152. };
  3153. } // end namespace Catch
  3154. // end catch_reporter_bases.hpp
  3155. // start catch_console_colour.h
  3156. namespace Catch {
  3157. struct Colour {
  3158. enum Code {
  3159. None = 0,
  3160. White,
  3161. Red,
  3162. Green,
  3163. Blue,
  3164. Cyan,
  3165. Yellow,
  3166. Grey,
  3167. Bright = 0x10,
  3168. BrightRed = Bright | Red,
  3169. BrightGreen = Bright | Green,
  3170. LightGrey = Bright | Grey,
  3171. BrightWhite = Bright | White,
  3172. BrightYellow = Bright | Yellow,
  3173. // By intention
  3174. FileName = LightGrey,
  3175. Warning = BrightYellow,
  3176. ResultError = BrightRed,
  3177. ResultSuccess = BrightGreen,
  3178. ResultExpectedFailure = Warning,
  3179. Error = BrightRed,
  3180. Success = Green,
  3181. OriginalExpression = Cyan,
  3182. ReconstructedExpression = BrightYellow,
  3183. SecondaryText = LightGrey,
  3184. Headers = White
  3185. };
  3186. // Use constructed object for RAII guard
  3187. Colour( Code _colourCode );
  3188. Colour( Colour&& other ) noexcept;
  3189. Colour& operator=( Colour&& other ) noexcept;
  3190. ~Colour();
  3191. // Use static method for one-shot changes
  3192. static void use( Code _colourCode );
  3193. private:
  3194. bool m_moved = false;
  3195. };
  3196. std::ostream& operator << ( std::ostream& os, Colour const& );
  3197. } // end namespace Catch
  3198. // end catch_console_colour.h
  3199. // start catch_reporter_registrars.hpp
  3200. namespace Catch {
  3201. template<typename T>
  3202. class ReporterRegistrar {
  3203. class ReporterFactory : public IReporterFactory {
  3204. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3205. return std::unique_ptr<T>( new T( config ) );
  3206. }
  3207. virtual std::string getDescription() const override {
  3208. return T::getDescription();
  3209. }
  3210. };
  3211. public:
  3212. explicit ReporterRegistrar( std::string const& name ) {
  3213. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  3214. }
  3215. };
  3216. template<typename T>
  3217. class ListenerRegistrar {
  3218. class ListenerFactory : public IReporterFactory {
  3219. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3220. return std::unique_ptr<T>( new T( config ) );
  3221. }
  3222. virtual std::string getDescription() const override {
  3223. return std::string();
  3224. }
  3225. };
  3226. public:
  3227. ListenerRegistrar() {
  3228. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  3229. }
  3230. };
  3231. }
  3232. #if !defined(CATCH_CONFIG_DISABLE)
  3233. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  3234. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3235. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  3236. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  3237. #define CATCH_REGISTER_LISTENER( listenerType ) \
  3238. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3239. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  3240. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  3241. #else // CATCH_CONFIG_DISABLE
  3242. #define CATCH_REGISTER_REPORTER(name, reporterType)
  3243. #define CATCH_REGISTER_LISTENER(listenerType)
  3244. #endif // CATCH_CONFIG_DISABLE
  3245. // end catch_reporter_registrars.hpp
  3246. // Allow users to base their work off existing reporters
  3247. // start catch_reporter_compact.h
  3248. namespace Catch {
  3249. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  3250. using StreamingReporterBase::StreamingReporterBase;
  3251. ~CompactReporter() override;
  3252. static std::string getDescription();
  3253. ReporterPreferences getPreferences() const override;
  3254. void noMatchingTestCases(std::string const& spec) override;
  3255. void assertionStarting(AssertionInfo const&) override;
  3256. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3257. void sectionEnded(SectionStats const& _sectionStats) override;
  3258. void testRunEnded(TestRunStats const& _testRunStats) override;
  3259. };
  3260. } // end namespace Catch
  3261. // end catch_reporter_compact.h
  3262. // start catch_reporter_console.h
  3263. #if defined(_MSC_VER)
  3264. #pragma warning(push)
  3265. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  3266. // Note that 4062 (not all labels are handled
  3267. // and default is missing) is enabled
  3268. #endif
  3269. namespace Catch {
  3270. // Fwd decls
  3271. struct SummaryColumn;
  3272. class TablePrinter;
  3273. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  3274. std::unique_ptr<TablePrinter> m_tablePrinter;
  3275. ConsoleReporter(ReporterConfig const& config);
  3276. ~ConsoleReporter() override;
  3277. static std::string getDescription();
  3278. void noMatchingTestCases(std::string const& spec) override;
  3279. void assertionStarting(AssertionInfo const&) override;
  3280. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3281. void sectionStarting(SectionInfo const& _sectionInfo) override;
  3282. void sectionEnded(SectionStats const& _sectionStats) override;
  3283. void benchmarkStarting(BenchmarkInfo const& info) override;
  3284. void benchmarkEnded(BenchmarkStats const& stats) override;
  3285. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  3286. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  3287. void testRunEnded(TestRunStats const& _testRunStats) override;
  3288. private:
  3289. void lazyPrint();
  3290. void lazyPrintWithoutClosingBenchmarkTable();
  3291. void lazyPrintRunInfo();
  3292. void lazyPrintGroupInfo();
  3293. void printTestCaseAndSectionHeader();
  3294. void printClosedHeader(std::string const& _name);
  3295. void printOpenHeader(std::string const& _name);
  3296. // if string has a : in first line will set indent to follow it on
  3297. // subsequent lines
  3298. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  3299. void printTotals(Totals const& totals);
  3300. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  3301. void printTotalsDivider(Totals const& totals);
  3302. void printSummaryDivider();
  3303. private:
  3304. bool m_headerPrinted = false;
  3305. };
  3306. } // end namespace Catch
  3307. #if defined(_MSC_VER)
  3308. #pragma warning(pop)
  3309. #endif
  3310. // end catch_reporter_console.h
  3311. // start catch_reporter_junit.h
  3312. // start catch_xmlwriter.h
  3313. #include <vector>
  3314. namespace Catch {
  3315. class XmlEncode {
  3316. public:
  3317. enum ForWhat { ForTextNodes, ForAttributes };
  3318. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  3319. void encodeTo( std::ostream& os ) const;
  3320. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  3321. private:
  3322. std::string m_str;
  3323. ForWhat m_forWhat;
  3324. };
  3325. class XmlWriter {
  3326. public:
  3327. class ScopedElement {
  3328. public:
  3329. ScopedElement( XmlWriter* writer );
  3330. ScopedElement( ScopedElement&& other ) noexcept;
  3331. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  3332. ~ScopedElement();
  3333. ScopedElement& writeText( std::string const& text, bool indent = true );
  3334. template<typename T>
  3335. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  3336. m_writer->writeAttribute( name, attribute );
  3337. return *this;
  3338. }
  3339. private:
  3340. mutable XmlWriter* m_writer = nullptr;
  3341. };
  3342. XmlWriter( std::ostream& os = Catch::cout() );
  3343. ~XmlWriter();
  3344. XmlWriter( XmlWriter const& ) = delete;
  3345. XmlWriter& operator=( XmlWriter const& ) = delete;
  3346. XmlWriter& startElement( std::string const& name );
  3347. ScopedElement scopedElement( std::string const& name );
  3348. XmlWriter& endElement();
  3349. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  3350. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  3351. template<typename T>
  3352. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  3353. ReusableStringStream rss;
  3354. rss << attribute;
  3355. return writeAttribute( name, rss.str() );
  3356. }
  3357. XmlWriter& writeText( std::string const& text, bool indent = true );
  3358. XmlWriter& writeComment( std::string const& text );
  3359. void writeStylesheetRef( std::string const& url );
  3360. XmlWriter& writeBlankLine();
  3361. void ensureTagClosed();
  3362. private:
  3363. void writeDeclaration();
  3364. void newlineIfNecessary();
  3365. bool m_tagIsOpen = false;
  3366. bool m_needsNewline = false;
  3367. std::vector<std::string> m_tags;
  3368. std::string m_indent;
  3369. std::ostream& m_os;
  3370. };
  3371. }
  3372. // end catch_xmlwriter.h
  3373. namespace Catch {
  3374. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  3375. public:
  3376. JunitReporter(ReporterConfig const& _config);
  3377. ~JunitReporter() override;
  3378. static std::string getDescription();
  3379. void noMatchingTestCases(std::string const& /*spec*/) override;
  3380. void testRunStarting(TestRunInfo const& runInfo) override;
  3381. void testGroupStarting(GroupInfo const& groupInfo) override;
  3382. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  3383. bool assertionEnded(AssertionStats const& assertionStats) override;
  3384. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3385. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3386. void testRunEndedCumulative() override;
  3387. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  3388. void writeTestCase(TestCaseNode const& testCaseNode);
  3389. void writeSection(std::string const& className,
  3390. std::string const& rootName,
  3391. SectionNode const& sectionNode);
  3392. void writeAssertions(SectionNode const& sectionNode);
  3393. void writeAssertion(AssertionStats const& stats);
  3394. XmlWriter xml;
  3395. Timer suiteTimer;
  3396. std::string stdOutForSuite;
  3397. std::string stdErrForSuite;
  3398. unsigned int unexpectedExceptions = 0;
  3399. bool m_okToFail = false;
  3400. };
  3401. } // end namespace Catch
  3402. // end catch_reporter_junit.h
  3403. // start catch_reporter_xml.h
  3404. namespace Catch {
  3405. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  3406. public:
  3407. XmlReporter(ReporterConfig const& _config);
  3408. ~XmlReporter() override;
  3409. static std::string getDescription();
  3410. virtual std::string getStylesheetRef() const;
  3411. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  3412. public: // StreamingReporterBase
  3413. void noMatchingTestCases(std::string const& s) override;
  3414. void testRunStarting(TestRunInfo const& testInfo) override;
  3415. void testGroupStarting(GroupInfo const& groupInfo) override;
  3416. void testCaseStarting(TestCaseInfo const& testInfo) override;
  3417. void sectionStarting(SectionInfo const& sectionInfo) override;
  3418. void assertionStarting(AssertionInfo const&) override;
  3419. bool assertionEnded(AssertionStats const& assertionStats) override;
  3420. void sectionEnded(SectionStats const& sectionStats) override;
  3421. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3422. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3423. void testRunEnded(TestRunStats const& testRunStats) override;
  3424. private:
  3425. Timer m_testCaseTimer;
  3426. XmlWriter m_xml;
  3427. int m_sectionDepth = 0;
  3428. };
  3429. } // end namespace Catch
  3430. // end catch_reporter_xml.h
  3431. // end catch_external_interfaces.h
  3432. #endif
  3433. #endif // ! CATCH_CONFIG_IMPL_ONLY
  3434. #ifdef CATCH_IMPL
  3435. // start catch_impl.hpp
  3436. #ifdef __clang__
  3437. #pragma clang diagnostic push
  3438. #pragma clang diagnostic ignored "-Wweak-vtables"
  3439. #endif
  3440. // Keep these here for external reporters
  3441. // start catch_test_case_tracker.h
  3442. #include <string>
  3443. #include <vector>
  3444. #include <memory>
  3445. namespace Catch {
  3446. namespace TestCaseTracking {
  3447. struct NameAndLocation {
  3448. std::string name;
  3449. SourceLineInfo location;
  3450. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  3451. };
  3452. struct ITracker;
  3453. using ITrackerPtr = std::shared_ptr<ITracker>;
  3454. struct ITracker {
  3455. virtual ~ITracker();
  3456. // static queries
  3457. virtual NameAndLocation const& nameAndLocation() const = 0;
  3458. // dynamic queries
  3459. virtual bool isComplete() const = 0; // Successfully completed or failed
  3460. virtual bool isSuccessfullyCompleted() const = 0;
  3461. virtual bool isOpen() const = 0; // Started but not complete
  3462. virtual bool hasChildren() const = 0;
  3463. virtual ITracker& parent() = 0;
  3464. // actions
  3465. virtual void close() = 0; // Successfully complete
  3466. virtual void fail() = 0;
  3467. virtual void markAsNeedingAnotherRun() = 0;
  3468. virtual void addChild( ITrackerPtr const& child ) = 0;
  3469. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  3470. virtual void openChild() = 0;
  3471. // Debug/ checking
  3472. virtual bool isSectionTracker() const = 0;
  3473. virtual bool isIndexTracker() const = 0;
  3474. };
  3475. class TrackerContext {
  3476. enum RunState {
  3477. NotStarted,
  3478. Executing,
  3479. CompletedCycle
  3480. };
  3481. ITrackerPtr m_rootTracker;
  3482. ITracker* m_currentTracker = nullptr;
  3483. RunState m_runState = NotStarted;
  3484. public:
  3485. static TrackerContext& instance();
  3486. ITracker& startRun();
  3487. void endRun();
  3488. void startCycle();
  3489. void completeCycle();
  3490. bool completedCycle() const;
  3491. ITracker& currentTracker();
  3492. void setCurrentTracker( ITracker* tracker );
  3493. };
  3494. class TrackerBase : public ITracker {
  3495. protected:
  3496. enum CycleState {
  3497. NotStarted,
  3498. Executing,
  3499. ExecutingChildren,
  3500. NeedsAnotherRun,
  3501. CompletedSuccessfully,
  3502. Failed
  3503. };
  3504. class TrackerHasName {
  3505. NameAndLocation m_nameAndLocation;
  3506. public:
  3507. TrackerHasName( NameAndLocation const& nameAndLocation );
  3508. bool operator ()( ITrackerPtr const& tracker ) const;
  3509. };
  3510. using Children = std::vector<ITrackerPtr>;
  3511. NameAndLocation m_nameAndLocation;
  3512. TrackerContext& m_ctx;
  3513. ITracker* m_parent;
  3514. Children m_children;
  3515. CycleState m_runState = NotStarted;
  3516. public:
  3517. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3518. NameAndLocation const& nameAndLocation() const override;
  3519. bool isComplete() const override;
  3520. bool isSuccessfullyCompleted() const override;
  3521. bool isOpen() const override;
  3522. bool hasChildren() const override;
  3523. void addChild( ITrackerPtr const& child ) override;
  3524. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  3525. ITracker& parent() override;
  3526. void openChild() override;
  3527. bool isSectionTracker() const override;
  3528. bool isIndexTracker() const override;
  3529. void open();
  3530. void close() override;
  3531. void fail() override;
  3532. void markAsNeedingAnotherRun() override;
  3533. private:
  3534. void moveToParent();
  3535. void moveToThis();
  3536. };
  3537. class SectionTracker : public TrackerBase {
  3538. std::vector<std::string> m_filters;
  3539. public:
  3540. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3541. bool isSectionTracker() const override;
  3542. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  3543. void tryOpen();
  3544. void addInitialFilters( std::vector<std::string> const& filters );
  3545. void addNextFilters( std::vector<std::string> const& filters );
  3546. };
  3547. class IndexTracker : public TrackerBase {
  3548. int m_size;
  3549. int m_index = -1;
  3550. public:
  3551. IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size );
  3552. bool isIndexTracker() const override;
  3553. void close() override;
  3554. static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size );
  3555. int index() const;
  3556. void moveNext();
  3557. };
  3558. } // namespace TestCaseTracking
  3559. using TestCaseTracking::ITracker;
  3560. using TestCaseTracking::TrackerContext;
  3561. using TestCaseTracking::SectionTracker;
  3562. using TestCaseTracking::IndexTracker;
  3563. } // namespace Catch
  3564. // end catch_test_case_tracker.h
  3565. // start catch_leak_detector.h
  3566. namespace Catch {
  3567. struct LeakDetector {
  3568. LeakDetector();
  3569. };
  3570. }
  3571. // end catch_leak_detector.h
  3572. // Cpp files will be included in the single-header file here
  3573. // start catch_approx.cpp
  3574. #include <cmath>
  3575. #include <limits>
  3576. namespace {
  3577. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  3578. // But without the subtraction to allow for INFINITY in comparison
  3579. bool marginComparison(double lhs, double rhs, double margin) {
  3580. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  3581. }
  3582. }
  3583. namespace Catch {
  3584. namespace Detail {
  3585. Approx::Approx ( double value )
  3586. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  3587. m_margin( 0.0 ),
  3588. m_scale( 0.0 ),
  3589. m_value( value )
  3590. {}
  3591. Approx Approx::custom() {
  3592. return Approx( 0 );
  3593. }
  3594. std::string Approx::toString() const {
  3595. ReusableStringStream rss;
  3596. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  3597. return rss.str();
  3598. }
  3599. bool Approx::equalityComparisonImpl(const double other) const {
  3600. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  3601. // Thanks to Richard Harris for his help refining the scaled margin value
  3602. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  3603. }
  3604. } // end namespace Detail
  3605. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  3606. return value.toString();
  3607. }
  3608. } // end namespace Catch
  3609. // end catch_approx.cpp
  3610. // start catch_assertionhandler.cpp
  3611. // start catch_context.h
  3612. #include <memory>
  3613. namespace Catch {
  3614. struct IResultCapture;
  3615. struct IRunner;
  3616. struct IConfig;
  3617. struct IMutableContext;
  3618. using IConfigPtr = std::shared_ptr<IConfig const>;
  3619. struct IContext
  3620. {
  3621. virtual ~IContext();
  3622. virtual IResultCapture* getResultCapture() = 0;
  3623. virtual IRunner* getRunner() = 0;
  3624. virtual IConfigPtr const& getConfig() const = 0;
  3625. };
  3626. struct IMutableContext : IContext
  3627. {
  3628. virtual ~IMutableContext();
  3629. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3630. virtual void setRunner( IRunner* runner ) = 0;
  3631. virtual void setConfig( IConfigPtr const& config ) = 0;
  3632. private:
  3633. static IMutableContext *currentContext;
  3634. friend IMutableContext& getCurrentMutableContext();
  3635. friend void cleanUpContext();
  3636. static void createContext();
  3637. };
  3638. inline IMutableContext& getCurrentMutableContext()
  3639. {
  3640. if( !IMutableContext::currentContext )
  3641. IMutableContext::createContext();
  3642. return *IMutableContext::currentContext;
  3643. }
  3644. inline IContext& getCurrentContext()
  3645. {
  3646. return getCurrentMutableContext();
  3647. }
  3648. void cleanUpContext();
  3649. }
  3650. // end catch_context.h
  3651. // start catch_debugger.h
  3652. namespace Catch {
  3653. bool isDebuggerActive();
  3654. }
  3655. #ifdef CATCH_PLATFORM_MAC
  3656. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  3657. #elif defined(CATCH_PLATFORM_LINUX)
  3658. // If we can use inline assembler, do it because this allows us to break
  3659. // directly at the location of the failing check instead of breaking inside
  3660. // raise() called from it, i.e. one stack frame below.
  3661. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  3662. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  3663. #else // Fall back to the generic way.
  3664. #include <signal.h>
  3665. #define CATCH_TRAP() raise(SIGTRAP)
  3666. #endif
  3667. #elif defined(_MSC_VER)
  3668. #define CATCH_TRAP() __debugbreak()
  3669. #elif defined(__MINGW32__)
  3670. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  3671. #define CATCH_TRAP() DebugBreak()
  3672. #endif
  3673. #ifdef CATCH_TRAP
  3674. #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
  3675. #else
  3676. namespace Catch {
  3677. inline void doNothing() {}
  3678. }
  3679. #define CATCH_BREAK_INTO_DEBUGGER() Catch::doNothing()
  3680. #endif
  3681. // end catch_debugger.h
  3682. // start catch_run_context.h
  3683. // start catch_fatal_condition.h
  3684. // start catch_windows_h_proxy.h
  3685. #if defined(CATCH_PLATFORM_WINDOWS)
  3686. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  3687. # define CATCH_DEFINED_NOMINMAX
  3688. # define NOMINMAX
  3689. #endif
  3690. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  3691. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  3692. # define WIN32_LEAN_AND_MEAN
  3693. #endif
  3694. #ifdef __AFXDLL
  3695. #include <AfxWin.h>
  3696. #else
  3697. #include <windows.h>
  3698. #endif
  3699. #ifdef CATCH_DEFINED_NOMINMAX
  3700. # undef NOMINMAX
  3701. #endif
  3702. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  3703. # undef WIN32_LEAN_AND_MEAN
  3704. #endif
  3705. #endif // defined(CATCH_PLATFORM_WINDOWS)
  3706. // end catch_windows_h_proxy.h
  3707. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  3708. namespace Catch {
  3709. struct FatalConditionHandler {
  3710. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  3711. FatalConditionHandler();
  3712. static void reset();
  3713. ~FatalConditionHandler();
  3714. private:
  3715. static bool isSet;
  3716. static ULONG guaranteeSize;
  3717. static PVOID exceptionHandlerHandle;
  3718. };
  3719. } // namespace Catch
  3720. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  3721. #include <signal.h>
  3722. namespace Catch {
  3723. struct FatalConditionHandler {
  3724. static bool isSet;
  3725. static struct sigaction oldSigActions[];
  3726. static stack_t oldSigStack;
  3727. static char altStackMem[];
  3728. static void handleSignal( int sig );
  3729. FatalConditionHandler();
  3730. ~FatalConditionHandler();
  3731. static void reset();
  3732. };
  3733. } // namespace Catch
  3734. #else
  3735. namespace Catch {
  3736. struct FatalConditionHandler {
  3737. void reset();
  3738. };
  3739. }
  3740. #endif
  3741. // end catch_fatal_condition.h
  3742. #include <string>
  3743. namespace Catch {
  3744. struct IMutableContext;
  3745. ///////////////////////////////////////////////////////////////////////////
  3746. class RunContext : public IResultCapture, public IRunner {
  3747. public:
  3748. RunContext( RunContext const& ) = delete;
  3749. RunContext& operator =( RunContext const& ) = delete;
  3750. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  3751. ~RunContext() override;
  3752. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  3753. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  3754. Totals runTest(TestCase const& testCase);
  3755. IConfigPtr config() const;
  3756. IStreamingReporter& reporter() const;
  3757. public: // IResultCapture
  3758. // Assertion handlers
  3759. void handleExpr
  3760. ( AssertionInfo const& info,
  3761. ITransientExpression const& expr,
  3762. AssertionReaction& reaction ) override;
  3763. void handleMessage
  3764. ( AssertionInfo const& info,
  3765. ResultWas::OfType resultType,
  3766. StringRef const& message,
  3767. AssertionReaction& reaction ) override;
  3768. void handleUnexpectedExceptionNotThrown
  3769. ( AssertionInfo const& info,
  3770. AssertionReaction& reaction ) override;
  3771. void handleUnexpectedInflightException
  3772. ( AssertionInfo const& info,
  3773. std::string const& message,
  3774. AssertionReaction& reaction ) override;
  3775. void handleIncomplete
  3776. ( AssertionInfo const& info ) override;
  3777. void handleNonExpr
  3778. ( AssertionInfo const &info,
  3779. ResultWas::OfType resultType,
  3780. AssertionReaction &reaction ) override;
  3781. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  3782. void sectionEnded( SectionEndInfo const& endInfo ) override;
  3783. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  3784. void benchmarkStarting( BenchmarkInfo const& info ) override;
  3785. void benchmarkEnded( BenchmarkStats const& stats ) override;
  3786. void pushScopedMessage( MessageInfo const& message ) override;
  3787. void popScopedMessage( MessageInfo const& message ) override;
  3788. std::string getCurrentTestName() const override;
  3789. const AssertionResult* getLastResult() const override;
  3790. void exceptionEarlyReported() override;
  3791. void handleFatalErrorCondition( StringRef message ) override;
  3792. bool lastAssertionPassed() override;
  3793. void assertionPassed() override;
  3794. public:
  3795. // !TBD We need to do this another way!
  3796. bool aborting() const override;
  3797. private:
  3798. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  3799. void invokeActiveTestCase();
  3800. void resetAssertionInfo();
  3801. bool testForMissingAssertions( Counts& assertions );
  3802. void assertionEnded( AssertionResult const& result );
  3803. void reportExpr
  3804. ( AssertionInfo const &info,
  3805. ResultWas::OfType resultType,
  3806. ITransientExpression const *expr,
  3807. bool negated );
  3808. void populateReaction( AssertionReaction& reaction );
  3809. private:
  3810. void handleUnfinishedSections();
  3811. TestRunInfo m_runInfo;
  3812. IMutableContext& m_context;
  3813. TestCase const* m_activeTestCase = nullptr;
  3814. ITracker* m_testCaseTracker;
  3815. Option<AssertionResult> m_lastResult;
  3816. IConfigPtr m_config;
  3817. Totals m_totals;
  3818. IStreamingReporterPtr m_reporter;
  3819. std::vector<MessageInfo> m_messages;
  3820. AssertionInfo m_lastAssertionInfo;
  3821. std::vector<SectionEndInfo> m_unfinishedSections;
  3822. std::vector<ITracker*> m_activeSections;
  3823. TrackerContext m_trackerContext;
  3824. bool m_lastAssertionPassed = false;
  3825. bool m_shouldReportUnexpected = true;
  3826. bool m_includeSuccessfulResults;
  3827. };
  3828. } // end namespace Catch
  3829. // end catch_run_context.h
  3830. namespace Catch {
  3831. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  3832. expr.streamReconstructedExpression( os );
  3833. return os;
  3834. }
  3835. LazyExpression::LazyExpression( bool isNegated )
  3836. : m_isNegated( isNegated )
  3837. {}
  3838. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  3839. LazyExpression::operator bool() const {
  3840. return m_transientExpression != nullptr;
  3841. }
  3842. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  3843. if( lazyExpr.m_isNegated )
  3844. os << "!";
  3845. if( lazyExpr ) {
  3846. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  3847. os << "(" << *lazyExpr.m_transientExpression << ")";
  3848. else
  3849. os << *lazyExpr.m_transientExpression;
  3850. }
  3851. else {
  3852. os << "{** error - unchecked empty expression requested **}";
  3853. }
  3854. return os;
  3855. }
  3856. AssertionHandler::AssertionHandler
  3857. ( StringRef macroName,
  3858. SourceLineInfo const& lineInfo,
  3859. StringRef capturedExpression,
  3860. ResultDisposition::Flags resultDisposition )
  3861. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  3862. m_resultCapture( getResultCapture() )
  3863. {}
  3864. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  3865. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  3866. }
  3867. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  3868. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  3869. }
  3870. auto AssertionHandler::allowThrows() const -> bool {
  3871. return getCurrentContext().getConfig()->allowThrows();
  3872. }
  3873. void AssertionHandler::complete() {
  3874. setCompleted();
  3875. if( m_reaction.shouldDebugBreak ) {
  3876. // If you find your debugger stopping you here then go one level up on the
  3877. // call-stack for the code that caused it (typically a failed assertion)
  3878. // (To go back to the test and change execution, jump over the throw, next)
  3879. CATCH_BREAK_INTO_DEBUGGER();
  3880. }
  3881. if( m_reaction.shouldThrow )
  3882. throw Catch::TestFailureException();
  3883. }
  3884. void AssertionHandler::setCompleted() {
  3885. m_completed = true;
  3886. }
  3887. void AssertionHandler::handleUnexpectedInflightException() {
  3888. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  3889. }
  3890. void AssertionHandler::handleExceptionThrownAsExpected() {
  3891. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  3892. }
  3893. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  3894. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  3895. }
  3896. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  3897. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  3898. }
  3899. void AssertionHandler::handleThrowingCallSkipped() {
  3900. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  3901. }
  3902. // This is the overload that takes a string and infers the Equals matcher from it
  3903. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  3904. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString ) {
  3905. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  3906. }
  3907. } // namespace Catch
  3908. // end catch_assertionhandler.cpp
  3909. // start catch_assertionresult.cpp
  3910. namespace Catch {
  3911. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  3912. lazyExpression(_lazyExpression),
  3913. resultType(_resultType) {}
  3914. std::string AssertionResultData::reconstructExpression() const {
  3915. if( reconstructedExpression.empty() ) {
  3916. if( lazyExpression ) {
  3917. ReusableStringStream rss;
  3918. rss << lazyExpression;
  3919. reconstructedExpression = rss.str();
  3920. }
  3921. }
  3922. return reconstructedExpression;
  3923. }
  3924. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  3925. : m_info( info ),
  3926. m_resultData( data )
  3927. {}
  3928. // Result was a success
  3929. bool AssertionResult::succeeded() const {
  3930. return Catch::isOk( m_resultData.resultType );
  3931. }
  3932. // Result was a success, or failure is suppressed
  3933. bool AssertionResult::isOk() const {
  3934. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  3935. }
  3936. ResultWas::OfType AssertionResult::getResultType() const {
  3937. return m_resultData.resultType;
  3938. }
  3939. bool AssertionResult::hasExpression() const {
  3940. return m_info.capturedExpression[0] != 0;
  3941. }
  3942. bool AssertionResult::hasMessage() const {
  3943. return !m_resultData.message.empty();
  3944. }
  3945. std::string AssertionResult::getExpression() const {
  3946. if( isFalseTest( m_info.resultDisposition ) )
  3947. return "!(" + m_info.capturedExpression + ")";
  3948. else
  3949. return m_info.capturedExpression;
  3950. }
  3951. std::string AssertionResult::getExpressionInMacro() const {
  3952. std::string expr;
  3953. if( m_info.macroName[0] == 0 )
  3954. expr = m_info.capturedExpression;
  3955. else {
  3956. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  3957. expr += m_info.macroName;
  3958. expr += "( ";
  3959. expr += m_info.capturedExpression;
  3960. expr += " )";
  3961. }
  3962. return expr;
  3963. }
  3964. bool AssertionResult::hasExpandedExpression() const {
  3965. return hasExpression() && getExpandedExpression() != getExpression();
  3966. }
  3967. std::string AssertionResult::getExpandedExpression() const {
  3968. std::string expr = m_resultData.reconstructExpression();
  3969. return expr.empty()
  3970. ? getExpression()
  3971. : expr;
  3972. }
  3973. std::string AssertionResult::getMessage() const {
  3974. return m_resultData.message;
  3975. }
  3976. SourceLineInfo AssertionResult::getSourceInfo() const {
  3977. return m_info.lineInfo;
  3978. }
  3979. StringRef AssertionResult::getTestMacroName() const {
  3980. return m_info.macroName;
  3981. }
  3982. } // end namespace Catch
  3983. // end catch_assertionresult.cpp
  3984. // start catch_benchmark.cpp
  3985. namespace Catch {
  3986. auto BenchmarkLooper::getResolution() -> uint64_t {
  3987. return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
  3988. }
  3989. void BenchmarkLooper::reportStart() {
  3990. getResultCapture().benchmarkStarting( { m_name } );
  3991. }
  3992. auto BenchmarkLooper::needsMoreIterations() -> bool {
  3993. auto elapsed = m_timer.getElapsedNanoseconds();
  3994. // Exponentially increasing iterations until we're confident in our timer resolution
  3995. if( elapsed < m_resolution ) {
  3996. m_iterationsToRun *= 10;
  3997. return true;
  3998. }
  3999. getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
  4000. return false;
  4001. }
  4002. } // end namespace Catch
  4003. // end catch_benchmark.cpp
  4004. // start catch_capture_matchers.cpp
  4005. namespace Catch {
  4006. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  4007. // This is the general overload that takes a any string matcher
  4008. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  4009. // the Equals matcher (so the header does not mention matchers)
  4010. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString ) {
  4011. std::string exceptionMessage = Catch::translateActiveException();
  4012. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  4013. handler.handleExpr( expr );
  4014. }
  4015. } // namespace Catch
  4016. // end catch_capture_matchers.cpp
  4017. // start catch_commandline.cpp
  4018. // start catch_commandline.h
  4019. // start catch_clara.h
  4020. // Use Catch's value for console width (store Clara's off to the side, if present)
  4021. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  4022. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4023. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4024. #endif
  4025. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  4026. #ifdef __clang__
  4027. #pragma clang diagnostic push
  4028. #pragma clang diagnostic ignored "-Wweak-vtables"
  4029. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  4030. #pragma clang diagnostic ignored "-Wshadow"
  4031. #endif
  4032. // start clara.hpp
  4033. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  4034. //
  4035. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4036. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4037. //
  4038. // See https://github.com/philsquared/Clara for more details
  4039. // Clara v1.1.4
  4040. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4041. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  4042. #endif
  4043. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4044. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4045. #endif
  4046. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  4047. #ifdef __has_include
  4048. #if __has_include(<optional>) && __cplusplus >= 201703L
  4049. #include <optional>
  4050. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  4051. #endif
  4052. #endif
  4053. #endif
  4054. // ----------- #included from clara_textflow.hpp -----------
  4055. // TextFlowCpp
  4056. //
  4057. // A single-header library for wrapping and laying out basic text, by Phil Nash
  4058. //
  4059. // This work is licensed under the BSD 2-Clause license.
  4060. // See the accompanying LICENSE file, or the one at https://opensource.org/licenses/BSD-2-Clause
  4061. //
  4062. // This project is hosted at https://github.com/philsquared/textflowcpp
  4063. #include <cassert>
  4064. #include <ostream>
  4065. #include <sstream>
  4066. #include <vector>
  4067. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4068. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  4069. #endif
  4070. namespace Catch { namespace clara { namespace TextFlow {
  4071. inline auto isWhitespace( char c ) -> bool {
  4072. static std::string chars = " \t\n\r";
  4073. return chars.find( c ) != std::string::npos;
  4074. }
  4075. inline auto isBreakableBefore( char c ) -> bool {
  4076. static std::string chars = "[({<|";
  4077. return chars.find( c ) != std::string::npos;
  4078. }
  4079. inline auto isBreakableAfter( char c ) -> bool {
  4080. static std::string chars = "])}>.,:;*+-=&/\\";
  4081. return chars.find( c ) != std::string::npos;
  4082. }
  4083. class Columns;
  4084. class Column {
  4085. std::vector<std::string> m_strings;
  4086. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  4087. size_t m_indent = 0;
  4088. size_t m_initialIndent = std::string::npos;
  4089. public:
  4090. class iterator {
  4091. friend Column;
  4092. Column const& m_column;
  4093. size_t m_stringIndex = 0;
  4094. size_t m_pos = 0;
  4095. size_t m_len = 0;
  4096. size_t m_end = 0;
  4097. bool m_suffix = false;
  4098. iterator( Column const& column, size_t stringIndex )
  4099. : m_column( column ),
  4100. m_stringIndex( stringIndex )
  4101. {}
  4102. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  4103. auto isBoundary( size_t at ) const -> bool {
  4104. assert( at > 0 );
  4105. assert( at <= line().size() );
  4106. return at == line().size() ||
  4107. ( isWhitespace( line()[at] ) && !isWhitespace( line()[at-1] ) ) ||
  4108. isBreakableBefore( line()[at] ) ||
  4109. isBreakableAfter( line()[at-1] );
  4110. }
  4111. void calcLength() {
  4112. assert( m_stringIndex < m_column.m_strings.size() );
  4113. m_suffix = false;
  4114. auto width = m_column.m_width-indent();
  4115. m_end = m_pos;
  4116. while( m_end < line().size() && line()[m_end] != '\n' )
  4117. ++m_end;
  4118. if( m_end < m_pos + width ) {
  4119. m_len = m_end - m_pos;
  4120. }
  4121. else {
  4122. size_t len = width;
  4123. while (len > 0 && !isBoundary(m_pos + len))
  4124. --len;
  4125. while (len > 0 && isWhitespace( line()[m_pos + len - 1] ))
  4126. --len;
  4127. if (len > 0) {
  4128. m_len = len;
  4129. } else {
  4130. m_suffix = true;
  4131. m_len = width - 1;
  4132. }
  4133. }
  4134. }
  4135. auto indent() const -> size_t {
  4136. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  4137. return initial == std::string::npos ? m_column.m_indent : initial;
  4138. }
  4139. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  4140. return std::string( indent(), ' ' ) + (m_suffix ? plain + "-" : plain);
  4141. }
  4142. public:
  4143. explicit iterator( Column const& column ) : m_column( column ) {
  4144. assert( m_column.m_width > m_column.m_indent );
  4145. assert( m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent );
  4146. calcLength();
  4147. if( m_len == 0 )
  4148. m_stringIndex++; // Empty string
  4149. }
  4150. auto operator *() const -> std::string {
  4151. assert( m_stringIndex < m_column.m_strings.size() );
  4152. assert( m_pos <= m_end );
  4153. if( m_pos + m_column.m_width < m_end )
  4154. return addIndentAndSuffix(line().substr(m_pos, m_len));
  4155. else
  4156. return addIndentAndSuffix(line().substr(m_pos, m_end - m_pos));
  4157. }
  4158. auto operator ++() -> iterator& {
  4159. m_pos += m_len;
  4160. if( m_pos < line().size() && line()[m_pos] == '\n' )
  4161. m_pos += 1;
  4162. else
  4163. while( m_pos < line().size() && isWhitespace( line()[m_pos] ) )
  4164. ++m_pos;
  4165. if( m_pos == line().size() ) {
  4166. m_pos = 0;
  4167. ++m_stringIndex;
  4168. }
  4169. if( m_stringIndex < m_column.m_strings.size() )
  4170. calcLength();
  4171. return *this;
  4172. }
  4173. auto operator ++(int) -> iterator {
  4174. iterator prev( *this );
  4175. operator++();
  4176. return prev;
  4177. }
  4178. auto operator ==( iterator const& other ) const -> bool {
  4179. return
  4180. m_pos == other.m_pos &&
  4181. m_stringIndex == other.m_stringIndex &&
  4182. &m_column == &other.m_column;
  4183. }
  4184. auto operator !=( iterator const& other ) const -> bool {
  4185. return !operator==( other );
  4186. }
  4187. };
  4188. using const_iterator = iterator;
  4189. explicit Column( std::string const& text ) { m_strings.push_back( text ); }
  4190. auto width( size_t newWidth ) -> Column& {
  4191. assert( newWidth > 0 );
  4192. m_width = newWidth;
  4193. return *this;
  4194. }
  4195. auto indent( size_t newIndent ) -> Column& {
  4196. m_indent = newIndent;
  4197. return *this;
  4198. }
  4199. auto initialIndent( size_t newIndent ) -> Column& {
  4200. m_initialIndent = newIndent;
  4201. return *this;
  4202. }
  4203. auto width() const -> size_t { return m_width; }
  4204. auto begin() const -> iterator { return iterator( *this ); }
  4205. auto end() const -> iterator { return { *this, m_strings.size() }; }
  4206. inline friend std::ostream& operator << ( std::ostream& os, Column const& col ) {
  4207. bool first = true;
  4208. for( auto line : col ) {
  4209. if( first )
  4210. first = false;
  4211. else
  4212. os << "\n";
  4213. os << line;
  4214. }
  4215. return os;
  4216. }
  4217. auto operator + ( Column const& other ) -> Columns;
  4218. auto toString() const -> std::string {
  4219. std::ostringstream oss;
  4220. oss << *this;
  4221. return oss.str();
  4222. }
  4223. };
  4224. class Spacer : public Column {
  4225. public:
  4226. explicit Spacer( size_t spaceWidth ) : Column( "" ) {
  4227. width( spaceWidth );
  4228. }
  4229. };
  4230. class Columns {
  4231. std::vector<Column> m_columns;
  4232. public:
  4233. class iterator {
  4234. friend Columns;
  4235. struct EndTag {};
  4236. std::vector<Column> const& m_columns;
  4237. std::vector<Column::iterator> m_iterators;
  4238. size_t m_activeIterators;
  4239. iterator( Columns const& columns, EndTag )
  4240. : m_columns( columns.m_columns ),
  4241. m_activeIterators( 0 )
  4242. {
  4243. m_iterators.reserve( m_columns.size() );
  4244. for( auto const& col : m_columns )
  4245. m_iterators.push_back( col.end() );
  4246. }
  4247. public:
  4248. explicit iterator( Columns const& columns )
  4249. : m_columns( columns.m_columns ),
  4250. m_activeIterators( m_columns.size() )
  4251. {
  4252. m_iterators.reserve( m_columns.size() );
  4253. for( auto const& col : m_columns )
  4254. m_iterators.push_back( col.begin() );
  4255. }
  4256. auto operator ==( iterator const& other ) const -> bool {
  4257. return m_iterators == other.m_iterators;
  4258. }
  4259. auto operator !=( iterator const& other ) const -> bool {
  4260. return m_iterators != other.m_iterators;
  4261. }
  4262. auto operator *() const -> std::string {
  4263. std::string row, padding;
  4264. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4265. auto width = m_columns[i].width();
  4266. if( m_iterators[i] != m_columns[i].end() ) {
  4267. std::string col = *m_iterators[i];
  4268. row += padding + col;
  4269. if( col.size() < width )
  4270. padding = std::string( width - col.size(), ' ' );
  4271. else
  4272. padding = "";
  4273. }
  4274. else {
  4275. padding += std::string( width, ' ' );
  4276. }
  4277. }
  4278. return row;
  4279. }
  4280. auto operator ++() -> iterator& {
  4281. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4282. if (m_iterators[i] != m_columns[i].end())
  4283. ++m_iterators[i];
  4284. }
  4285. return *this;
  4286. }
  4287. auto operator ++(int) -> iterator {
  4288. iterator prev( *this );
  4289. operator++();
  4290. return prev;
  4291. }
  4292. };
  4293. using const_iterator = iterator;
  4294. auto begin() const -> iterator { return iterator( *this ); }
  4295. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  4296. auto operator += ( Column const& col ) -> Columns& {
  4297. m_columns.push_back( col );
  4298. return *this;
  4299. }
  4300. auto operator + ( Column const& col ) -> Columns {
  4301. Columns combined = *this;
  4302. combined += col;
  4303. return combined;
  4304. }
  4305. inline friend std::ostream& operator << ( std::ostream& os, Columns const& cols ) {
  4306. bool first = true;
  4307. for( auto line : cols ) {
  4308. if( first )
  4309. first = false;
  4310. else
  4311. os << "\n";
  4312. os << line;
  4313. }
  4314. return os;
  4315. }
  4316. auto toString() const -> std::string {
  4317. std::ostringstream oss;
  4318. oss << *this;
  4319. return oss.str();
  4320. }
  4321. };
  4322. inline auto Column::operator + ( Column const& other ) -> Columns {
  4323. Columns cols;
  4324. cols += *this;
  4325. cols += other;
  4326. return cols;
  4327. }
  4328. }}} // namespace Catch::clara::TextFlow
  4329. // ----------- end of #include from clara_textflow.hpp -----------
  4330. // ........... back in clara.hpp
  4331. #include <memory>
  4332. #include <set>
  4333. #include <algorithm>
  4334. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  4335. #define CATCH_PLATFORM_WINDOWS
  4336. #endif
  4337. namespace Catch { namespace clara {
  4338. namespace detail {
  4339. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  4340. template<typename L>
  4341. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  4342. template<typename ClassT, typename ReturnT, typename... Args>
  4343. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  4344. static const bool isValid = false;
  4345. };
  4346. template<typename ClassT, typename ReturnT, typename ArgT>
  4347. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  4348. static const bool isValid = true;
  4349. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  4350. using ReturnType = ReturnT;
  4351. };
  4352. class TokenStream;
  4353. // Transport for raw args (copied from main args, or supplied via init list for testing)
  4354. class Args {
  4355. friend TokenStream;
  4356. std::string m_exeName;
  4357. std::vector<std::string> m_args;
  4358. public:
  4359. Args( int argc, char const* const* argv )
  4360. : m_exeName(argv[0]),
  4361. m_args(argv + 1, argv + argc) {}
  4362. Args( std::initializer_list<std::string> args )
  4363. : m_exeName( *args.begin() ),
  4364. m_args( args.begin()+1, args.end() )
  4365. {}
  4366. auto exeName() const -> std::string {
  4367. return m_exeName;
  4368. }
  4369. };
  4370. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  4371. // may encode an option + its argument if the : or = form is used
  4372. enum class TokenType {
  4373. Option, Argument
  4374. };
  4375. struct Token {
  4376. TokenType type;
  4377. std::string token;
  4378. };
  4379. inline auto isOptPrefix( char c ) -> bool {
  4380. return c == '-'
  4381. #ifdef CATCH_PLATFORM_WINDOWS
  4382. || c == '/'
  4383. #endif
  4384. ;
  4385. }
  4386. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  4387. class TokenStream {
  4388. using Iterator = std::vector<std::string>::const_iterator;
  4389. Iterator it;
  4390. Iterator itEnd;
  4391. std::vector<Token> m_tokenBuffer;
  4392. void loadBuffer() {
  4393. m_tokenBuffer.resize( 0 );
  4394. // Skip any empty strings
  4395. while( it != itEnd && it->empty() )
  4396. ++it;
  4397. if( it != itEnd ) {
  4398. auto const &next = *it;
  4399. if( isOptPrefix( next[0] ) ) {
  4400. auto delimiterPos = next.find_first_of( " :=" );
  4401. if( delimiterPos != std::string::npos ) {
  4402. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  4403. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  4404. } else {
  4405. if( next[1] != '-' && next.size() > 2 ) {
  4406. std::string opt = "- ";
  4407. for( size_t i = 1; i < next.size(); ++i ) {
  4408. opt[1] = next[i];
  4409. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  4410. }
  4411. } else {
  4412. m_tokenBuffer.push_back( { TokenType::Option, next } );
  4413. }
  4414. }
  4415. } else {
  4416. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  4417. }
  4418. }
  4419. }
  4420. public:
  4421. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  4422. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  4423. loadBuffer();
  4424. }
  4425. explicit operator bool() const {
  4426. return !m_tokenBuffer.empty() || it != itEnd;
  4427. }
  4428. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  4429. auto operator*() const -> Token {
  4430. assert( !m_tokenBuffer.empty() );
  4431. return m_tokenBuffer.front();
  4432. }
  4433. auto operator->() const -> Token const * {
  4434. assert( !m_tokenBuffer.empty() );
  4435. return &m_tokenBuffer.front();
  4436. }
  4437. auto operator++() -> TokenStream & {
  4438. if( m_tokenBuffer.size() >= 2 ) {
  4439. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  4440. } else {
  4441. if( it != itEnd )
  4442. ++it;
  4443. loadBuffer();
  4444. }
  4445. return *this;
  4446. }
  4447. };
  4448. class ResultBase {
  4449. public:
  4450. enum Type {
  4451. Ok, LogicError, RuntimeError
  4452. };
  4453. protected:
  4454. ResultBase( Type type ) : m_type( type ) {}
  4455. virtual ~ResultBase() = default;
  4456. virtual void enforceOk() const = 0;
  4457. Type m_type;
  4458. };
  4459. template<typename T>
  4460. class ResultValueBase : public ResultBase {
  4461. public:
  4462. auto value() const -> T const & {
  4463. enforceOk();
  4464. return m_value;
  4465. }
  4466. protected:
  4467. ResultValueBase( Type type ) : ResultBase( type ) {}
  4468. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  4469. if( m_type == ResultBase::Ok )
  4470. new( &m_value ) T( other.m_value );
  4471. }
  4472. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  4473. new( &m_value ) T( value );
  4474. }
  4475. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  4476. if( m_type == ResultBase::Ok )
  4477. m_value.~T();
  4478. ResultBase::operator=(other);
  4479. if( m_type == ResultBase::Ok )
  4480. new( &m_value ) T( other.m_value );
  4481. return *this;
  4482. }
  4483. ~ResultValueBase() override {
  4484. if( m_type == Ok )
  4485. m_value.~T();
  4486. }
  4487. union {
  4488. T m_value;
  4489. };
  4490. };
  4491. template<>
  4492. class ResultValueBase<void> : public ResultBase {
  4493. protected:
  4494. using ResultBase::ResultBase;
  4495. };
  4496. template<typename T = void>
  4497. class BasicResult : public ResultValueBase<T> {
  4498. public:
  4499. template<typename U>
  4500. explicit BasicResult( BasicResult<U> const &other )
  4501. : ResultValueBase<T>( other.type() ),
  4502. m_errorMessage( other.errorMessage() )
  4503. {
  4504. assert( type() != ResultBase::Ok );
  4505. }
  4506. template<typename U>
  4507. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  4508. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  4509. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  4510. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  4511. explicit operator bool() const { return m_type == ResultBase::Ok; }
  4512. auto type() const -> ResultBase::Type { return m_type; }
  4513. auto errorMessage() const -> std::string { return m_errorMessage; }
  4514. protected:
  4515. void enforceOk() const override {
  4516. // Errors shouldn't reach this point, but if they do
  4517. // the actual error message will be in m_errorMessage
  4518. assert( m_type != ResultBase::LogicError );
  4519. assert( m_type != ResultBase::RuntimeError );
  4520. if( m_type != ResultBase::Ok )
  4521. std::abort();
  4522. }
  4523. std::string m_errorMessage; // Only populated if resultType is an error
  4524. BasicResult( ResultBase::Type type, std::string const &message )
  4525. : ResultValueBase<T>(type),
  4526. m_errorMessage(message)
  4527. {
  4528. assert( m_type != ResultBase::Ok );
  4529. }
  4530. using ResultValueBase<T>::ResultValueBase;
  4531. using ResultBase::m_type;
  4532. };
  4533. enum class ParseResultType {
  4534. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  4535. };
  4536. class ParseState {
  4537. public:
  4538. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  4539. : m_type(type),
  4540. m_remainingTokens( remainingTokens )
  4541. {}
  4542. auto type() const -> ParseResultType { return m_type; }
  4543. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  4544. private:
  4545. ParseResultType m_type;
  4546. TokenStream m_remainingTokens;
  4547. };
  4548. using Result = BasicResult<void>;
  4549. using ParserResult = BasicResult<ParseResultType>;
  4550. using InternalParseResult = BasicResult<ParseState>;
  4551. struct HelpColumns {
  4552. std::string left;
  4553. std::string right;
  4554. };
  4555. template<typename T>
  4556. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  4557. std::stringstream ss;
  4558. ss << source;
  4559. ss >> target;
  4560. if( ss.fail() )
  4561. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  4562. else
  4563. return ParserResult::ok( ParseResultType::Matched );
  4564. }
  4565. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  4566. target = source;
  4567. return ParserResult::ok( ParseResultType::Matched );
  4568. }
  4569. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  4570. std::string srcLC = source;
  4571. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( ::tolower(c) ); } );
  4572. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  4573. target = true;
  4574. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  4575. target = false;
  4576. else
  4577. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  4578. return ParserResult::ok( ParseResultType::Matched );
  4579. }
  4580. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  4581. template<typename T>
  4582. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  4583. T temp;
  4584. auto result = convertInto( source, temp );
  4585. if( result )
  4586. target = std::move(temp);
  4587. return result;
  4588. }
  4589. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  4590. struct NonCopyable {
  4591. NonCopyable() = default;
  4592. NonCopyable( NonCopyable const & ) = delete;
  4593. NonCopyable( NonCopyable && ) = delete;
  4594. NonCopyable &operator=( NonCopyable const & ) = delete;
  4595. NonCopyable &operator=( NonCopyable && ) = delete;
  4596. };
  4597. struct BoundRef : NonCopyable {
  4598. virtual ~BoundRef() = default;
  4599. virtual auto isContainer() const -> bool { return false; }
  4600. virtual auto isFlag() const -> bool { return false; }
  4601. };
  4602. struct BoundValueRefBase : BoundRef {
  4603. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  4604. };
  4605. struct BoundFlagRefBase : BoundRef {
  4606. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  4607. virtual auto isFlag() const -> bool { return true; }
  4608. };
  4609. template<typename T>
  4610. struct BoundValueRef : BoundValueRefBase {
  4611. T &m_ref;
  4612. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  4613. auto setValue( std::string const &arg ) -> ParserResult override {
  4614. return convertInto( arg, m_ref );
  4615. }
  4616. };
  4617. template<typename T>
  4618. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  4619. std::vector<T> &m_ref;
  4620. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  4621. auto isContainer() const -> bool override { return true; }
  4622. auto setValue( std::string const &arg ) -> ParserResult override {
  4623. T temp;
  4624. auto result = convertInto( arg, temp );
  4625. if( result )
  4626. m_ref.push_back( temp );
  4627. return result;
  4628. }
  4629. };
  4630. struct BoundFlagRef : BoundFlagRefBase {
  4631. bool &m_ref;
  4632. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  4633. auto setFlag( bool flag ) -> ParserResult override {
  4634. m_ref = flag;
  4635. return ParserResult::ok( ParseResultType::Matched );
  4636. }
  4637. };
  4638. template<typename ReturnType>
  4639. struct LambdaInvoker {
  4640. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  4641. template<typename L, typename ArgType>
  4642. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4643. return lambda( arg );
  4644. }
  4645. };
  4646. template<>
  4647. struct LambdaInvoker<void> {
  4648. template<typename L, typename ArgType>
  4649. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4650. lambda( arg );
  4651. return ParserResult::ok( ParseResultType::Matched );
  4652. }
  4653. };
  4654. template<typename ArgType, typename L>
  4655. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  4656. ArgType temp{};
  4657. auto result = convertInto( arg, temp );
  4658. return !result
  4659. ? result
  4660. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  4661. }
  4662. template<typename L>
  4663. struct BoundLambda : BoundValueRefBase {
  4664. L m_lambda;
  4665. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4666. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  4667. auto setValue( std::string const &arg ) -> ParserResult override {
  4668. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  4669. }
  4670. };
  4671. template<typename L>
  4672. struct BoundFlagLambda : BoundFlagRefBase {
  4673. L m_lambda;
  4674. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4675. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  4676. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  4677. auto setFlag( bool flag ) -> ParserResult override {
  4678. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  4679. }
  4680. };
  4681. enum class Optionality { Optional, Required };
  4682. struct Parser;
  4683. class ParserBase {
  4684. public:
  4685. virtual ~ParserBase() = default;
  4686. virtual auto validate() const -> Result { return Result::ok(); }
  4687. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  4688. virtual auto cardinality() const -> size_t { return 1; }
  4689. auto parse( Args const &args ) const -> InternalParseResult {
  4690. return parse( args.exeName(), TokenStream( args ) );
  4691. }
  4692. };
  4693. template<typename DerivedT>
  4694. class ComposableParserImpl : public ParserBase {
  4695. public:
  4696. template<typename T>
  4697. auto operator|( T const &other ) const -> Parser;
  4698. template<typename T>
  4699. auto operator+( T const &other ) const -> Parser;
  4700. };
  4701. // Common code and state for Args and Opts
  4702. template<typename DerivedT>
  4703. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  4704. protected:
  4705. Optionality m_optionality = Optionality::Optional;
  4706. std::shared_ptr<BoundRef> m_ref;
  4707. std::string m_hint;
  4708. std::string m_description;
  4709. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  4710. public:
  4711. template<typename T>
  4712. ParserRefImpl( T &ref, std::string const &hint )
  4713. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  4714. m_hint( hint )
  4715. {}
  4716. template<typename LambdaT>
  4717. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  4718. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  4719. m_hint(hint)
  4720. {}
  4721. auto operator()( std::string const &description ) -> DerivedT & {
  4722. m_description = description;
  4723. return static_cast<DerivedT &>( *this );
  4724. }
  4725. auto optional() -> DerivedT & {
  4726. m_optionality = Optionality::Optional;
  4727. return static_cast<DerivedT &>( *this );
  4728. };
  4729. auto required() -> DerivedT & {
  4730. m_optionality = Optionality::Required;
  4731. return static_cast<DerivedT &>( *this );
  4732. };
  4733. auto isOptional() const -> bool {
  4734. return m_optionality == Optionality::Optional;
  4735. }
  4736. auto cardinality() const -> size_t override {
  4737. if( m_ref->isContainer() )
  4738. return 0;
  4739. else
  4740. return 1;
  4741. }
  4742. auto hint() const -> std::string { return m_hint; }
  4743. };
  4744. class ExeName : public ComposableParserImpl<ExeName> {
  4745. std::shared_ptr<std::string> m_name;
  4746. std::shared_ptr<BoundValueRefBase> m_ref;
  4747. template<typename LambdaT>
  4748. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  4749. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  4750. }
  4751. public:
  4752. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  4753. explicit ExeName( std::string &ref ) : ExeName() {
  4754. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  4755. }
  4756. template<typename LambdaT>
  4757. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  4758. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  4759. }
  4760. // The exe name is not parsed out of the normal tokens, but is handled specially
  4761. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4762. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  4763. }
  4764. auto name() const -> std::string { return *m_name; }
  4765. auto set( std::string const& newName ) -> ParserResult {
  4766. auto lastSlash = newName.find_last_of( "\\/" );
  4767. auto filename = ( lastSlash == std::string::npos )
  4768. ? newName
  4769. : newName.substr( lastSlash+1 );
  4770. *m_name = filename;
  4771. if( m_ref )
  4772. return m_ref->setValue( filename );
  4773. else
  4774. return ParserResult::ok( ParseResultType::Matched );
  4775. }
  4776. };
  4777. class Arg : public ParserRefImpl<Arg> {
  4778. public:
  4779. using ParserRefImpl::ParserRefImpl;
  4780. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  4781. auto validationResult = validate();
  4782. if( !validationResult )
  4783. return InternalParseResult( validationResult );
  4784. auto remainingTokens = tokens;
  4785. auto const &token = *remainingTokens;
  4786. if( token.type != TokenType::Argument )
  4787. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  4788. assert( !m_ref->isFlag() );
  4789. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  4790. auto result = valueRef->setValue( remainingTokens->token );
  4791. if( !result )
  4792. return InternalParseResult( result );
  4793. else
  4794. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  4795. }
  4796. };
  4797. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  4798. #ifdef CATCH_PLATFORM_WINDOWS
  4799. if( optName[0] == '/' )
  4800. return "-" + optName.substr( 1 );
  4801. else
  4802. #endif
  4803. return optName;
  4804. }
  4805. class Opt : public ParserRefImpl<Opt> {
  4806. protected:
  4807. std::vector<std::string> m_optNames;
  4808. public:
  4809. template<typename LambdaT>
  4810. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  4811. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  4812. template<typename LambdaT>
  4813. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4814. template<typename T>
  4815. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4816. auto operator[]( std::string const &optName ) -> Opt & {
  4817. m_optNames.push_back( optName );
  4818. return *this;
  4819. }
  4820. auto getHelpColumns() const -> std::vector<HelpColumns> {
  4821. std::ostringstream oss;
  4822. bool first = true;
  4823. for( auto const &opt : m_optNames ) {
  4824. if (first)
  4825. first = false;
  4826. else
  4827. oss << ", ";
  4828. oss << opt;
  4829. }
  4830. if( !m_hint.empty() )
  4831. oss << " <" << m_hint << ">";
  4832. return { { oss.str(), m_description } };
  4833. }
  4834. auto isMatch( std::string const &optToken ) const -> bool {
  4835. auto normalisedToken = normaliseOpt( optToken );
  4836. for( auto const &name : m_optNames ) {
  4837. if( normaliseOpt( name ) == normalisedToken )
  4838. return true;
  4839. }
  4840. return false;
  4841. }
  4842. using ParserBase::parse;
  4843. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4844. auto validationResult = validate();
  4845. if( !validationResult )
  4846. return InternalParseResult( validationResult );
  4847. auto remainingTokens = tokens;
  4848. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  4849. auto const &token = *remainingTokens;
  4850. if( isMatch(token.token ) ) {
  4851. if( m_ref->isFlag() ) {
  4852. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  4853. auto result = flagRef->setFlag( true );
  4854. if( !result )
  4855. return InternalParseResult( result );
  4856. if( result.value() == ParseResultType::ShortCircuitAll )
  4857. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  4858. } else {
  4859. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  4860. ++remainingTokens;
  4861. if( !remainingTokens )
  4862. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  4863. auto const &argToken = *remainingTokens;
  4864. if( argToken.type != TokenType::Argument )
  4865. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  4866. auto result = valueRef->setValue( argToken.token );
  4867. if( !result )
  4868. return InternalParseResult( result );
  4869. if( result.value() == ParseResultType::ShortCircuitAll )
  4870. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  4871. }
  4872. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  4873. }
  4874. }
  4875. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  4876. }
  4877. auto validate() const -> Result override {
  4878. if( m_optNames.empty() )
  4879. return Result::logicError( "No options supplied to Opt" );
  4880. for( auto const &name : m_optNames ) {
  4881. if( name.empty() )
  4882. return Result::logicError( "Option name cannot be empty" );
  4883. #ifdef CATCH_PLATFORM_WINDOWS
  4884. if( name[0] != '-' && name[0] != '/' )
  4885. return Result::logicError( "Option name must begin with '-' or '/'" );
  4886. #else
  4887. if( name[0] != '-' )
  4888. return Result::logicError( "Option name must begin with '-'" );
  4889. #endif
  4890. }
  4891. return ParserRefImpl::validate();
  4892. }
  4893. };
  4894. struct Help : Opt {
  4895. Help( bool &showHelpFlag )
  4896. : Opt([&]( bool flag ) {
  4897. showHelpFlag = flag;
  4898. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  4899. })
  4900. {
  4901. static_cast<Opt &>( *this )
  4902. ("display usage information")
  4903. ["-?"]["-h"]["--help"]
  4904. .optional();
  4905. }
  4906. };
  4907. struct Parser : ParserBase {
  4908. mutable ExeName m_exeName;
  4909. std::vector<Opt> m_options;
  4910. std::vector<Arg> m_args;
  4911. auto operator|=( ExeName const &exeName ) -> Parser & {
  4912. m_exeName = exeName;
  4913. return *this;
  4914. }
  4915. auto operator|=( Arg const &arg ) -> Parser & {
  4916. m_args.push_back(arg);
  4917. return *this;
  4918. }
  4919. auto operator|=( Opt const &opt ) -> Parser & {
  4920. m_options.push_back(opt);
  4921. return *this;
  4922. }
  4923. auto operator|=( Parser const &other ) -> Parser & {
  4924. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  4925. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  4926. return *this;
  4927. }
  4928. template<typename T>
  4929. auto operator|( T const &other ) const -> Parser {
  4930. return Parser( *this ) |= other;
  4931. }
  4932. // Forward deprecated interface with '+' instead of '|'
  4933. template<typename T>
  4934. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  4935. template<typename T>
  4936. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  4937. auto getHelpColumns() const -> std::vector<HelpColumns> {
  4938. std::vector<HelpColumns> cols;
  4939. for (auto const &o : m_options) {
  4940. auto childCols = o.getHelpColumns();
  4941. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  4942. }
  4943. return cols;
  4944. }
  4945. void writeToStream( std::ostream &os ) const {
  4946. if (!m_exeName.name().empty()) {
  4947. os << "usage:\n" << " " << m_exeName.name() << " ";
  4948. bool required = true, first = true;
  4949. for( auto const &arg : m_args ) {
  4950. if (first)
  4951. first = false;
  4952. else
  4953. os << " ";
  4954. if( arg.isOptional() && required ) {
  4955. os << "[";
  4956. required = false;
  4957. }
  4958. os << "<" << arg.hint() << ">";
  4959. if( arg.cardinality() == 0 )
  4960. os << " ... ";
  4961. }
  4962. if( !required )
  4963. os << "]";
  4964. if( !m_options.empty() )
  4965. os << " options";
  4966. os << "\n\nwhere options are:" << std::endl;
  4967. }
  4968. auto rows = getHelpColumns();
  4969. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  4970. size_t optWidth = 0;
  4971. for( auto const &cols : rows )
  4972. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  4973. optWidth = (std::min)(optWidth, consoleWidth/2);
  4974. for( auto const &cols : rows ) {
  4975. auto row =
  4976. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  4977. TextFlow::Spacer(4) +
  4978. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  4979. os << row << std::endl;
  4980. }
  4981. }
  4982. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  4983. parser.writeToStream( os );
  4984. return os;
  4985. }
  4986. auto validate() const -> Result override {
  4987. for( auto const &opt : m_options ) {
  4988. auto result = opt.validate();
  4989. if( !result )
  4990. return result;
  4991. }
  4992. for( auto const &arg : m_args ) {
  4993. auto result = arg.validate();
  4994. if( !result )
  4995. return result;
  4996. }
  4997. return Result::ok();
  4998. }
  4999. using ParserBase::parse;
  5000. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  5001. struct ParserInfo {
  5002. ParserBase const* parser = nullptr;
  5003. size_t count = 0;
  5004. };
  5005. const size_t totalParsers = m_options.size() + m_args.size();
  5006. assert( totalParsers < 512 );
  5007. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  5008. ParserInfo parseInfos[512];
  5009. {
  5010. size_t i = 0;
  5011. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  5012. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  5013. }
  5014. m_exeName.set( exeName );
  5015. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  5016. while( result.value().remainingTokens() ) {
  5017. bool tokenParsed = false;
  5018. for( size_t i = 0; i < totalParsers; ++i ) {
  5019. auto& parseInfo = parseInfos[i];
  5020. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  5021. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  5022. if (!result)
  5023. return result;
  5024. if (result.value().type() != ParseResultType::NoMatch) {
  5025. tokenParsed = true;
  5026. ++parseInfo.count;
  5027. break;
  5028. }
  5029. }
  5030. }
  5031. if( result.value().type() == ParseResultType::ShortCircuitAll )
  5032. return result;
  5033. if( !tokenParsed )
  5034. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  5035. }
  5036. // !TBD Check missing required options
  5037. return result;
  5038. }
  5039. };
  5040. template<typename DerivedT>
  5041. template<typename T>
  5042. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  5043. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  5044. }
  5045. } // namespace detail
  5046. // A Combined parser
  5047. using detail::Parser;
  5048. // A parser for options
  5049. using detail::Opt;
  5050. // A parser for arguments
  5051. using detail::Arg;
  5052. // Wrapper for argc, argv from main()
  5053. using detail::Args;
  5054. // Specifies the name of the executable
  5055. using detail::ExeName;
  5056. // Convenience wrapper for option parser that specifies the help option
  5057. using detail::Help;
  5058. // enum of result types from a parse
  5059. using detail::ParseResultType;
  5060. // Result type for parser operation
  5061. using detail::ParserResult;
  5062. }} // namespace Catch::clara
  5063. // end clara.hpp
  5064. #ifdef __clang__
  5065. #pragma clang diagnostic pop
  5066. #endif
  5067. // Restore Clara's value for console width, if present
  5068. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5069. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5070. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5071. #endif
  5072. // end catch_clara.h
  5073. namespace Catch {
  5074. clara::Parser makeCommandLineParser( ConfigData& config );
  5075. } // end namespace Catch
  5076. // end catch_commandline.h
  5077. #include <fstream>
  5078. #include <ctime>
  5079. namespace Catch {
  5080. clara::Parser makeCommandLineParser( ConfigData& config ) {
  5081. using namespace clara;
  5082. auto const setWarning = [&]( std::string const& warning ) {
  5083. auto warningSet = [&]() {
  5084. if( warning == "NoAssertions" )
  5085. return WarnAbout::NoAssertions;
  5086. if ( warning == "NoTests" )
  5087. return WarnAbout::NoTests;
  5088. return WarnAbout::Nothing;
  5089. }();
  5090. if (warningSet == WarnAbout::Nothing)
  5091. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  5092. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  5093. return ParserResult::ok( ParseResultType::Matched );
  5094. };
  5095. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  5096. std::ifstream f( filename.c_str() );
  5097. if( !f.is_open() )
  5098. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  5099. std::string line;
  5100. while( std::getline( f, line ) ) {
  5101. line = trim(line);
  5102. if( !line.empty() && !startsWith( line, '#' ) ) {
  5103. if( !startsWith( line, '"' ) )
  5104. line = '"' + line + '"';
  5105. config.testsOrTags.push_back( line + ',' );
  5106. }
  5107. }
  5108. return ParserResult::ok( ParseResultType::Matched );
  5109. };
  5110. auto const setTestOrder = [&]( std::string const& order ) {
  5111. if( startsWith( "declared", order ) )
  5112. config.runOrder = RunTests::InDeclarationOrder;
  5113. else if( startsWith( "lexical", order ) )
  5114. config.runOrder = RunTests::InLexicographicalOrder;
  5115. else if( startsWith( "random", order ) )
  5116. config.runOrder = RunTests::InRandomOrder;
  5117. else
  5118. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  5119. return ParserResult::ok( ParseResultType::Matched );
  5120. };
  5121. auto const setRngSeed = [&]( std::string const& seed ) {
  5122. if( seed != "time" )
  5123. return clara::detail::convertInto( seed, config.rngSeed );
  5124. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  5125. return ParserResult::ok( ParseResultType::Matched );
  5126. };
  5127. auto const setColourUsage = [&]( std::string const& useColour ) {
  5128. auto mode = toLower( useColour );
  5129. if( mode == "yes" )
  5130. config.useColour = UseColour::Yes;
  5131. else if( mode == "no" )
  5132. config.useColour = UseColour::No;
  5133. else if( mode == "auto" )
  5134. config.useColour = UseColour::Auto;
  5135. else
  5136. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  5137. return ParserResult::ok( ParseResultType::Matched );
  5138. };
  5139. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  5140. auto keypressLc = toLower( keypress );
  5141. if( keypressLc == "start" )
  5142. config.waitForKeypress = WaitForKeypress::BeforeStart;
  5143. else if( keypressLc == "exit" )
  5144. config.waitForKeypress = WaitForKeypress::BeforeExit;
  5145. else if( keypressLc == "both" )
  5146. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  5147. else
  5148. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  5149. return ParserResult::ok( ParseResultType::Matched );
  5150. };
  5151. auto const setVerbosity = [&]( std::string const& verbosity ) {
  5152. auto lcVerbosity = toLower( verbosity );
  5153. if( lcVerbosity == "quiet" )
  5154. config.verbosity = Verbosity::Quiet;
  5155. else if( lcVerbosity == "normal" )
  5156. config.verbosity = Verbosity::Normal;
  5157. else if( lcVerbosity == "high" )
  5158. config.verbosity = Verbosity::High;
  5159. else
  5160. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  5161. return ParserResult::ok( ParseResultType::Matched );
  5162. };
  5163. auto cli
  5164. = ExeName( config.processName )
  5165. | Help( config.showHelp )
  5166. | Opt( config.listTests )
  5167. ["-l"]["--list-tests"]
  5168. ( "list all/matching test cases" )
  5169. | Opt( config.listTags )
  5170. ["-t"]["--list-tags"]
  5171. ( "list all/matching tags" )
  5172. | Opt( config.showSuccessfulTests )
  5173. ["-s"]["--success"]
  5174. ( "include successful tests in output" )
  5175. | Opt( config.shouldDebugBreak )
  5176. ["-b"]["--break"]
  5177. ( "break into debugger on failure" )
  5178. | Opt( config.noThrow )
  5179. ["-e"]["--nothrow"]
  5180. ( "skip exception tests" )
  5181. | Opt( config.showInvisibles )
  5182. ["-i"]["--invisibles"]
  5183. ( "show invisibles (tabs, newlines)" )
  5184. | Opt( config.outputFilename, "filename" )
  5185. ["-o"]["--out"]
  5186. ( "output filename" )
  5187. | Opt( config.reporterNames, "name" )
  5188. ["-r"]["--reporter"]
  5189. ( "reporter to use (defaults to console)" )
  5190. | Opt( config.name, "name" )
  5191. ["-n"]["--name"]
  5192. ( "suite name" )
  5193. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  5194. ["-a"]["--abort"]
  5195. ( "abort at first failure" )
  5196. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  5197. ["-x"]["--abortx"]
  5198. ( "abort after x failures" )
  5199. | Opt( setWarning, "warning name" )
  5200. ["-w"]["--warn"]
  5201. ( "enable warnings" )
  5202. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  5203. ["-d"]["--durations"]
  5204. ( "show test durations" )
  5205. | Opt( loadTestNamesFromFile, "filename" )
  5206. ["-f"]["--input-file"]
  5207. ( "load test names to run from a file" )
  5208. | Opt( config.filenamesAsTags )
  5209. ["-#"]["--filenames-as-tags"]
  5210. ( "adds a tag for the filename" )
  5211. | Opt( config.sectionsToRun, "section name" )
  5212. ["-c"]["--section"]
  5213. ( "specify section to run" )
  5214. | Opt( setVerbosity, "quiet|normal|high" )
  5215. ["-v"]["--verbosity"]
  5216. ( "set output verbosity" )
  5217. | Opt( config.listTestNamesOnly )
  5218. ["--list-test-names-only"]
  5219. ( "list all/matching test cases names only" )
  5220. | Opt( config.listReporters )
  5221. ["--list-reporters"]
  5222. ( "list all reporters" )
  5223. | Opt( setTestOrder, "decl|lex|rand" )
  5224. ["--order"]
  5225. ( "test case order (defaults to decl)" )
  5226. | Opt( setRngSeed, "'time'|number" )
  5227. ["--rng-seed"]
  5228. ( "set a specific seed for random numbers" )
  5229. | Opt( setColourUsage, "yes|no" )
  5230. ["--use-colour"]
  5231. ( "should output be colourised" )
  5232. | Opt( config.libIdentify )
  5233. ["--libidentify"]
  5234. ( "report name and version according to libidentify standard" )
  5235. | Opt( setWaitForKeypress, "start|exit|both" )
  5236. ["--wait-for-keypress"]
  5237. ( "waits for a keypress before exiting" )
  5238. | Opt( config.benchmarkResolutionMultiple, "multiplier" )
  5239. ["--benchmark-resolution-multiple"]
  5240. ( "multiple of clock resolution to run benchmarks" )
  5241. | Arg( config.testsOrTags, "test name|pattern|tags" )
  5242. ( "which test or tests to use" );
  5243. return cli;
  5244. }
  5245. } // end namespace Catch
  5246. // end catch_commandline.cpp
  5247. // start catch_common.cpp
  5248. #include <cstring>
  5249. #include <ostream>
  5250. namespace Catch {
  5251. bool SourceLineInfo::empty() const noexcept {
  5252. return file[0] == '\0';
  5253. }
  5254. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  5255. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  5256. }
  5257. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  5258. return line < other.line || ( line == other.line && (std::strcmp(file, other.file) < 0));
  5259. }
  5260. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  5261. #ifndef __GNUG__
  5262. os << info.file << '(' << info.line << ')';
  5263. #else
  5264. os << info.file << ':' << info.line;
  5265. #endif
  5266. return os;
  5267. }
  5268. std::string StreamEndStop::operator+() const {
  5269. return std::string();
  5270. }
  5271. NonCopyable::NonCopyable() = default;
  5272. NonCopyable::~NonCopyable() = default;
  5273. }
  5274. // end catch_common.cpp
  5275. // start catch_config.cpp
  5276. // start catch_enforce.h
  5277. #include <stdexcept>
  5278. #define CATCH_PREPARE_EXCEPTION( type, msg ) \
  5279. type( ( Catch::ReusableStringStream() << msg ).str() )
  5280. #define CATCH_INTERNAL_ERROR( msg ) \
  5281. throw CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg);
  5282. #define CATCH_ERROR( msg ) \
  5283. throw CATCH_PREPARE_EXCEPTION( std::domain_error, msg )
  5284. #define CATCH_ENFORCE( condition, msg ) \
  5285. do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
  5286. // end catch_enforce.h
  5287. namespace Catch {
  5288. Config::Config( ConfigData const& data )
  5289. : m_data( data ),
  5290. m_stream( openStream() )
  5291. {
  5292. TestSpecParser parser(ITagAliasRegistry::get());
  5293. if (data.testsOrTags.empty()) {
  5294. parser.parse("~[.]"); // All not hidden tests
  5295. }
  5296. else {
  5297. m_hasTestFilters = true;
  5298. for( auto const& testOrTags : data.testsOrTags )
  5299. parser.parse( testOrTags );
  5300. }
  5301. m_testSpec = parser.testSpec();
  5302. }
  5303. std::string const& Config::getFilename() const {
  5304. return m_data.outputFilename ;
  5305. }
  5306. bool Config::listTests() const { return m_data.listTests; }
  5307. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  5308. bool Config::listTags() const { return m_data.listTags; }
  5309. bool Config::listReporters() const { return m_data.listReporters; }
  5310. std::string Config::getProcessName() const { return m_data.processName; }
  5311. std::vector<std::string> const& Config::getReporterNames() const { return m_data.reporterNames; }
  5312. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  5313. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  5314. TestSpec const& Config::testSpec() const { return m_testSpec; }
  5315. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  5316. bool Config::showHelp() const { return m_data.showHelp; }
  5317. // IConfig interface
  5318. bool Config::allowThrows() const { return !m_data.noThrow; }
  5319. std::ostream& Config::stream() const { return m_stream->stream(); }
  5320. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  5321. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  5322. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  5323. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  5324. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  5325. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  5326. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  5327. int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
  5328. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  5329. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  5330. int Config::abortAfter() const { return m_data.abortAfter; }
  5331. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  5332. Verbosity Config::verbosity() const { return m_data.verbosity; }
  5333. IStream const* Config::openStream() {
  5334. return Catch::makeStream(m_data.outputFilename);
  5335. }
  5336. } // end namespace Catch
  5337. // end catch_config.cpp
  5338. // start catch_console_colour.cpp
  5339. #if defined(__clang__)
  5340. # pragma clang diagnostic push
  5341. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  5342. #endif
  5343. // start catch_errno_guard.h
  5344. namespace Catch {
  5345. class ErrnoGuard {
  5346. public:
  5347. ErrnoGuard();
  5348. ~ErrnoGuard();
  5349. private:
  5350. int m_oldErrno;
  5351. };
  5352. }
  5353. // end catch_errno_guard.h
  5354. #include <sstream>
  5355. namespace Catch {
  5356. namespace {
  5357. struct IColourImpl {
  5358. virtual ~IColourImpl() = default;
  5359. virtual void use( Colour::Code _colourCode ) = 0;
  5360. };
  5361. struct NoColourImpl : IColourImpl {
  5362. void use( Colour::Code ) {}
  5363. static IColourImpl* instance() {
  5364. static NoColourImpl s_instance;
  5365. return &s_instance;
  5366. }
  5367. };
  5368. } // anon namespace
  5369. } // namespace Catch
  5370. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  5371. # ifdef CATCH_PLATFORM_WINDOWS
  5372. # define CATCH_CONFIG_COLOUR_WINDOWS
  5373. # else
  5374. # define CATCH_CONFIG_COLOUR_ANSI
  5375. # endif
  5376. #endif
  5377. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  5378. namespace Catch {
  5379. namespace {
  5380. class Win32ColourImpl : public IColourImpl {
  5381. public:
  5382. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  5383. {
  5384. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  5385. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  5386. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  5387. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  5388. }
  5389. virtual void use( Colour::Code _colourCode ) override {
  5390. switch( _colourCode ) {
  5391. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  5392. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5393. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  5394. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  5395. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  5396. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  5397. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  5398. case Colour::Grey: return setTextAttribute( 0 );
  5399. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  5400. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  5401. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  5402. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5403. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  5404. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5405. default:
  5406. CATCH_ERROR( "Unknown colour requested" );
  5407. }
  5408. }
  5409. private:
  5410. void setTextAttribute( WORD _textAttribute ) {
  5411. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  5412. }
  5413. HANDLE stdoutHandle;
  5414. WORD originalForegroundAttributes;
  5415. WORD originalBackgroundAttributes;
  5416. };
  5417. IColourImpl* platformColourInstance() {
  5418. static Win32ColourImpl s_instance;
  5419. IConfigPtr config = getCurrentContext().getConfig();
  5420. UseColour::YesOrNo colourMode = config
  5421. ? config->useColour()
  5422. : UseColour::Auto;
  5423. if( colourMode == UseColour::Auto )
  5424. colourMode = UseColour::Yes;
  5425. return colourMode == UseColour::Yes
  5426. ? &s_instance
  5427. : NoColourImpl::instance();
  5428. }
  5429. } // end anon namespace
  5430. } // end namespace Catch
  5431. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  5432. #include <unistd.h>
  5433. namespace Catch {
  5434. namespace {
  5435. // use POSIX/ ANSI console terminal codes
  5436. // Thanks to Adam Strzelecki for original contribution
  5437. // (http://github.com/nanoant)
  5438. // https://github.com/philsquared/Catch/pull/131
  5439. class PosixColourImpl : public IColourImpl {
  5440. public:
  5441. virtual void use( Colour::Code _colourCode ) override {
  5442. switch( _colourCode ) {
  5443. case Colour::None:
  5444. case Colour::White: return setColour( "[0m" );
  5445. case Colour::Red: return setColour( "[0;31m" );
  5446. case Colour::Green: return setColour( "[0;32m" );
  5447. case Colour::Blue: return setColour( "[0;34m" );
  5448. case Colour::Cyan: return setColour( "[0;36m" );
  5449. case Colour::Yellow: return setColour( "[0;33m" );
  5450. case Colour::Grey: return setColour( "[1;30m" );
  5451. case Colour::LightGrey: return setColour( "[0;37m" );
  5452. case Colour::BrightRed: return setColour( "[1;31m" );
  5453. case Colour::BrightGreen: return setColour( "[1;32m" );
  5454. case Colour::BrightWhite: return setColour( "[1;37m" );
  5455. case Colour::BrightYellow: return setColour( "[1;33m" );
  5456. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5457. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  5458. }
  5459. }
  5460. static IColourImpl* instance() {
  5461. static PosixColourImpl s_instance;
  5462. return &s_instance;
  5463. }
  5464. private:
  5465. void setColour( const char* _escapeCode ) {
  5466. Catch::cout() << '\033' << _escapeCode;
  5467. }
  5468. };
  5469. bool useColourOnPlatform() {
  5470. return
  5471. #ifdef CATCH_PLATFORM_MAC
  5472. !isDebuggerActive() &&
  5473. #endif
  5474. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  5475. isatty(STDOUT_FILENO)
  5476. #else
  5477. false
  5478. #endif
  5479. ;
  5480. }
  5481. IColourImpl* platformColourInstance() {
  5482. ErrnoGuard guard;
  5483. IConfigPtr config = getCurrentContext().getConfig();
  5484. UseColour::YesOrNo colourMode = config
  5485. ? config->useColour()
  5486. : UseColour::Auto;
  5487. if( colourMode == UseColour::Auto )
  5488. colourMode = useColourOnPlatform()
  5489. ? UseColour::Yes
  5490. : UseColour::No;
  5491. return colourMode == UseColour::Yes
  5492. ? PosixColourImpl::instance()
  5493. : NoColourImpl::instance();
  5494. }
  5495. } // end anon namespace
  5496. } // end namespace Catch
  5497. #else // not Windows or ANSI ///////////////////////////////////////////////
  5498. namespace Catch {
  5499. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  5500. } // end namespace Catch
  5501. #endif // Windows/ ANSI/ None
  5502. namespace Catch {
  5503. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  5504. Colour::Colour( Colour&& rhs ) noexcept {
  5505. m_moved = rhs.m_moved;
  5506. rhs.m_moved = true;
  5507. }
  5508. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  5509. m_moved = rhs.m_moved;
  5510. rhs.m_moved = true;
  5511. return *this;
  5512. }
  5513. Colour::~Colour(){ if( !m_moved ) use( None ); }
  5514. void Colour::use( Code _colourCode ) {
  5515. static IColourImpl* impl = platformColourInstance();
  5516. impl->use( _colourCode );
  5517. }
  5518. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  5519. return os;
  5520. }
  5521. } // end namespace Catch
  5522. #if defined(__clang__)
  5523. # pragma clang diagnostic pop
  5524. #endif
  5525. // end catch_console_colour.cpp
  5526. // start catch_context.cpp
  5527. namespace Catch {
  5528. class Context : public IMutableContext, NonCopyable {
  5529. public: // IContext
  5530. virtual IResultCapture* getResultCapture() override {
  5531. return m_resultCapture;
  5532. }
  5533. virtual IRunner* getRunner() override {
  5534. return m_runner;
  5535. }
  5536. virtual IConfigPtr const& getConfig() const override {
  5537. return m_config;
  5538. }
  5539. virtual ~Context() override;
  5540. public: // IMutableContext
  5541. virtual void setResultCapture( IResultCapture* resultCapture ) override {
  5542. m_resultCapture = resultCapture;
  5543. }
  5544. virtual void setRunner( IRunner* runner ) override {
  5545. m_runner = runner;
  5546. }
  5547. virtual void setConfig( IConfigPtr const& config ) override {
  5548. m_config = config;
  5549. }
  5550. friend IMutableContext& getCurrentMutableContext();
  5551. private:
  5552. IConfigPtr m_config;
  5553. IRunner* m_runner = nullptr;
  5554. IResultCapture* m_resultCapture = nullptr;
  5555. };
  5556. IMutableContext *IMutableContext::currentContext = nullptr;
  5557. void IMutableContext::createContext()
  5558. {
  5559. currentContext = new Context();
  5560. }
  5561. void cleanUpContext() {
  5562. delete IMutableContext::currentContext;
  5563. IMutableContext::currentContext = nullptr;
  5564. }
  5565. IContext::~IContext() = default;
  5566. IMutableContext::~IMutableContext() = default;
  5567. Context::~Context() = default;
  5568. }
  5569. // end catch_context.cpp
  5570. // start catch_debug_console.cpp
  5571. // start catch_debug_console.h
  5572. #include <string>
  5573. namespace Catch {
  5574. void writeToDebugConsole( std::string const& text );
  5575. }
  5576. // end catch_debug_console.h
  5577. #ifdef CATCH_PLATFORM_WINDOWS
  5578. namespace Catch {
  5579. void writeToDebugConsole( std::string const& text ) {
  5580. ::OutputDebugStringA( text.c_str() );
  5581. }
  5582. }
  5583. #else
  5584. namespace Catch {
  5585. void writeToDebugConsole( std::string const& text ) {
  5586. // !TBD: Need a version for Mac/ XCode and other IDEs
  5587. Catch::cout() << text;
  5588. }
  5589. }
  5590. #endif // Platform
  5591. // end catch_debug_console.cpp
  5592. // start catch_debugger.cpp
  5593. #ifdef CATCH_PLATFORM_MAC
  5594. # include <assert.h>
  5595. # include <stdbool.h>
  5596. # include <sys/types.h>
  5597. # include <unistd.h>
  5598. # include <sys/sysctl.h>
  5599. # include <cstddef>
  5600. # include <ostream>
  5601. namespace Catch {
  5602. // The following function is taken directly from the following technical note:
  5603. // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  5604. // Returns true if the current process is being debugged (either
  5605. // running under the debugger or has a debugger attached post facto).
  5606. bool isDebuggerActive(){
  5607. int mib[4];
  5608. struct kinfo_proc info;
  5609. std::size_t size;
  5610. // Initialize the flags so that, if sysctl fails for some bizarre
  5611. // reason, we get a predictable result.
  5612. info.kp_proc.p_flag = 0;
  5613. // Initialize mib, which tells sysctl the info we want, in this case
  5614. // we're looking for information about a specific process ID.
  5615. mib[0] = CTL_KERN;
  5616. mib[1] = KERN_PROC;
  5617. mib[2] = KERN_PROC_PID;
  5618. mib[3] = getpid();
  5619. // Call sysctl.
  5620. size = sizeof(info);
  5621. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  5622. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  5623. return false;
  5624. }
  5625. // We're being debugged if the P_TRACED flag is set.
  5626. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  5627. }
  5628. } // namespace Catch
  5629. #elif defined(CATCH_PLATFORM_LINUX)
  5630. #include <fstream>
  5631. #include <string>
  5632. namespace Catch{
  5633. // The standard POSIX way of detecting a debugger is to attempt to
  5634. // ptrace() the process, but this needs to be done from a child and not
  5635. // this process itself to still allow attaching to this process later
  5636. // if wanted, so is rather heavy. Under Linux we have the PID of the
  5637. // "debugger" (which doesn't need to be gdb, of course, it could also
  5638. // be strace, for example) in /proc/$PID/status, so just get it from
  5639. // there instead.
  5640. bool isDebuggerActive(){
  5641. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  5642. // This way our users can properly assert over errno values
  5643. ErrnoGuard guard;
  5644. std::ifstream in("/proc/self/status");
  5645. for( std::string line; std::getline(in, line); ) {
  5646. static const int PREFIX_LEN = 11;
  5647. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  5648. // We're traced if the PID is not 0 and no other PID starts
  5649. // with 0 digit, so it's enough to check for just a single
  5650. // character.
  5651. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  5652. }
  5653. }
  5654. return false;
  5655. }
  5656. } // namespace Catch
  5657. #elif defined(_MSC_VER)
  5658. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5659. namespace Catch {
  5660. bool isDebuggerActive() {
  5661. return IsDebuggerPresent() != 0;
  5662. }
  5663. }
  5664. #elif defined(__MINGW32__)
  5665. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5666. namespace Catch {
  5667. bool isDebuggerActive() {
  5668. return IsDebuggerPresent() != 0;
  5669. }
  5670. }
  5671. #else
  5672. namespace Catch {
  5673. bool isDebuggerActive() { return false; }
  5674. }
  5675. #endif // Platform
  5676. // end catch_debugger.cpp
  5677. // start catch_decomposer.cpp
  5678. namespace Catch {
  5679. ITransientExpression::~ITransientExpression() = default;
  5680. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  5681. if( lhs.size() + rhs.size() < 40 &&
  5682. lhs.find('\n') == std::string::npos &&
  5683. rhs.find('\n') == std::string::npos )
  5684. os << lhs << " " << op << " " << rhs;
  5685. else
  5686. os << lhs << "\n" << op << "\n" << rhs;
  5687. }
  5688. }
  5689. // end catch_decomposer.cpp
  5690. // start catch_errno_guard.cpp
  5691. #include <cerrno>
  5692. namespace Catch {
  5693. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  5694. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  5695. }
  5696. // end catch_errno_guard.cpp
  5697. // start catch_exception_translator_registry.cpp
  5698. // start catch_exception_translator_registry.h
  5699. #include <vector>
  5700. #include <string>
  5701. #include <memory>
  5702. namespace Catch {
  5703. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  5704. public:
  5705. ~ExceptionTranslatorRegistry();
  5706. virtual void registerTranslator( const IExceptionTranslator* translator );
  5707. virtual std::string translateActiveException() const override;
  5708. std::string tryTranslators() const;
  5709. private:
  5710. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  5711. };
  5712. }
  5713. // end catch_exception_translator_registry.h
  5714. #ifdef __OBJC__
  5715. #import "Foundation/Foundation.h"
  5716. #endif
  5717. namespace Catch {
  5718. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  5719. }
  5720. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  5721. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  5722. }
  5723. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  5724. try {
  5725. #ifdef __OBJC__
  5726. // In Objective-C try objective-c exceptions first
  5727. @try {
  5728. return tryTranslators();
  5729. }
  5730. @catch (NSException *exception) {
  5731. return Catch::Detail::stringify( [exception description] );
  5732. }
  5733. #else
  5734. // Compiling a mixed mode project with MSVC means that CLR
  5735. // exceptions will be caught in (...) as well. However, these
  5736. // do not fill-in std::current_exception and thus lead to crash
  5737. // when attempting rethrow.
  5738. // /EHa switch also causes structured exceptions to be caught
  5739. // here, but they fill-in current_exception properly, so
  5740. // at worst the output should be a little weird, instead of
  5741. // causing a crash.
  5742. if (std::current_exception() == nullptr) {
  5743. return "Non C++ exception. Possibly a CLR exception.";
  5744. }
  5745. return tryTranslators();
  5746. #endif
  5747. }
  5748. catch( TestFailureException& ) {
  5749. std::rethrow_exception(std::current_exception());
  5750. }
  5751. catch( std::exception& ex ) {
  5752. return ex.what();
  5753. }
  5754. catch( std::string& msg ) {
  5755. return msg;
  5756. }
  5757. catch( const char* msg ) {
  5758. return msg;
  5759. }
  5760. catch(...) {
  5761. return "Unknown exception";
  5762. }
  5763. }
  5764. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  5765. if( m_translators.empty() )
  5766. std::rethrow_exception(std::current_exception());
  5767. else
  5768. return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() );
  5769. }
  5770. }
  5771. // end catch_exception_translator_registry.cpp
  5772. // start catch_fatal_condition.cpp
  5773. #if defined(__GNUC__)
  5774. # pragma GCC diagnostic push
  5775. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  5776. #endif
  5777. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  5778. namespace {
  5779. // Report the error condition
  5780. void reportFatal( char const * const message ) {
  5781. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  5782. }
  5783. }
  5784. #endif // signals/SEH handling
  5785. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  5786. namespace Catch {
  5787. struct SignalDefs { DWORD id; const char* name; };
  5788. // There is no 1-1 mapping between signals and windows exceptions.
  5789. // Windows can easily distinguish between SO and SigSegV,
  5790. // but SigInt, SigTerm, etc are handled differently.
  5791. static SignalDefs signalDefs[] = {
  5792. { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
  5793. { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
  5794. { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
  5795. { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
  5796. };
  5797. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  5798. for (auto const& def : signalDefs) {
  5799. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  5800. reportFatal(def.name);
  5801. }
  5802. }
  5803. // If its not an exception we care about, pass it along.
  5804. // This stops us from eating debugger breaks etc.
  5805. return EXCEPTION_CONTINUE_SEARCH;
  5806. }
  5807. FatalConditionHandler::FatalConditionHandler() {
  5808. isSet = true;
  5809. // 32k seems enough for Catch to handle stack overflow,
  5810. // but the value was found experimentally, so there is no strong guarantee
  5811. guaranteeSize = 32 * 1024;
  5812. exceptionHandlerHandle = nullptr;
  5813. // Register as first handler in current chain
  5814. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  5815. // Pass in guarantee size to be filled
  5816. SetThreadStackGuarantee(&guaranteeSize);
  5817. }
  5818. void FatalConditionHandler::reset() {
  5819. if (isSet) {
  5820. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  5821. SetThreadStackGuarantee(&guaranteeSize);
  5822. exceptionHandlerHandle = nullptr;
  5823. isSet = false;
  5824. }
  5825. }
  5826. FatalConditionHandler::~FatalConditionHandler() {
  5827. reset();
  5828. }
  5829. bool FatalConditionHandler::isSet = false;
  5830. ULONG FatalConditionHandler::guaranteeSize = 0;
  5831. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  5832. } // namespace Catch
  5833. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  5834. namespace Catch {
  5835. struct SignalDefs {
  5836. int id;
  5837. const char* name;
  5838. };
  5839. static SignalDefs signalDefs[] = {
  5840. { SIGINT, "SIGINT - Terminal interrupt signal" },
  5841. { SIGILL, "SIGILL - Illegal instruction signal" },
  5842. { SIGFPE, "SIGFPE - Floating point error signal" },
  5843. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  5844. { SIGTERM, "SIGTERM - Termination request signal" },
  5845. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  5846. };
  5847. void FatalConditionHandler::handleSignal( int sig ) {
  5848. char const * name = "<unknown signal>";
  5849. for (auto const& def : signalDefs) {
  5850. if (sig == def.id) {
  5851. name = def.name;
  5852. break;
  5853. }
  5854. }
  5855. reset();
  5856. reportFatal(name);
  5857. raise( sig );
  5858. }
  5859. FatalConditionHandler::FatalConditionHandler() {
  5860. isSet = true;
  5861. stack_t sigStack;
  5862. sigStack.ss_sp = altStackMem;
  5863. sigStack.ss_size = SIGSTKSZ;
  5864. sigStack.ss_flags = 0;
  5865. sigaltstack(&sigStack, &oldSigStack);
  5866. struct sigaction sa = { };
  5867. sa.sa_handler = handleSignal;
  5868. sa.sa_flags = SA_ONSTACK;
  5869. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  5870. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  5871. }
  5872. }
  5873. FatalConditionHandler::~FatalConditionHandler() {
  5874. reset();
  5875. }
  5876. void FatalConditionHandler::reset() {
  5877. if( isSet ) {
  5878. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  5879. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  5880. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  5881. }
  5882. // Return the old stack
  5883. sigaltstack(&oldSigStack, nullptr);
  5884. isSet = false;
  5885. }
  5886. }
  5887. bool FatalConditionHandler::isSet = false;
  5888. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  5889. stack_t FatalConditionHandler::oldSigStack = {};
  5890. char FatalConditionHandler::altStackMem[SIGSTKSZ] = {};
  5891. } // namespace Catch
  5892. #else
  5893. namespace Catch {
  5894. void FatalConditionHandler::reset() {}
  5895. }
  5896. #endif // signals/SEH handling
  5897. #if defined(__GNUC__)
  5898. # pragma GCC diagnostic pop
  5899. #endif
  5900. // end catch_fatal_condition.cpp
  5901. // start catch_interfaces_capture.cpp
  5902. namespace Catch {
  5903. IResultCapture::~IResultCapture() = default;
  5904. }
  5905. // end catch_interfaces_capture.cpp
  5906. // start catch_interfaces_config.cpp
  5907. namespace Catch {
  5908. IConfig::~IConfig() = default;
  5909. }
  5910. // end catch_interfaces_config.cpp
  5911. // start catch_interfaces_exception.cpp
  5912. namespace Catch {
  5913. IExceptionTranslator::~IExceptionTranslator() = default;
  5914. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  5915. }
  5916. // end catch_interfaces_exception.cpp
  5917. // start catch_interfaces_registry_hub.cpp
  5918. namespace Catch {
  5919. IRegistryHub::~IRegistryHub() = default;
  5920. IMutableRegistryHub::~IMutableRegistryHub() = default;
  5921. }
  5922. // end catch_interfaces_registry_hub.cpp
  5923. // start catch_interfaces_reporter.cpp
  5924. // start catch_reporter_multi.h
  5925. namespace Catch {
  5926. class MultipleReporters : public IStreamingReporter {
  5927. using Reporters = std::vector<IStreamingReporterPtr>;
  5928. Reporters m_reporters;
  5929. public:
  5930. void add( IStreamingReporterPtr&& reporter );
  5931. public: // IStreamingReporter
  5932. ReporterPreferences getPreferences() const override;
  5933. void noMatchingTestCases( std::string const& spec ) override;
  5934. static std::set<Verbosity> getSupportedVerbosities();
  5935. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  5936. void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override;
  5937. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  5938. void testGroupStarting( GroupInfo const& groupInfo ) override;
  5939. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  5940. void sectionStarting( SectionInfo const& sectionInfo ) override;
  5941. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  5942. // The return value indicates if the messages buffer should be cleared:
  5943. bool assertionEnded( AssertionStats const& assertionStats ) override;
  5944. void sectionEnded( SectionStats const& sectionStats ) override;
  5945. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  5946. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  5947. void testRunEnded( TestRunStats const& testRunStats ) override;
  5948. void skipTest( TestCaseInfo const& testInfo ) override;
  5949. bool isMulti() const override;
  5950. };
  5951. } // end namespace Catch
  5952. // end catch_reporter_multi.h
  5953. namespace Catch {
  5954. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  5955. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  5956. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  5957. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  5958. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  5959. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  5960. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  5961. GroupInfo::GroupInfo( std::string const& _name,
  5962. std::size_t _groupIndex,
  5963. std::size_t _groupsCount )
  5964. : name( _name ),
  5965. groupIndex( _groupIndex ),
  5966. groupsCounts( _groupsCount )
  5967. {}
  5968. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  5969. std::vector<MessageInfo> const& _infoMessages,
  5970. Totals const& _totals )
  5971. : assertionResult( _assertionResult ),
  5972. infoMessages( _infoMessages ),
  5973. totals( _totals )
  5974. {
  5975. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  5976. if( assertionResult.hasMessage() ) {
  5977. // Copy message into messages list.
  5978. // !TBD This should have been done earlier, somewhere
  5979. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  5980. builder << assertionResult.getMessage();
  5981. builder.m_info.message = builder.m_stream.str();
  5982. infoMessages.push_back( builder.m_info );
  5983. }
  5984. }
  5985. AssertionStats::~AssertionStats() = default;
  5986. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  5987. Counts const& _assertions,
  5988. double _durationInSeconds,
  5989. bool _missingAssertions )
  5990. : sectionInfo( _sectionInfo ),
  5991. assertions( _assertions ),
  5992. durationInSeconds( _durationInSeconds ),
  5993. missingAssertions( _missingAssertions )
  5994. {}
  5995. SectionStats::~SectionStats() = default;
  5996. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  5997. Totals const& _totals,
  5998. std::string const& _stdOut,
  5999. std::string const& _stdErr,
  6000. bool _aborting )
  6001. : testInfo( _testInfo ),
  6002. totals( _totals ),
  6003. stdOut( _stdOut ),
  6004. stdErr( _stdErr ),
  6005. aborting( _aborting )
  6006. {}
  6007. TestCaseStats::~TestCaseStats() = default;
  6008. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  6009. Totals const& _totals,
  6010. bool _aborting )
  6011. : groupInfo( _groupInfo ),
  6012. totals( _totals ),
  6013. aborting( _aborting )
  6014. {}
  6015. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  6016. : groupInfo( _groupInfo ),
  6017. aborting( false )
  6018. {}
  6019. TestGroupStats::~TestGroupStats() = default;
  6020. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  6021. Totals const& _totals,
  6022. bool _aborting )
  6023. : runInfo( _runInfo ),
  6024. totals( _totals ),
  6025. aborting( _aborting )
  6026. {}
  6027. TestRunStats::~TestRunStats() = default;
  6028. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  6029. bool IStreamingReporter::isMulti() const { return false; }
  6030. IReporterFactory::~IReporterFactory() = default;
  6031. IReporterRegistry::~IReporterRegistry() = default;
  6032. void addReporter( IStreamingReporterPtr& existingReporter, IStreamingReporterPtr&& additionalReporter ) {
  6033. if( !existingReporter ) {
  6034. existingReporter = std::move( additionalReporter );
  6035. return;
  6036. }
  6037. MultipleReporters* multi = nullptr;
  6038. if( existingReporter->isMulti() ) {
  6039. multi = static_cast<MultipleReporters*>( existingReporter.get() );
  6040. }
  6041. else {
  6042. auto newMulti = std::unique_ptr<MultipleReporters>( new MultipleReporters );
  6043. newMulti->add( std::move( existingReporter ) );
  6044. multi = newMulti.get();
  6045. existingReporter = std::move( newMulti );
  6046. }
  6047. multi->add( std::move( additionalReporter ) );
  6048. }
  6049. } // end namespace Catch
  6050. // end catch_interfaces_reporter.cpp
  6051. // start catch_interfaces_runner.cpp
  6052. namespace Catch {
  6053. IRunner::~IRunner() = default;
  6054. }
  6055. // end catch_interfaces_runner.cpp
  6056. // start catch_interfaces_testcase.cpp
  6057. namespace Catch {
  6058. ITestInvoker::~ITestInvoker() = default;
  6059. ITestCaseRegistry::~ITestCaseRegistry() = default;
  6060. }
  6061. // end catch_interfaces_testcase.cpp
  6062. // start catch_leak_detector.cpp
  6063. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  6064. #include <crtdbg.h>
  6065. namespace Catch {
  6066. LeakDetector::LeakDetector() {
  6067. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  6068. flag |= _CRTDBG_LEAK_CHECK_DF;
  6069. flag |= _CRTDBG_ALLOC_MEM_DF;
  6070. _CrtSetDbgFlag(flag);
  6071. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  6072. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  6073. // Change this to leaking allocation's number to break there
  6074. _CrtSetBreakAlloc(-1);
  6075. }
  6076. }
  6077. #else
  6078. Catch::LeakDetector::LeakDetector() {}
  6079. #endif
  6080. // end catch_leak_detector.cpp
  6081. // start catch_list.cpp
  6082. // start catch_list.h
  6083. #include <set>
  6084. namespace Catch {
  6085. std::size_t listTests( Config const& config );
  6086. std::size_t listTestsNamesOnly( Config const& config );
  6087. struct TagInfo {
  6088. void add( std::string const& spelling );
  6089. std::string all() const;
  6090. std::set<std::string> spellings;
  6091. std::size_t count = 0;
  6092. };
  6093. std::size_t listTags( Config const& config );
  6094. std::size_t listReporters( Config const& /*config*/ );
  6095. Option<std::size_t> list( Config const& config );
  6096. } // end namespace Catch
  6097. // end catch_list.h
  6098. // start catch_text.h
  6099. namespace Catch {
  6100. using namespace clara::TextFlow;
  6101. }
  6102. // end catch_text.h
  6103. #include <limits>
  6104. #include <algorithm>
  6105. #include <iomanip>
  6106. namespace Catch {
  6107. std::size_t listTests( Config const& config ) {
  6108. TestSpec testSpec = config.testSpec();
  6109. if( config.hasTestFilters() )
  6110. Catch::cout() << "Matching test cases:\n";
  6111. else {
  6112. Catch::cout() << "All available test cases:\n";
  6113. }
  6114. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6115. for( auto const& testCaseInfo : matchedTestCases ) {
  6116. Colour::Code colour = testCaseInfo.isHidden()
  6117. ? Colour::SecondaryText
  6118. : Colour::None;
  6119. Colour colourGuard( colour );
  6120. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  6121. if( config.verbosity() >= Verbosity::High ) {
  6122. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  6123. std::string description = testCaseInfo.description;
  6124. if( description.empty() )
  6125. description = "(NO DESCRIPTION)";
  6126. Catch::cout() << Column( description ).indent(4) << std::endl;
  6127. }
  6128. if( !testCaseInfo.tags.empty() )
  6129. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  6130. }
  6131. if( !config.hasTestFilters() )
  6132. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  6133. else
  6134. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  6135. return matchedTestCases.size();
  6136. }
  6137. std::size_t listTestsNamesOnly( Config const& config ) {
  6138. TestSpec testSpec = config.testSpec();
  6139. std::size_t matchedTests = 0;
  6140. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6141. for( auto const& testCaseInfo : matchedTestCases ) {
  6142. matchedTests++;
  6143. if( startsWith( testCaseInfo.name, '#' ) )
  6144. Catch::cout() << '"' << testCaseInfo.name << '"';
  6145. else
  6146. Catch::cout() << testCaseInfo.name;
  6147. if ( config.verbosity() >= Verbosity::High )
  6148. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  6149. Catch::cout() << std::endl;
  6150. }
  6151. return matchedTests;
  6152. }
  6153. void TagInfo::add( std::string const& spelling ) {
  6154. ++count;
  6155. spellings.insert( spelling );
  6156. }
  6157. std::string TagInfo::all() const {
  6158. std::string out;
  6159. for( auto const& spelling : spellings )
  6160. out += "[" + spelling + "]";
  6161. return out;
  6162. }
  6163. std::size_t listTags( Config const& config ) {
  6164. TestSpec testSpec = config.testSpec();
  6165. if( config.hasTestFilters() )
  6166. Catch::cout() << "Tags for matching test cases:\n";
  6167. else {
  6168. Catch::cout() << "All available tags:\n";
  6169. }
  6170. std::map<std::string, TagInfo> tagCounts;
  6171. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6172. for( auto const& testCase : matchedTestCases ) {
  6173. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  6174. std::string lcaseTagName = toLower( tagName );
  6175. auto countIt = tagCounts.find( lcaseTagName );
  6176. if( countIt == tagCounts.end() )
  6177. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  6178. countIt->second.add( tagName );
  6179. }
  6180. }
  6181. for( auto const& tagCount : tagCounts ) {
  6182. ReusableStringStream rss;
  6183. rss << " " << std::setw(2) << tagCount.second.count << " ";
  6184. auto str = rss.str();
  6185. auto wrapper = Column( tagCount.second.all() )
  6186. .initialIndent( 0 )
  6187. .indent( str.size() )
  6188. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  6189. Catch::cout() << str << wrapper << '\n';
  6190. }
  6191. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  6192. return tagCounts.size();
  6193. }
  6194. std::size_t listReporters( Config const& /*config*/ ) {
  6195. Catch::cout() << "Available reporters:\n";
  6196. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  6197. std::size_t maxNameLen = 0;
  6198. for( auto const& factoryKvp : factories )
  6199. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  6200. for( auto const& factoryKvp : factories ) {
  6201. Catch::cout()
  6202. << Column( factoryKvp.first + ":" )
  6203. .indent(2)
  6204. .width( 5+maxNameLen )
  6205. + Column( factoryKvp.second->getDescription() )
  6206. .initialIndent(0)
  6207. .indent(2)
  6208. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  6209. << "\n";
  6210. }
  6211. Catch::cout() << std::endl;
  6212. return factories.size();
  6213. }
  6214. Option<std::size_t> list( Config const& config ) {
  6215. Option<std::size_t> listedCount;
  6216. if( config.listTests() )
  6217. listedCount = listedCount.valueOr(0) + listTests( config );
  6218. if( config.listTestNamesOnly() )
  6219. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
  6220. if( config.listTags() )
  6221. listedCount = listedCount.valueOr(0) + listTags( config );
  6222. if( config.listReporters() )
  6223. listedCount = listedCount.valueOr(0) + listReporters( config );
  6224. return listedCount;
  6225. }
  6226. } // end namespace Catch
  6227. // end catch_list.cpp
  6228. // start catch_matchers.cpp
  6229. namespace Catch {
  6230. namespace Matchers {
  6231. namespace Impl {
  6232. std::string MatcherUntypedBase::toString() const {
  6233. if( m_cachedToString.empty() )
  6234. m_cachedToString = describe();
  6235. return m_cachedToString;
  6236. }
  6237. MatcherUntypedBase::~MatcherUntypedBase() = default;
  6238. } // namespace Impl
  6239. } // namespace Matchers
  6240. using namespace Matchers;
  6241. using Matchers::Impl::MatcherBase;
  6242. } // namespace Catch
  6243. // end catch_matchers.cpp
  6244. // start catch_matchers_floating.cpp
  6245. #include <cstdlib>
  6246. #include <cstdint>
  6247. #include <cstring>
  6248. #include <stdexcept>
  6249. namespace Catch {
  6250. namespace Matchers {
  6251. namespace Floating {
  6252. enum class FloatingPointKind : uint8_t {
  6253. Float,
  6254. Double
  6255. };
  6256. }
  6257. }
  6258. }
  6259. namespace {
  6260. template <typename T>
  6261. struct Converter;
  6262. template <>
  6263. struct Converter<float> {
  6264. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  6265. Converter(float f) {
  6266. std::memcpy(&i, &f, sizeof(f));
  6267. }
  6268. int32_t i;
  6269. };
  6270. template <>
  6271. struct Converter<double> {
  6272. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  6273. Converter(double d) {
  6274. std::memcpy(&i, &d, sizeof(d));
  6275. }
  6276. int64_t i;
  6277. };
  6278. template <typename T>
  6279. auto convert(T t) -> Converter<T> {
  6280. return Converter<T>(t);
  6281. }
  6282. template <typename FP>
  6283. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  6284. // Comparison with NaN should always be false.
  6285. // This way we can rule it out before getting into the ugly details
  6286. if (std::isnan(lhs) || std::isnan(rhs)) {
  6287. return false;
  6288. }
  6289. auto lc = convert(lhs);
  6290. auto rc = convert(rhs);
  6291. if ((lc.i < 0) != (rc.i < 0)) {
  6292. // Potentially we can have +0 and -0
  6293. return lhs == rhs;
  6294. }
  6295. auto ulpDiff = std::abs(lc.i - rc.i);
  6296. return ulpDiff <= maxUlpDiff;
  6297. }
  6298. }
  6299. namespace Catch {
  6300. namespace Matchers {
  6301. namespace Floating {
  6302. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  6303. :m_target{ target }, m_margin{ margin } {
  6304. if (m_margin < 0) {
  6305. throw std::domain_error("Allowed margin difference has to be >= 0");
  6306. }
  6307. }
  6308. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6309. // But without the subtraction to allow for INFINITY in comparison
  6310. bool WithinAbsMatcher::match(double const& matchee) const {
  6311. return (matchee + m_margin >= m_target) && (m_target + m_margin >= m_margin);
  6312. }
  6313. std::string WithinAbsMatcher::describe() const {
  6314. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  6315. }
  6316. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  6317. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  6318. if (m_ulps < 0) {
  6319. throw std::domain_error("Allowed ulp difference has to be >= 0");
  6320. }
  6321. }
  6322. bool WithinUlpsMatcher::match(double const& matchee) const {
  6323. switch (m_type) {
  6324. case FloatingPointKind::Float:
  6325. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  6326. case FloatingPointKind::Double:
  6327. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  6328. default:
  6329. throw std::domain_error("Unknown FloatingPointKind value");
  6330. }
  6331. }
  6332. std::string WithinUlpsMatcher::describe() const {
  6333. return "is within " + std::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  6334. }
  6335. }// namespace Floating
  6336. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  6337. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  6338. }
  6339. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  6340. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  6341. }
  6342. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  6343. return Floating::WithinAbsMatcher(target, margin);
  6344. }
  6345. } // namespace Matchers
  6346. } // namespace Catch
  6347. // end catch_matchers_floating.cpp
  6348. // start catch_matchers_string.cpp
  6349. #include <regex>
  6350. namespace Catch {
  6351. namespace Matchers {
  6352. namespace StdString {
  6353. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  6354. : m_caseSensitivity( caseSensitivity ),
  6355. m_str( adjustString( str ) )
  6356. {}
  6357. std::string CasedString::adjustString( std::string const& str ) const {
  6358. return m_caseSensitivity == CaseSensitive::No
  6359. ? toLower( str )
  6360. : str;
  6361. }
  6362. std::string CasedString::caseSensitivitySuffix() const {
  6363. return m_caseSensitivity == CaseSensitive::No
  6364. ? " (case insensitive)"
  6365. : std::string();
  6366. }
  6367. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  6368. : m_comparator( comparator ),
  6369. m_operation( operation ) {
  6370. }
  6371. std::string StringMatcherBase::describe() const {
  6372. std::string description;
  6373. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  6374. m_comparator.caseSensitivitySuffix().size());
  6375. description += m_operation;
  6376. description += ": \"";
  6377. description += m_comparator.m_str;
  6378. description += "\"";
  6379. description += m_comparator.caseSensitivitySuffix();
  6380. return description;
  6381. }
  6382. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  6383. bool EqualsMatcher::match( std::string const& source ) const {
  6384. return m_comparator.adjustString( source ) == m_comparator.m_str;
  6385. }
  6386. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  6387. bool ContainsMatcher::match( std::string const& source ) const {
  6388. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  6389. }
  6390. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  6391. bool StartsWithMatcher::match( std::string const& source ) const {
  6392. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6393. }
  6394. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  6395. bool EndsWithMatcher::match( std::string const& source ) const {
  6396. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6397. }
  6398. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  6399. bool RegexMatcher::match(std::string const& matchee) const {
  6400. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  6401. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  6402. flags |= std::regex::icase;
  6403. }
  6404. auto reg = std::regex(m_regex, flags);
  6405. return std::regex_match(matchee, reg);
  6406. }
  6407. std::string RegexMatcher::describe() const {
  6408. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  6409. }
  6410. } // namespace StdString
  6411. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6412. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  6413. }
  6414. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6415. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  6416. }
  6417. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6418. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  6419. }
  6420. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6421. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  6422. }
  6423. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  6424. return StdString::RegexMatcher(regex, caseSensitivity);
  6425. }
  6426. } // namespace Matchers
  6427. } // namespace Catch
  6428. // end catch_matchers_string.cpp
  6429. // start catch_message.cpp
  6430. // start catch_uncaught_exceptions.h
  6431. namespace Catch {
  6432. bool uncaught_exceptions();
  6433. } // end namespace Catch
  6434. // end catch_uncaught_exceptions.h
  6435. namespace Catch {
  6436. MessageInfo::MessageInfo( std::string const& _macroName,
  6437. SourceLineInfo const& _lineInfo,
  6438. ResultWas::OfType _type )
  6439. : macroName( _macroName ),
  6440. lineInfo( _lineInfo ),
  6441. type( _type ),
  6442. sequence( ++globalCount )
  6443. {}
  6444. bool MessageInfo::operator==( MessageInfo const& other ) const {
  6445. return sequence == other.sequence;
  6446. }
  6447. bool MessageInfo::operator<( MessageInfo const& other ) const {
  6448. return sequence < other.sequence;
  6449. }
  6450. // This may need protecting if threading support is added
  6451. unsigned int MessageInfo::globalCount = 0;
  6452. ////////////////////////////////////////////////////////////////////////////
  6453. Catch::MessageBuilder::MessageBuilder( std::string const& macroName,
  6454. SourceLineInfo const& lineInfo,
  6455. ResultWas::OfType type )
  6456. :m_info(macroName, lineInfo, type) {}
  6457. ////////////////////////////////////////////////////////////////////////////
  6458. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  6459. : m_info( builder.m_info )
  6460. {
  6461. m_info.message = builder.m_stream.str();
  6462. getResultCapture().pushScopedMessage( m_info );
  6463. }
  6464. ScopedMessage::~ScopedMessage() {
  6465. if ( !uncaught_exceptions() ){
  6466. getResultCapture().popScopedMessage(m_info);
  6467. }
  6468. }
  6469. } // end namespace Catch
  6470. // end catch_message.cpp
  6471. // start catch_random_number_generator.cpp
  6472. // start catch_random_number_generator.h
  6473. #include <algorithm>
  6474. namespace Catch {
  6475. struct IConfig;
  6476. void seedRng( IConfig const& config );
  6477. unsigned int rngSeed();
  6478. struct RandomNumberGenerator {
  6479. using result_type = unsigned int;
  6480. static constexpr result_type (min)() { return 0; }
  6481. static constexpr result_type (max)() { return 1000000; }
  6482. result_type operator()( result_type n ) const;
  6483. result_type operator()() const;
  6484. template<typename V>
  6485. static void shuffle( V& vector ) {
  6486. RandomNumberGenerator rng;
  6487. std::shuffle( vector.begin(), vector.end(), rng );
  6488. }
  6489. };
  6490. }
  6491. // end catch_random_number_generator.h
  6492. #include <cstdlib>
  6493. namespace Catch {
  6494. void seedRng( IConfig const& config ) {
  6495. if( config.rngSeed() != 0 )
  6496. std::srand( config.rngSeed() );
  6497. }
  6498. unsigned int rngSeed() {
  6499. return getCurrentContext().getConfig()->rngSeed();
  6500. }
  6501. RandomNumberGenerator::result_type RandomNumberGenerator::operator()( result_type n ) const {
  6502. return std::rand() % n;
  6503. }
  6504. RandomNumberGenerator::result_type RandomNumberGenerator::operator()() const {
  6505. return std::rand() % (max)();
  6506. }
  6507. }
  6508. // end catch_random_number_generator.cpp
  6509. // start catch_registry_hub.cpp
  6510. // start catch_test_case_registry_impl.h
  6511. #include <vector>
  6512. #include <set>
  6513. #include <algorithm>
  6514. #include <ios>
  6515. namespace Catch {
  6516. class TestCase;
  6517. struct IConfig;
  6518. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  6519. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  6520. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  6521. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  6522. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  6523. class TestRegistry : public ITestCaseRegistry {
  6524. public:
  6525. virtual ~TestRegistry() = default;
  6526. virtual void registerTest( TestCase const& testCase );
  6527. std::vector<TestCase> const& getAllTests() const override;
  6528. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  6529. private:
  6530. std::vector<TestCase> m_functions;
  6531. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  6532. mutable std::vector<TestCase> m_sortedFunctions;
  6533. std::size_t m_unnamedCount = 0;
  6534. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  6535. };
  6536. ///////////////////////////////////////////////////////////////////////////
  6537. class TestInvokerAsFunction : public ITestInvoker {
  6538. void(*m_testAsFunction)();
  6539. public:
  6540. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  6541. void invoke() const override;
  6542. };
  6543. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  6544. ///////////////////////////////////////////////////////////////////////////
  6545. } // end namespace Catch
  6546. // end catch_test_case_registry_impl.h
  6547. // start catch_reporter_registry.h
  6548. #include <map>
  6549. namespace Catch {
  6550. class ReporterRegistry : public IReporterRegistry {
  6551. public:
  6552. ~ReporterRegistry() override;
  6553. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  6554. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  6555. void registerListener( IReporterFactoryPtr const& factory );
  6556. FactoryMap const& getFactories() const override;
  6557. Listeners const& getListeners() const override;
  6558. private:
  6559. FactoryMap m_factories;
  6560. Listeners m_listeners;
  6561. };
  6562. }
  6563. // end catch_reporter_registry.h
  6564. // start catch_tag_alias_registry.h
  6565. // start catch_tag_alias.h
  6566. #include <string>
  6567. namespace Catch {
  6568. struct TagAlias {
  6569. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  6570. std::string tag;
  6571. SourceLineInfo lineInfo;
  6572. };
  6573. } // end namespace Catch
  6574. // end catch_tag_alias.h
  6575. #include <map>
  6576. namespace Catch {
  6577. class TagAliasRegistry : public ITagAliasRegistry {
  6578. public:
  6579. ~TagAliasRegistry() override;
  6580. TagAlias const* find( std::string const& alias ) const override;
  6581. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  6582. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  6583. private:
  6584. std::map<std::string, TagAlias> m_registry;
  6585. };
  6586. } // end namespace Catch
  6587. // end catch_tag_alias_registry.h
  6588. // start catch_startup_exception_registry.h
  6589. #include <vector>
  6590. #include <exception>
  6591. namespace Catch {
  6592. class StartupExceptionRegistry {
  6593. public:
  6594. void add(std::exception_ptr const& exception) noexcept;
  6595. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  6596. private:
  6597. std::vector<std::exception_ptr> m_exceptions;
  6598. };
  6599. } // end namespace Catch
  6600. // end catch_startup_exception_registry.h
  6601. namespace Catch {
  6602. namespace {
  6603. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  6604. private NonCopyable {
  6605. public: // IRegistryHub
  6606. RegistryHub() = default;
  6607. IReporterRegistry const& getReporterRegistry() const override {
  6608. return m_reporterRegistry;
  6609. }
  6610. ITestCaseRegistry const& getTestCaseRegistry() const override {
  6611. return m_testCaseRegistry;
  6612. }
  6613. IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() override {
  6614. return m_exceptionTranslatorRegistry;
  6615. }
  6616. ITagAliasRegistry const& getTagAliasRegistry() const override {
  6617. return m_tagAliasRegistry;
  6618. }
  6619. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  6620. return m_exceptionRegistry;
  6621. }
  6622. public: // IMutableRegistryHub
  6623. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  6624. m_reporterRegistry.registerReporter( name, factory );
  6625. }
  6626. void registerListener( IReporterFactoryPtr const& factory ) override {
  6627. m_reporterRegistry.registerListener( factory );
  6628. }
  6629. void registerTest( TestCase const& testInfo ) override {
  6630. m_testCaseRegistry.registerTest( testInfo );
  6631. }
  6632. void registerTranslator( const IExceptionTranslator* translator ) override {
  6633. m_exceptionTranslatorRegistry.registerTranslator( translator );
  6634. }
  6635. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  6636. m_tagAliasRegistry.add( alias, tag, lineInfo );
  6637. }
  6638. void registerStartupException() noexcept override {
  6639. m_exceptionRegistry.add(std::current_exception());
  6640. }
  6641. private:
  6642. TestRegistry m_testCaseRegistry;
  6643. ReporterRegistry m_reporterRegistry;
  6644. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  6645. TagAliasRegistry m_tagAliasRegistry;
  6646. StartupExceptionRegistry m_exceptionRegistry;
  6647. };
  6648. // Single, global, instance
  6649. RegistryHub*& getTheRegistryHub() {
  6650. static RegistryHub* theRegistryHub = nullptr;
  6651. if( !theRegistryHub )
  6652. theRegistryHub = new RegistryHub();
  6653. return theRegistryHub;
  6654. }
  6655. }
  6656. IRegistryHub& getRegistryHub() {
  6657. return *getTheRegistryHub();
  6658. }
  6659. IMutableRegistryHub& getMutableRegistryHub() {
  6660. return *getTheRegistryHub();
  6661. }
  6662. void cleanUp() {
  6663. delete getTheRegistryHub();
  6664. getTheRegistryHub() = nullptr;
  6665. cleanUpContext();
  6666. ReusableStringStream::cleanup();
  6667. }
  6668. std::string translateActiveException() {
  6669. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  6670. }
  6671. } // end namespace Catch
  6672. // end catch_registry_hub.cpp
  6673. // start catch_reporter_registry.cpp
  6674. namespace Catch {
  6675. ReporterRegistry::~ReporterRegistry() = default;
  6676. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  6677. auto it = m_factories.find( name );
  6678. if( it == m_factories.end() )
  6679. return nullptr;
  6680. return it->second->create( ReporterConfig( config ) );
  6681. }
  6682. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  6683. m_factories.emplace(name, factory);
  6684. }
  6685. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  6686. m_listeners.push_back( factory );
  6687. }
  6688. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  6689. return m_factories;
  6690. }
  6691. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  6692. return m_listeners;
  6693. }
  6694. }
  6695. // end catch_reporter_registry.cpp
  6696. // start catch_result_type.cpp
  6697. namespace Catch {
  6698. bool isOk( ResultWas::OfType resultType ) {
  6699. return ( resultType & ResultWas::FailureBit ) == 0;
  6700. }
  6701. bool isJustInfo( int flags ) {
  6702. return flags == ResultWas::Info;
  6703. }
  6704. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  6705. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  6706. }
  6707. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  6708. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  6709. } // end namespace Catch
  6710. // end catch_result_type.cpp
  6711. // start catch_run_context.cpp
  6712. #include <cassert>
  6713. #include <algorithm>
  6714. #include <sstream>
  6715. namespace Catch {
  6716. class RedirectedStream {
  6717. std::ostream& m_originalStream;
  6718. std::ostream& m_redirectionStream;
  6719. std::streambuf* m_prevBuf;
  6720. public:
  6721. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  6722. : m_originalStream( originalStream ),
  6723. m_redirectionStream( redirectionStream ),
  6724. m_prevBuf( m_originalStream.rdbuf() )
  6725. {
  6726. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  6727. }
  6728. ~RedirectedStream() {
  6729. m_originalStream.rdbuf( m_prevBuf );
  6730. }
  6731. };
  6732. class RedirectedStdOut {
  6733. ReusableStringStream m_rss;
  6734. RedirectedStream m_cout;
  6735. public:
  6736. RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  6737. auto str() const -> std::string { return m_rss.str(); }
  6738. };
  6739. // StdErr has two constituent streams in C++, std::cerr and std::clog
  6740. // This means that we need to redirect 2 streams into 1 to keep proper
  6741. // order of writes
  6742. class RedirectedStdErr {
  6743. ReusableStringStream m_rss;
  6744. RedirectedStream m_cerr;
  6745. RedirectedStream m_clog;
  6746. public:
  6747. RedirectedStdErr()
  6748. : m_cerr( Catch::cerr(), m_rss.get() ),
  6749. m_clog( Catch::clog(), m_rss.get() )
  6750. {}
  6751. auto str() const -> std::string { return m_rss.str(); }
  6752. };
  6753. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  6754. : m_runInfo(_config->name()),
  6755. m_context(getCurrentMutableContext()),
  6756. m_config(_config),
  6757. m_reporter(std::move(reporter)),
  6758. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  6759. m_includeSuccessfulResults( m_config->includeSuccessfulResults() )
  6760. {
  6761. m_context.setRunner(this);
  6762. m_context.setConfig(m_config);
  6763. m_context.setResultCapture(this);
  6764. m_reporter->testRunStarting(m_runInfo);
  6765. }
  6766. RunContext::~RunContext() {
  6767. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  6768. }
  6769. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  6770. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  6771. }
  6772. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  6773. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  6774. }
  6775. Totals RunContext::runTest(TestCase const& testCase) {
  6776. Totals prevTotals = m_totals;
  6777. std::string redirectedCout;
  6778. std::string redirectedCerr;
  6779. auto const& testInfo = testCase.getTestCaseInfo();
  6780. m_reporter->testCaseStarting(testInfo);
  6781. m_activeTestCase = &testCase;
  6782. ITracker& rootTracker = m_trackerContext.startRun();
  6783. assert(rootTracker.isSectionTracker());
  6784. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  6785. do {
  6786. m_trackerContext.startCycle();
  6787. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  6788. runCurrentTest(redirectedCout, redirectedCerr);
  6789. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  6790. Totals deltaTotals = m_totals.delta(prevTotals);
  6791. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  6792. deltaTotals.assertions.failed++;
  6793. deltaTotals.testCases.passed--;
  6794. deltaTotals.testCases.failed++;
  6795. }
  6796. m_totals.testCases += deltaTotals.testCases;
  6797. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  6798. deltaTotals,
  6799. redirectedCout,
  6800. redirectedCerr,
  6801. aborting()));
  6802. m_activeTestCase = nullptr;
  6803. m_testCaseTracker = nullptr;
  6804. return deltaTotals;
  6805. }
  6806. IConfigPtr RunContext::config() const {
  6807. return m_config;
  6808. }
  6809. IStreamingReporter& RunContext::reporter() const {
  6810. return *m_reporter;
  6811. }
  6812. void RunContext::assertionEnded(AssertionResult const & result) {
  6813. if (result.getResultType() == ResultWas::Ok) {
  6814. m_totals.assertions.passed++;
  6815. m_lastAssertionPassed = true;
  6816. } else if (!result.isOk()) {
  6817. m_lastAssertionPassed = false;
  6818. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  6819. m_totals.assertions.failedButOk++;
  6820. else
  6821. m_totals.assertions.failed++;
  6822. }
  6823. else {
  6824. m_lastAssertionPassed = true;
  6825. }
  6826. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  6827. // and should be let to clear themselves out.
  6828. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  6829. // Reset working state
  6830. resetAssertionInfo();
  6831. m_lastResult = result;
  6832. }
  6833. void RunContext::resetAssertionInfo() {
  6834. m_lastAssertionInfo.macroName = StringRef();
  6835. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  6836. }
  6837. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  6838. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  6839. if (!sectionTracker.isOpen())
  6840. return false;
  6841. m_activeSections.push_back(&sectionTracker);
  6842. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  6843. m_reporter->sectionStarting(sectionInfo);
  6844. assertions = m_totals.assertions;
  6845. return true;
  6846. }
  6847. bool RunContext::testForMissingAssertions(Counts& assertions) {
  6848. if (assertions.total() != 0)
  6849. return false;
  6850. if (!m_config->warnAboutMissingAssertions())
  6851. return false;
  6852. if (m_trackerContext.currentTracker().hasChildren())
  6853. return false;
  6854. m_totals.assertions.failed++;
  6855. assertions.failed++;
  6856. return true;
  6857. }
  6858. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  6859. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  6860. bool missingAssertions = testForMissingAssertions(assertions);
  6861. if (!m_activeSections.empty()) {
  6862. m_activeSections.back()->close();
  6863. m_activeSections.pop_back();
  6864. }
  6865. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  6866. m_messages.clear();
  6867. }
  6868. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  6869. if (m_unfinishedSections.empty())
  6870. m_activeSections.back()->fail();
  6871. else
  6872. m_activeSections.back()->close();
  6873. m_activeSections.pop_back();
  6874. m_unfinishedSections.push_back(endInfo);
  6875. }
  6876. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  6877. m_reporter->benchmarkStarting( info );
  6878. }
  6879. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  6880. m_reporter->benchmarkEnded( stats );
  6881. }
  6882. void RunContext::pushScopedMessage(MessageInfo const & message) {
  6883. m_messages.push_back(message);
  6884. }
  6885. void RunContext::popScopedMessage(MessageInfo const & message) {
  6886. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  6887. }
  6888. std::string RunContext::getCurrentTestName() const {
  6889. return m_activeTestCase
  6890. ? m_activeTestCase->getTestCaseInfo().name
  6891. : std::string();
  6892. }
  6893. const AssertionResult * RunContext::getLastResult() const {
  6894. return &(*m_lastResult);
  6895. }
  6896. void RunContext::exceptionEarlyReported() {
  6897. m_shouldReportUnexpected = false;
  6898. }
  6899. void RunContext::handleFatalErrorCondition( StringRef message ) {
  6900. // First notify reporter that bad things happened
  6901. m_reporter->fatalErrorEncountered(message);
  6902. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  6903. // Instead, fake a result data.
  6904. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  6905. tempResult.message = message;
  6906. AssertionResult result(m_lastAssertionInfo, tempResult);
  6907. assertionEnded(result);
  6908. handleUnfinishedSections();
  6909. // Recreate section for test case (as we will lose the one that was in scope)
  6910. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  6911. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  6912. Counts assertions;
  6913. assertions.failed = 1;
  6914. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  6915. m_reporter->sectionEnded(testCaseSectionStats);
  6916. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  6917. Totals deltaTotals;
  6918. deltaTotals.testCases.failed = 1;
  6919. deltaTotals.assertions.failed = 1;
  6920. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  6921. deltaTotals,
  6922. std::string(),
  6923. std::string(),
  6924. false));
  6925. m_totals.testCases.failed++;
  6926. testGroupEnded(std::string(), m_totals, 1, 1);
  6927. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  6928. }
  6929. bool RunContext::lastAssertionPassed() {
  6930. return m_lastAssertionPassed;
  6931. }
  6932. void RunContext::assertionPassed() {
  6933. m_lastAssertionPassed = true;
  6934. ++m_totals.assertions.passed;
  6935. resetAssertionInfo();
  6936. }
  6937. bool RunContext::aborting() const {
  6938. return m_totals.assertions.failed == static_cast<std::size_t>(m_config->abortAfter());
  6939. }
  6940. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  6941. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  6942. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description);
  6943. m_reporter->sectionStarting(testCaseSection);
  6944. Counts prevAssertions = m_totals.assertions;
  6945. double duration = 0;
  6946. m_shouldReportUnexpected = true;
  6947. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  6948. seedRng(*m_config);
  6949. Timer timer;
  6950. try {
  6951. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  6952. RedirectedStdOut redirectedStdOut;
  6953. RedirectedStdErr redirectedStdErr;
  6954. timer.start();
  6955. invokeActiveTestCase();
  6956. redirectedCout += redirectedStdOut.str();
  6957. redirectedCerr += redirectedStdErr.str();
  6958. } else {
  6959. timer.start();
  6960. invokeActiveTestCase();
  6961. }
  6962. duration = timer.getElapsedSeconds();
  6963. } catch (TestFailureException&) {
  6964. // This just means the test was aborted due to failure
  6965. } catch (...) {
  6966. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  6967. // are reported without translation at the point of origin.
  6968. if( m_shouldReportUnexpected ) {
  6969. AssertionReaction dummyReaction;
  6970. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  6971. }
  6972. }
  6973. Counts assertions = m_totals.assertions - prevAssertions;
  6974. bool missingAssertions = testForMissingAssertions(assertions);
  6975. m_testCaseTracker->close();
  6976. handleUnfinishedSections();
  6977. m_messages.clear();
  6978. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  6979. m_reporter->sectionEnded(testCaseSectionStats);
  6980. }
  6981. void RunContext::invokeActiveTestCase() {
  6982. FatalConditionHandler fatalConditionHandler; // Handle signals
  6983. m_activeTestCase->invoke();
  6984. fatalConditionHandler.reset();
  6985. }
  6986. void RunContext::handleUnfinishedSections() {
  6987. // If sections ended prematurely due to an exception we stored their
  6988. // infos here so we can tear them down outside the unwind process.
  6989. for (auto it = m_unfinishedSections.rbegin(),
  6990. itEnd = m_unfinishedSections.rend();
  6991. it != itEnd;
  6992. ++it)
  6993. sectionEnded(*it);
  6994. m_unfinishedSections.clear();
  6995. }
  6996. void RunContext::handleExpr(
  6997. AssertionInfo const& info,
  6998. ITransientExpression const& expr,
  6999. AssertionReaction& reaction
  7000. ) {
  7001. m_reporter->assertionStarting( info );
  7002. bool negated = isFalseTest( info.resultDisposition );
  7003. bool result = expr.getResult() != negated;
  7004. if( result ) {
  7005. if (!m_includeSuccessfulResults) {
  7006. assertionPassed();
  7007. }
  7008. else {
  7009. reportExpr(info, ResultWas::Ok, &expr, negated);
  7010. }
  7011. }
  7012. else {
  7013. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  7014. populateReaction( reaction );
  7015. }
  7016. }
  7017. void RunContext::reportExpr(
  7018. AssertionInfo const &info,
  7019. ResultWas::OfType resultType,
  7020. ITransientExpression const *expr,
  7021. bool negated ) {
  7022. m_lastAssertionInfo = info;
  7023. AssertionResultData data( resultType, LazyExpression( negated ) );
  7024. AssertionResult assertionResult{ info, data };
  7025. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  7026. assertionEnded( assertionResult );
  7027. }
  7028. void RunContext::handleMessage(
  7029. AssertionInfo const& info,
  7030. ResultWas::OfType resultType,
  7031. StringRef const& message,
  7032. AssertionReaction& reaction
  7033. ) {
  7034. m_reporter->assertionStarting( info );
  7035. m_lastAssertionInfo = info;
  7036. AssertionResultData data( resultType, LazyExpression( false ) );
  7037. data.message = message;
  7038. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  7039. assertionEnded( assertionResult );
  7040. if( !assertionResult.isOk() )
  7041. populateReaction( reaction );
  7042. }
  7043. void RunContext::handleUnexpectedExceptionNotThrown(
  7044. AssertionInfo const& info,
  7045. AssertionReaction& reaction
  7046. ) {
  7047. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  7048. }
  7049. void RunContext::handleUnexpectedInflightException(
  7050. AssertionInfo const& info,
  7051. std::string const& message,
  7052. AssertionReaction& reaction
  7053. ) {
  7054. m_lastAssertionInfo = info;
  7055. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  7056. data.message = message;
  7057. AssertionResult assertionResult{ info, data };
  7058. assertionEnded( assertionResult );
  7059. populateReaction( reaction );
  7060. }
  7061. void RunContext::populateReaction( AssertionReaction& reaction ) {
  7062. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  7063. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  7064. }
  7065. void RunContext::handleIncomplete(
  7066. AssertionInfo const& info
  7067. ) {
  7068. m_lastAssertionInfo = info;
  7069. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  7070. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  7071. AssertionResult assertionResult{ info, data };
  7072. assertionEnded( assertionResult );
  7073. }
  7074. void RunContext::handleNonExpr(
  7075. AssertionInfo const &info,
  7076. ResultWas::OfType resultType,
  7077. AssertionReaction &reaction
  7078. ) {
  7079. m_lastAssertionInfo = info;
  7080. AssertionResultData data( resultType, LazyExpression( false ) );
  7081. AssertionResult assertionResult{ info, data };
  7082. assertionEnded( assertionResult );
  7083. if( !assertionResult.isOk() )
  7084. populateReaction( reaction );
  7085. }
  7086. IResultCapture& getResultCapture() {
  7087. if (auto* capture = getCurrentContext().getResultCapture())
  7088. return *capture;
  7089. else
  7090. CATCH_INTERNAL_ERROR("No result capture instance");
  7091. }
  7092. }
  7093. // end catch_run_context.cpp
  7094. // start catch_section.cpp
  7095. namespace Catch {
  7096. Section::Section( SectionInfo const& info )
  7097. : m_info( info ),
  7098. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  7099. {
  7100. m_timer.start();
  7101. }
  7102. Section::~Section() {
  7103. if( m_sectionIncluded ) {
  7104. SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() );
  7105. if( uncaught_exceptions() )
  7106. getResultCapture().sectionEndedEarly( endInfo );
  7107. else
  7108. getResultCapture().sectionEnded( endInfo );
  7109. }
  7110. }
  7111. // This indicates whether the section should be executed or not
  7112. Section::operator bool() const {
  7113. return m_sectionIncluded;
  7114. }
  7115. } // end namespace Catch
  7116. // end catch_section.cpp
  7117. // start catch_section_info.cpp
  7118. namespace Catch {
  7119. SectionInfo::SectionInfo
  7120. ( SourceLineInfo const& _lineInfo,
  7121. std::string const& _name,
  7122. std::string const& _description )
  7123. : name( _name ),
  7124. description( _description ),
  7125. lineInfo( _lineInfo )
  7126. {}
  7127. SectionEndInfo::SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds )
  7128. : sectionInfo( _sectionInfo ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds )
  7129. {}
  7130. } // end namespace Catch
  7131. // end catch_section_info.cpp
  7132. // start catch_session.cpp
  7133. // start catch_session.h
  7134. #include <memory>
  7135. namespace Catch {
  7136. class Session : NonCopyable {
  7137. public:
  7138. Session();
  7139. ~Session() override;
  7140. void showHelp() const;
  7141. void libIdentify();
  7142. int applyCommandLine( int argc, char const * const * argv );
  7143. void useConfigData( ConfigData const& configData );
  7144. int run( int argc, char* argv[] );
  7145. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  7146. int run( int argc, wchar_t* const argv[] );
  7147. #endif
  7148. int run();
  7149. clara::Parser const& cli() const;
  7150. void cli( clara::Parser const& newParser );
  7151. ConfigData& configData();
  7152. Config& config();
  7153. private:
  7154. int runInternal();
  7155. clara::Parser m_cli;
  7156. ConfigData m_configData;
  7157. std::shared_ptr<Config> m_config;
  7158. bool m_startupExceptions = false;
  7159. };
  7160. } // end namespace Catch
  7161. // end catch_session.h
  7162. // start catch_version.h
  7163. #include <iosfwd>
  7164. namespace Catch {
  7165. // Versioning information
  7166. struct Version {
  7167. Version( Version const& ) = delete;
  7168. Version& operator=( Version const& ) = delete;
  7169. Version( unsigned int _majorVersion,
  7170. unsigned int _minorVersion,
  7171. unsigned int _patchNumber,
  7172. char const * const _branchName,
  7173. unsigned int _buildNumber );
  7174. unsigned int const majorVersion;
  7175. unsigned int const minorVersion;
  7176. unsigned int const patchNumber;
  7177. // buildNumber is only used if branchName is not null
  7178. char const * const branchName;
  7179. unsigned int const buildNumber;
  7180. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  7181. };
  7182. Version const& libraryVersion();
  7183. }
  7184. // end catch_version.h
  7185. #include <cstdlib>
  7186. #include <iomanip>
  7187. namespace Catch {
  7188. namespace {
  7189. const int MaxExitCode = 255;
  7190. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  7191. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  7192. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  7193. return reporter;
  7194. }
  7195. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  7196. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  7197. #endif
  7198. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  7199. auto const& reporterNames = config->getReporterNames();
  7200. if (reporterNames.empty())
  7201. return createReporter(CATCH_CONFIG_DEFAULT_REPORTER, config);
  7202. IStreamingReporterPtr reporter;
  7203. for (auto const& name : reporterNames)
  7204. addReporter(reporter, createReporter(name, config));
  7205. return reporter;
  7206. }
  7207. #undef CATCH_CONFIG_DEFAULT_REPORTER
  7208. void addListeners(IStreamingReporterPtr& reporters, IConfigPtr const& config) {
  7209. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  7210. for (auto const& listener : listeners)
  7211. addReporter(reporters, listener->create(Catch::ReporterConfig(config)));
  7212. }
  7213. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  7214. IStreamingReporterPtr reporter = makeReporter(config);
  7215. addListeners(reporter, config);
  7216. RunContext context(config, std::move(reporter));
  7217. Totals totals;
  7218. context.testGroupStarting(config->name(), 1, 1);
  7219. TestSpec testSpec = config->testSpec();
  7220. auto const& allTestCases = getAllTestCasesSorted(*config);
  7221. for (auto const& testCase : allTestCases) {
  7222. if (!context.aborting() && matchTest(testCase, testSpec, *config))
  7223. totals += context.runTest(testCase);
  7224. else
  7225. context.reporter().skipTest(testCase);
  7226. }
  7227. if (config->warnAboutNoTests() && totals.testCases.total() == 0) {
  7228. ReusableStringStream testConfig;
  7229. bool first = true;
  7230. for (const auto& input : config->getTestsOrTags()) {
  7231. if (!first) { testConfig << ' '; }
  7232. first = false;
  7233. testConfig << input;
  7234. }
  7235. context.reporter().noMatchingTestCases(testConfig.str());
  7236. totals.error = -1;
  7237. }
  7238. context.testGroupEnded(config->name(), totals, 1, 1);
  7239. return totals;
  7240. }
  7241. void applyFilenamesAsTags(Catch::IConfig const& config) {
  7242. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  7243. for (auto& testCase : tests) {
  7244. auto tags = testCase.tags;
  7245. std::string filename = testCase.lineInfo.file;
  7246. auto lastSlash = filename.find_last_of("\\/");
  7247. if (lastSlash != std::string::npos) {
  7248. filename.erase(0, lastSlash);
  7249. filename[0] = '#';
  7250. }
  7251. auto lastDot = filename.find_last_of('.');
  7252. if (lastDot != std::string::npos) {
  7253. filename.erase(lastDot);
  7254. }
  7255. tags.push_back(std::move(filename));
  7256. setTags(testCase, tags);
  7257. }
  7258. }
  7259. } // anon namespace
  7260. Session::Session() {
  7261. static bool alreadyInstantiated = false;
  7262. if( alreadyInstantiated ) {
  7263. try { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  7264. catch(...) { getMutableRegistryHub().registerStartupException(); }
  7265. }
  7266. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  7267. if ( !exceptions.empty() ) {
  7268. m_startupExceptions = true;
  7269. Colour colourGuard( Colour::Red );
  7270. Catch::cerr() << "Errors occurred during startup!" << '\n';
  7271. // iterate over all exceptions and notify user
  7272. for ( const auto& ex_ptr : exceptions ) {
  7273. try {
  7274. std::rethrow_exception(ex_ptr);
  7275. } catch ( std::exception const& ex ) {
  7276. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  7277. }
  7278. }
  7279. }
  7280. alreadyInstantiated = true;
  7281. m_cli = makeCommandLineParser( m_configData );
  7282. }
  7283. Session::~Session() {
  7284. Catch::cleanUp();
  7285. }
  7286. void Session::showHelp() const {
  7287. Catch::cout()
  7288. << "\nCatch v" << libraryVersion() << "\n"
  7289. << m_cli << std::endl
  7290. << "For more detailed usage please see the project docs\n" << std::endl;
  7291. }
  7292. void Session::libIdentify() {
  7293. Catch::cout()
  7294. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  7295. << std::left << std::setw(16) << "category: " << "testframework\n"
  7296. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  7297. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  7298. }
  7299. int Session::applyCommandLine( int argc, char const * const * argv ) {
  7300. if( m_startupExceptions )
  7301. return 1;
  7302. auto result = m_cli.parse( clara::Args( argc, argv ) );
  7303. if( !result ) {
  7304. Catch::cerr()
  7305. << Colour( Colour::Red )
  7306. << "\nError(s) in input:\n"
  7307. << Column( result.errorMessage() ).indent( 2 )
  7308. << "\n\n";
  7309. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  7310. return MaxExitCode;
  7311. }
  7312. if( m_configData.showHelp )
  7313. showHelp();
  7314. if( m_configData.libIdentify )
  7315. libIdentify();
  7316. m_config.reset();
  7317. return 0;
  7318. }
  7319. void Session::useConfigData( ConfigData const& configData ) {
  7320. m_configData = configData;
  7321. m_config.reset();
  7322. }
  7323. int Session::run( int argc, char* argv[] ) {
  7324. if( m_startupExceptions )
  7325. return 1;
  7326. int returnCode = applyCommandLine( argc, argv );
  7327. if( returnCode == 0 )
  7328. returnCode = run();
  7329. return returnCode;
  7330. }
  7331. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  7332. int Session::run( int argc, wchar_t* const argv[] ) {
  7333. char **utf8Argv = new char *[ argc ];
  7334. for ( int i = 0; i < argc; ++i ) {
  7335. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  7336. utf8Argv[ i ] = new char[ bufSize ];
  7337. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  7338. }
  7339. int returnCode = run( argc, utf8Argv );
  7340. for ( int i = 0; i < argc; ++i )
  7341. delete [] utf8Argv[ i ];
  7342. delete [] utf8Argv;
  7343. return returnCode;
  7344. }
  7345. #endif
  7346. int Session::run() {
  7347. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  7348. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  7349. static_cast<void>(std::getchar());
  7350. }
  7351. int exitCode = runInternal();
  7352. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  7353. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  7354. static_cast<void>(std::getchar());
  7355. }
  7356. return exitCode;
  7357. }
  7358. clara::Parser const& Session::cli() const {
  7359. return m_cli;
  7360. }
  7361. void Session::cli( clara::Parser const& newParser ) {
  7362. m_cli = newParser;
  7363. }
  7364. ConfigData& Session::configData() {
  7365. return m_configData;
  7366. }
  7367. Config& Session::config() {
  7368. if( !m_config )
  7369. m_config = std::make_shared<Config>( m_configData );
  7370. return *m_config;
  7371. }
  7372. int Session::runInternal() {
  7373. if( m_startupExceptions )
  7374. return 1;
  7375. if( m_configData.showHelp || m_configData.libIdentify )
  7376. return 0;
  7377. try
  7378. {
  7379. config(); // Force config to be constructed
  7380. seedRng( *m_config );
  7381. if( m_configData.filenamesAsTags )
  7382. applyFilenamesAsTags( *m_config );
  7383. // Handle list request
  7384. if( Option<std::size_t> listed = list( config() ) )
  7385. return static_cast<int>( *listed );
  7386. auto totals = runTests( m_config );
  7387. // Note that on unices only the lower 8 bits are usually used, clamping
  7388. // the return value to 255 prevents false negative when some multiple
  7389. // of 256 tests has failed
  7390. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  7391. }
  7392. catch( std::exception& ex ) {
  7393. Catch::cerr() << ex.what() << std::endl;
  7394. return MaxExitCode;
  7395. }
  7396. }
  7397. } // end namespace Catch
  7398. // end catch_session.cpp
  7399. // start catch_startup_exception_registry.cpp
  7400. namespace Catch {
  7401. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  7402. try {
  7403. m_exceptions.push_back(exception);
  7404. }
  7405. catch(...) {
  7406. // If we run out of memory during start-up there's really not a lot more we can do about it
  7407. std::terminate();
  7408. }
  7409. }
  7410. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  7411. return m_exceptions;
  7412. }
  7413. } // end namespace Catch
  7414. // end catch_startup_exception_registry.cpp
  7415. // start catch_stream.cpp
  7416. #include <cstdio>
  7417. #include <iostream>
  7418. #include <fstream>
  7419. #include <sstream>
  7420. #include <vector>
  7421. #include <memory>
  7422. #if defined(__clang__)
  7423. # pragma clang diagnostic push
  7424. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7425. #endif
  7426. namespace Catch {
  7427. Catch::IStream::~IStream() = default;
  7428. namespace detail { namespace {
  7429. template<typename WriterF, std::size_t bufferSize=256>
  7430. class StreamBufImpl : public std::streambuf {
  7431. char data[bufferSize];
  7432. WriterF m_writer;
  7433. public:
  7434. StreamBufImpl() {
  7435. setp( data, data + sizeof(data) );
  7436. }
  7437. ~StreamBufImpl() noexcept {
  7438. StreamBufImpl::sync();
  7439. }
  7440. private:
  7441. int overflow( int c ) override {
  7442. sync();
  7443. if( c != EOF ) {
  7444. if( pbase() == epptr() )
  7445. m_writer( std::string( 1, static_cast<char>( c ) ) );
  7446. else
  7447. sputc( static_cast<char>( c ) );
  7448. }
  7449. return 0;
  7450. }
  7451. int sync() override {
  7452. if( pbase() != pptr() ) {
  7453. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  7454. setp( pbase(), epptr() );
  7455. }
  7456. return 0;
  7457. }
  7458. };
  7459. ///////////////////////////////////////////////////////////////////////////
  7460. struct OutputDebugWriter {
  7461. void operator()( std::string const&str ) {
  7462. writeToDebugConsole( str );
  7463. }
  7464. };
  7465. ///////////////////////////////////////////////////////////////////////////
  7466. class FileStream : public IStream {
  7467. mutable std::ofstream m_ofs;
  7468. public:
  7469. FileStream( StringRef filename ) {
  7470. m_ofs.open( filename.c_str() );
  7471. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  7472. }
  7473. ~FileStream() override = default;
  7474. public: // IStream
  7475. std::ostream& stream() const override {
  7476. return m_ofs;
  7477. }
  7478. };
  7479. ///////////////////////////////////////////////////////////////////////////
  7480. class CoutStream : public IStream {
  7481. mutable std::ostream m_os;
  7482. public:
  7483. // Store the streambuf from cout up-front because
  7484. // cout may get redirected when running tests
  7485. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  7486. ~CoutStream() override = default;
  7487. public: // IStream
  7488. std::ostream& stream() const override { return m_os; }
  7489. };
  7490. ///////////////////////////////////////////////////////////////////////////
  7491. class DebugOutStream : public IStream {
  7492. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  7493. mutable std::ostream m_os;
  7494. public:
  7495. DebugOutStream()
  7496. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  7497. m_os( m_streamBuf.get() )
  7498. {}
  7499. ~DebugOutStream() override = default;
  7500. public: // IStream
  7501. std::ostream& stream() const override { return m_os; }
  7502. };
  7503. }} // namespace anon::detail
  7504. ///////////////////////////////////////////////////////////////////////////
  7505. auto makeStream( StringRef const &filename ) -> IStream const* {
  7506. if( filename.empty() )
  7507. return new detail::CoutStream();
  7508. else if( filename[0] == '%' ) {
  7509. if( filename == "%debug" )
  7510. return new detail::DebugOutStream();
  7511. else
  7512. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  7513. }
  7514. else
  7515. return new detail::FileStream( filename );
  7516. }
  7517. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  7518. struct StringStreams {
  7519. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  7520. std::vector<std::size_t> m_unused;
  7521. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  7522. static StringStreams* s_instance;
  7523. auto add() -> std::size_t {
  7524. if( m_unused.empty() ) {
  7525. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  7526. return m_streams.size()-1;
  7527. }
  7528. else {
  7529. auto index = m_unused.back();
  7530. m_unused.pop_back();
  7531. return index;
  7532. }
  7533. }
  7534. void release( std::size_t index ) {
  7535. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  7536. m_unused.push_back(index);
  7537. }
  7538. // !TBD: put in TLS
  7539. static auto instance() -> StringStreams& {
  7540. if( !s_instance )
  7541. s_instance = new StringStreams();
  7542. return *s_instance;
  7543. }
  7544. static void cleanup() {
  7545. delete s_instance;
  7546. s_instance = nullptr;
  7547. }
  7548. };
  7549. StringStreams* StringStreams::s_instance = nullptr;
  7550. void ReusableStringStream::cleanup() {
  7551. StringStreams::cleanup();
  7552. }
  7553. ReusableStringStream::ReusableStringStream()
  7554. : m_index( StringStreams::instance().add() ),
  7555. m_oss( StringStreams::instance().m_streams[m_index].get() )
  7556. {}
  7557. ReusableStringStream::~ReusableStringStream() {
  7558. static_cast<std::ostringstream*>( m_oss )->str("");
  7559. m_oss->clear();
  7560. StringStreams::instance().release( m_index );
  7561. }
  7562. auto ReusableStringStream::str() const -> std::string {
  7563. return static_cast<std::ostringstream*>( m_oss )->str();
  7564. }
  7565. ///////////////////////////////////////////////////////////////////////////
  7566. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  7567. std::ostream& cout() { return std::cout; }
  7568. std::ostream& cerr() { return std::cerr; }
  7569. std::ostream& clog() { return std::clog; }
  7570. #endif
  7571. }
  7572. #if defined(__clang__)
  7573. # pragma clang diagnostic pop
  7574. #endif
  7575. // end catch_stream.cpp
  7576. // start catch_string_manip.cpp
  7577. #include <algorithm>
  7578. #include <ostream>
  7579. #include <cstring>
  7580. #include <cctype>
  7581. namespace Catch {
  7582. bool startsWith( std::string const& s, std::string const& prefix ) {
  7583. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  7584. }
  7585. bool startsWith( std::string const& s, char prefix ) {
  7586. return !s.empty() && s[0] == prefix;
  7587. }
  7588. bool endsWith( std::string const& s, std::string const& suffix ) {
  7589. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  7590. }
  7591. bool endsWith( std::string const& s, char suffix ) {
  7592. return !s.empty() && s[s.size()-1] == suffix;
  7593. }
  7594. bool contains( std::string const& s, std::string const& infix ) {
  7595. return s.find( infix ) != std::string::npos;
  7596. }
  7597. char toLowerCh(char c) {
  7598. return static_cast<char>( std::tolower( c ) );
  7599. }
  7600. void toLowerInPlace( std::string& s ) {
  7601. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  7602. }
  7603. std::string toLower( std::string const& s ) {
  7604. std::string lc = s;
  7605. toLowerInPlace( lc );
  7606. return lc;
  7607. }
  7608. std::string trim( std::string const& str ) {
  7609. static char const* whitespaceChars = "\n\r\t ";
  7610. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  7611. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  7612. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  7613. }
  7614. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  7615. bool replaced = false;
  7616. std::size_t i = str.find( replaceThis );
  7617. while( i != std::string::npos ) {
  7618. replaced = true;
  7619. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  7620. if( i < str.size()-withThis.size() )
  7621. i = str.find( replaceThis, i+withThis.size() );
  7622. else
  7623. i = std::string::npos;
  7624. }
  7625. return replaced;
  7626. }
  7627. pluralise::pluralise( std::size_t count, std::string const& label )
  7628. : m_count( count ),
  7629. m_label( label )
  7630. {}
  7631. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  7632. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  7633. if( pluraliser.m_count != 1 )
  7634. os << 's';
  7635. return os;
  7636. }
  7637. }
  7638. // end catch_string_manip.cpp
  7639. // start catch_stringref.cpp
  7640. #if defined(__clang__)
  7641. # pragma clang diagnostic push
  7642. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7643. #endif
  7644. #include <ostream>
  7645. #include <cstring>
  7646. #include <cstdint>
  7647. namespace {
  7648. const uint32_t byte_2_lead = 0xC0;
  7649. const uint32_t byte_3_lead = 0xE0;
  7650. const uint32_t byte_4_lead = 0xF0;
  7651. }
  7652. namespace Catch {
  7653. StringRef::StringRef( char const* rawChars ) noexcept
  7654. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  7655. {}
  7656. StringRef::operator std::string() const {
  7657. return std::string( m_start, m_size );
  7658. }
  7659. void StringRef::swap( StringRef& other ) noexcept {
  7660. std::swap( m_start, other.m_start );
  7661. std::swap( m_size, other.m_size );
  7662. std::swap( m_data, other.m_data );
  7663. }
  7664. auto StringRef::c_str() const -> char const* {
  7665. if( isSubstring() )
  7666. const_cast<StringRef*>( this )->takeOwnership();
  7667. return m_start;
  7668. }
  7669. auto StringRef::currentData() const noexcept -> char const* {
  7670. return m_start;
  7671. }
  7672. auto StringRef::isOwned() const noexcept -> bool {
  7673. return m_data != nullptr;
  7674. }
  7675. auto StringRef::isSubstring() const noexcept -> bool {
  7676. return m_start[m_size] != '\0';
  7677. }
  7678. void StringRef::takeOwnership() {
  7679. if( !isOwned() ) {
  7680. m_data = new char[m_size+1];
  7681. memcpy( m_data, m_start, m_size );
  7682. m_data[m_size] = '\0';
  7683. m_start = m_data;
  7684. }
  7685. }
  7686. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  7687. if( start < m_size )
  7688. return StringRef( m_start+start, size );
  7689. else
  7690. return StringRef();
  7691. }
  7692. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  7693. return
  7694. size() == other.size() &&
  7695. (std::strncmp( m_start, other.m_start, size() ) == 0);
  7696. }
  7697. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  7698. return !operator==( other );
  7699. }
  7700. auto StringRef::operator[](size_type index) const noexcept -> char {
  7701. return m_start[index];
  7702. }
  7703. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  7704. size_type noChars = m_size;
  7705. // Make adjustments for uft encodings
  7706. for( size_type i=0; i < m_size; ++i ) {
  7707. char c = m_start[i];
  7708. if( ( c & byte_2_lead ) == byte_2_lead ) {
  7709. noChars--;
  7710. if (( c & byte_3_lead ) == byte_3_lead )
  7711. noChars--;
  7712. if( ( c & byte_4_lead ) == byte_4_lead )
  7713. noChars--;
  7714. }
  7715. }
  7716. return noChars;
  7717. }
  7718. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  7719. std::string str;
  7720. str.reserve( lhs.size() + rhs.size() );
  7721. str += lhs;
  7722. str += rhs;
  7723. return str;
  7724. }
  7725. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  7726. return std::string( lhs ) + std::string( rhs );
  7727. }
  7728. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  7729. return std::string( lhs ) + std::string( rhs );
  7730. }
  7731. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  7732. return os.write(str.currentData(), str.size());
  7733. }
  7734. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  7735. lhs.append(rhs.currentData(), rhs.size());
  7736. return lhs;
  7737. }
  7738. } // namespace Catch
  7739. #if defined(__clang__)
  7740. # pragma clang diagnostic pop
  7741. #endif
  7742. // end catch_stringref.cpp
  7743. // start catch_tag_alias.cpp
  7744. namespace Catch {
  7745. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  7746. }
  7747. // end catch_tag_alias.cpp
  7748. // start catch_tag_alias_autoregistrar.cpp
  7749. namespace Catch {
  7750. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  7751. try {
  7752. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  7753. } catch (...) {
  7754. // Do not throw when constructing global objects, instead register the exception to be processed later
  7755. getMutableRegistryHub().registerStartupException();
  7756. }
  7757. }
  7758. }
  7759. // end catch_tag_alias_autoregistrar.cpp
  7760. // start catch_tag_alias_registry.cpp
  7761. #include <sstream>
  7762. namespace Catch {
  7763. TagAliasRegistry::~TagAliasRegistry() {}
  7764. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  7765. auto it = m_registry.find( alias );
  7766. if( it != m_registry.end() )
  7767. return &(it->second);
  7768. else
  7769. return nullptr;
  7770. }
  7771. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  7772. std::string expandedTestSpec = unexpandedTestSpec;
  7773. for( auto const& registryKvp : m_registry ) {
  7774. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  7775. if( pos != std::string::npos ) {
  7776. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  7777. registryKvp.second.tag +
  7778. expandedTestSpec.substr( pos + registryKvp.first.size() );
  7779. }
  7780. }
  7781. return expandedTestSpec;
  7782. }
  7783. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  7784. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  7785. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  7786. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  7787. "error: tag alias, '" << alias << "' already registered.\n"
  7788. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  7789. << "\tRedefined at: " << lineInfo );
  7790. }
  7791. ITagAliasRegistry::~ITagAliasRegistry() {}
  7792. ITagAliasRegistry const& ITagAliasRegistry::get() {
  7793. return getRegistryHub().getTagAliasRegistry();
  7794. }
  7795. } // end namespace Catch
  7796. // end catch_tag_alias_registry.cpp
  7797. // start catch_test_case_info.cpp
  7798. #include <cctype>
  7799. #include <exception>
  7800. #include <algorithm>
  7801. #include <sstream>
  7802. namespace Catch {
  7803. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  7804. if( startsWith( tag, '.' ) ||
  7805. tag == "!hide" )
  7806. return TestCaseInfo::IsHidden;
  7807. else if( tag == "!throws" )
  7808. return TestCaseInfo::Throws;
  7809. else if( tag == "!shouldfail" )
  7810. return TestCaseInfo::ShouldFail;
  7811. else if( tag == "!mayfail" )
  7812. return TestCaseInfo::MayFail;
  7813. else if( tag == "!nonportable" )
  7814. return TestCaseInfo::NonPortable;
  7815. else if( tag == "!benchmark" )
  7816. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  7817. else
  7818. return TestCaseInfo::None;
  7819. }
  7820. bool isReservedTag( std::string const& tag ) {
  7821. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( tag[0] );
  7822. }
  7823. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  7824. CATCH_ENFORCE( !isReservedTag(tag),
  7825. "Tag name: [" << tag << "] is not allowed.\n"
  7826. << "Tag names starting with non alpha-numeric characters are reserved\n"
  7827. << _lineInfo );
  7828. }
  7829. TestCase makeTestCase( ITestInvoker* _testCase,
  7830. std::string const& _className,
  7831. NameAndTags const& nameAndTags,
  7832. SourceLineInfo const& _lineInfo )
  7833. {
  7834. bool isHidden = false;
  7835. // Parse out tags
  7836. std::vector<std::string> tags;
  7837. std::string desc, tag;
  7838. bool inTag = false;
  7839. std::string _descOrTags = nameAndTags.tags;
  7840. for (char c : _descOrTags) {
  7841. if( !inTag ) {
  7842. if( c == '[' )
  7843. inTag = true;
  7844. else
  7845. desc += c;
  7846. }
  7847. else {
  7848. if( c == ']' ) {
  7849. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  7850. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  7851. isHidden = true;
  7852. else if( prop == TestCaseInfo::None )
  7853. enforceNotReservedTag( tag, _lineInfo );
  7854. tags.push_back( tag );
  7855. tag.clear();
  7856. inTag = false;
  7857. }
  7858. else
  7859. tag += c;
  7860. }
  7861. }
  7862. if( isHidden ) {
  7863. tags.push_back( "." );
  7864. }
  7865. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  7866. return TestCase( _testCase, std::move(info) );
  7867. }
  7868. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  7869. std::sort(begin(tags), end(tags));
  7870. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  7871. testCaseInfo.lcaseTags.clear();
  7872. for( auto const& tag : tags ) {
  7873. std::string lcaseTag = toLower( tag );
  7874. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  7875. testCaseInfo.lcaseTags.push_back( lcaseTag );
  7876. }
  7877. testCaseInfo.tags = std::move(tags);
  7878. }
  7879. TestCaseInfo::TestCaseInfo( std::string const& _name,
  7880. std::string const& _className,
  7881. std::string const& _description,
  7882. std::vector<std::string> const& _tags,
  7883. SourceLineInfo const& _lineInfo )
  7884. : name( _name ),
  7885. className( _className ),
  7886. description( _description ),
  7887. lineInfo( _lineInfo ),
  7888. properties( None )
  7889. {
  7890. setTags( *this, _tags );
  7891. }
  7892. bool TestCaseInfo::isHidden() const {
  7893. return ( properties & IsHidden ) != 0;
  7894. }
  7895. bool TestCaseInfo::throws() const {
  7896. return ( properties & Throws ) != 0;
  7897. }
  7898. bool TestCaseInfo::okToFail() const {
  7899. return ( properties & (ShouldFail | MayFail ) ) != 0;
  7900. }
  7901. bool TestCaseInfo::expectedToFail() const {
  7902. return ( properties & (ShouldFail ) ) != 0;
  7903. }
  7904. std::string TestCaseInfo::tagsAsString() const {
  7905. std::string ret;
  7906. // '[' and ']' per tag
  7907. std::size_t full_size = 2 * tags.size();
  7908. for (const auto& tag : tags) {
  7909. full_size += tag.size();
  7910. }
  7911. ret.reserve(full_size);
  7912. for (const auto& tag : tags) {
  7913. ret.push_back('[');
  7914. ret.append(tag);
  7915. ret.push_back(']');
  7916. }
  7917. return ret;
  7918. }
  7919. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  7920. TestCase TestCase::withName( std::string const& _newName ) const {
  7921. TestCase other( *this );
  7922. other.name = _newName;
  7923. return other;
  7924. }
  7925. void TestCase::invoke() const {
  7926. test->invoke();
  7927. }
  7928. bool TestCase::operator == ( TestCase const& other ) const {
  7929. return test.get() == other.test.get() &&
  7930. name == other.name &&
  7931. className == other.className;
  7932. }
  7933. bool TestCase::operator < ( TestCase const& other ) const {
  7934. return name < other.name;
  7935. }
  7936. TestCaseInfo const& TestCase::getTestCaseInfo() const
  7937. {
  7938. return *this;
  7939. }
  7940. } // end namespace Catch
  7941. // end catch_test_case_info.cpp
  7942. // start catch_test_case_registry_impl.cpp
  7943. #include <sstream>
  7944. namespace Catch {
  7945. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  7946. std::vector<TestCase> sorted = unsortedTestCases;
  7947. switch( config.runOrder() ) {
  7948. case RunTests::InLexicographicalOrder:
  7949. std::sort( sorted.begin(), sorted.end() );
  7950. break;
  7951. case RunTests::InRandomOrder:
  7952. seedRng( config );
  7953. RandomNumberGenerator::shuffle( sorted );
  7954. break;
  7955. case RunTests::InDeclarationOrder:
  7956. // already in declaration order
  7957. break;
  7958. }
  7959. return sorted;
  7960. }
  7961. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  7962. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  7963. }
  7964. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  7965. std::set<TestCase> seenFunctions;
  7966. for( auto const& function : functions ) {
  7967. auto prev = seenFunctions.insert( function );
  7968. CATCH_ENFORCE( prev.second,
  7969. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  7970. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  7971. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  7972. }
  7973. }
  7974. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  7975. std::vector<TestCase> filtered;
  7976. filtered.reserve( testCases.size() );
  7977. for( auto const& testCase : testCases )
  7978. if( matchTest( testCase, testSpec, config ) )
  7979. filtered.push_back( testCase );
  7980. return filtered;
  7981. }
  7982. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  7983. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  7984. }
  7985. void TestRegistry::registerTest( TestCase const& testCase ) {
  7986. std::string name = testCase.getTestCaseInfo().name;
  7987. if( name.empty() ) {
  7988. ReusableStringStream rss;
  7989. rss << "Anonymous test case " << ++m_unnamedCount;
  7990. return registerTest( testCase.withName( rss.str() ) );
  7991. }
  7992. m_functions.push_back( testCase );
  7993. }
  7994. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  7995. return m_functions;
  7996. }
  7997. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  7998. if( m_sortedFunctions.empty() )
  7999. enforceNoDuplicateTestCases( m_functions );
  8000. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  8001. m_sortedFunctions = sortTests( config, m_functions );
  8002. m_currentSortOrder = config.runOrder();
  8003. }
  8004. return m_sortedFunctions;
  8005. }
  8006. ///////////////////////////////////////////////////////////////////////////
  8007. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  8008. void TestInvokerAsFunction::invoke() const {
  8009. m_testAsFunction();
  8010. }
  8011. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  8012. std::string className = classOrQualifiedMethodName;
  8013. if( startsWith( className, '&' ) )
  8014. {
  8015. std::size_t lastColons = className.rfind( "::" );
  8016. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  8017. if( penultimateColons == std::string::npos )
  8018. penultimateColons = 1;
  8019. className = className.substr( penultimateColons, lastColons-penultimateColons );
  8020. }
  8021. return className;
  8022. }
  8023. } // end namespace Catch
  8024. // end catch_test_case_registry_impl.cpp
  8025. // start catch_test_case_tracker.cpp
  8026. #include <algorithm>
  8027. #include <assert.h>
  8028. #include <stdexcept>
  8029. #include <memory>
  8030. #include <sstream>
  8031. #if defined(__clang__)
  8032. # pragma clang diagnostic push
  8033. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8034. #endif
  8035. namespace Catch {
  8036. namespace TestCaseTracking {
  8037. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  8038. : name( _name ),
  8039. location( _location )
  8040. {}
  8041. ITracker::~ITracker() = default;
  8042. TrackerContext& TrackerContext::instance() {
  8043. static TrackerContext s_instance;
  8044. return s_instance;
  8045. }
  8046. ITracker& TrackerContext::startRun() {
  8047. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  8048. m_currentTracker = nullptr;
  8049. m_runState = Executing;
  8050. return *m_rootTracker;
  8051. }
  8052. void TrackerContext::endRun() {
  8053. m_rootTracker.reset();
  8054. m_currentTracker = nullptr;
  8055. m_runState = NotStarted;
  8056. }
  8057. void TrackerContext::startCycle() {
  8058. m_currentTracker = m_rootTracker.get();
  8059. m_runState = Executing;
  8060. }
  8061. void TrackerContext::completeCycle() {
  8062. m_runState = CompletedCycle;
  8063. }
  8064. bool TrackerContext::completedCycle() const {
  8065. return m_runState == CompletedCycle;
  8066. }
  8067. ITracker& TrackerContext::currentTracker() {
  8068. return *m_currentTracker;
  8069. }
  8070. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  8071. m_currentTracker = tracker;
  8072. }
  8073. TrackerBase::TrackerHasName::TrackerHasName( NameAndLocation const& nameAndLocation ) : m_nameAndLocation( nameAndLocation ) {}
  8074. bool TrackerBase::TrackerHasName::operator ()( ITrackerPtr const& tracker ) const {
  8075. return
  8076. tracker->nameAndLocation().name == m_nameAndLocation.name &&
  8077. tracker->nameAndLocation().location == m_nameAndLocation.location;
  8078. }
  8079. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8080. : m_nameAndLocation( nameAndLocation ),
  8081. m_ctx( ctx ),
  8082. m_parent( parent )
  8083. {}
  8084. NameAndLocation const& TrackerBase::nameAndLocation() const {
  8085. return m_nameAndLocation;
  8086. }
  8087. bool TrackerBase::isComplete() const {
  8088. return m_runState == CompletedSuccessfully || m_runState == Failed;
  8089. }
  8090. bool TrackerBase::isSuccessfullyCompleted() const {
  8091. return m_runState == CompletedSuccessfully;
  8092. }
  8093. bool TrackerBase::isOpen() const {
  8094. return m_runState != NotStarted && !isComplete();
  8095. }
  8096. bool TrackerBase::hasChildren() const {
  8097. return !m_children.empty();
  8098. }
  8099. void TrackerBase::addChild( ITrackerPtr const& child ) {
  8100. m_children.push_back( child );
  8101. }
  8102. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  8103. auto it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( nameAndLocation ) );
  8104. return( it != m_children.end() )
  8105. ? *it
  8106. : nullptr;
  8107. }
  8108. ITracker& TrackerBase::parent() {
  8109. assert( m_parent ); // Should always be non-null except for root
  8110. return *m_parent;
  8111. }
  8112. void TrackerBase::openChild() {
  8113. if( m_runState != ExecutingChildren ) {
  8114. m_runState = ExecutingChildren;
  8115. if( m_parent )
  8116. m_parent->openChild();
  8117. }
  8118. }
  8119. bool TrackerBase::isSectionTracker() const { return false; }
  8120. bool TrackerBase::isIndexTracker() const { return false; }
  8121. void TrackerBase::open() {
  8122. m_runState = Executing;
  8123. moveToThis();
  8124. if( m_parent )
  8125. m_parent->openChild();
  8126. }
  8127. void TrackerBase::close() {
  8128. // Close any still open children (e.g. generators)
  8129. while( &m_ctx.currentTracker() != this )
  8130. m_ctx.currentTracker().close();
  8131. switch( m_runState ) {
  8132. case NeedsAnotherRun:
  8133. break;
  8134. case Executing:
  8135. m_runState = CompletedSuccessfully;
  8136. break;
  8137. case ExecutingChildren:
  8138. if( m_children.empty() || m_children.back()->isComplete() )
  8139. m_runState = CompletedSuccessfully;
  8140. break;
  8141. case NotStarted:
  8142. case CompletedSuccessfully:
  8143. case Failed:
  8144. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  8145. default:
  8146. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  8147. }
  8148. moveToParent();
  8149. m_ctx.completeCycle();
  8150. }
  8151. void TrackerBase::fail() {
  8152. m_runState = Failed;
  8153. if( m_parent )
  8154. m_parent->markAsNeedingAnotherRun();
  8155. moveToParent();
  8156. m_ctx.completeCycle();
  8157. }
  8158. void TrackerBase::markAsNeedingAnotherRun() {
  8159. m_runState = NeedsAnotherRun;
  8160. }
  8161. void TrackerBase::moveToParent() {
  8162. assert( m_parent );
  8163. m_ctx.setCurrentTracker( m_parent );
  8164. }
  8165. void TrackerBase::moveToThis() {
  8166. m_ctx.setCurrentTracker( this );
  8167. }
  8168. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8169. : TrackerBase( nameAndLocation, ctx, parent )
  8170. {
  8171. if( parent ) {
  8172. while( !parent->isSectionTracker() )
  8173. parent = &parent->parent();
  8174. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  8175. addNextFilters( parentSection.m_filters );
  8176. }
  8177. }
  8178. bool SectionTracker::isSectionTracker() const { return true; }
  8179. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  8180. std::shared_ptr<SectionTracker> section;
  8181. ITracker& currentTracker = ctx.currentTracker();
  8182. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8183. assert( childTracker );
  8184. assert( childTracker->isSectionTracker() );
  8185. section = std::static_pointer_cast<SectionTracker>( childTracker );
  8186. }
  8187. else {
  8188. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  8189. currentTracker.addChild( section );
  8190. }
  8191. if( !ctx.completedCycle() )
  8192. section->tryOpen();
  8193. return *section;
  8194. }
  8195. void SectionTracker::tryOpen() {
  8196. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  8197. open();
  8198. }
  8199. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  8200. if( !filters.empty() ) {
  8201. m_filters.push_back(""); // Root - should never be consulted
  8202. m_filters.push_back(""); // Test Case - not a section filter
  8203. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  8204. }
  8205. }
  8206. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  8207. if( filters.size() > 1 )
  8208. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  8209. }
  8210. IndexTracker::IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size )
  8211. : TrackerBase( nameAndLocation, ctx, parent ),
  8212. m_size( size )
  8213. {}
  8214. bool IndexTracker::isIndexTracker() const { return true; }
  8215. IndexTracker& IndexTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) {
  8216. std::shared_ptr<IndexTracker> tracker;
  8217. ITracker& currentTracker = ctx.currentTracker();
  8218. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8219. assert( childTracker );
  8220. assert( childTracker->isIndexTracker() );
  8221. tracker = std::static_pointer_cast<IndexTracker>( childTracker );
  8222. }
  8223. else {
  8224. tracker = std::make_shared<IndexTracker>( nameAndLocation, ctx, &currentTracker, size );
  8225. currentTracker.addChild( tracker );
  8226. }
  8227. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  8228. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  8229. tracker->moveNext();
  8230. tracker->open();
  8231. }
  8232. return *tracker;
  8233. }
  8234. int IndexTracker::index() const { return m_index; }
  8235. void IndexTracker::moveNext() {
  8236. m_index++;
  8237. m_children.clear();
  8238. }
  8239. void IndexTracker::close() {
  8240. TrackerBase::close();
  8241. if( m_runState == CompletedSuccessfully && m_index < m_size-1 )
  8242. m_runState = Executing;
  8243. }
  8244. } // namespace TestCaseTracking
  8245. using TestCaseTracking::ITracker;
  8246. using TestCaseTracking::TrackerContext;
  8247. using TestCaseTracking::SectionTracker;
  8248. using TestCaseTracking::IndexTracker;
  8249. } // namespace Catch
  8250. #if defined(__clang__)
  8251. # pragma clang diagnostic pop
  8252. #endif
  8253. // end catch_test_case_tracker.cpp
  8254. // start catch_test_registry.cpp
  8255. namespace Catch {
  8256. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  8257. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  8258. }
  8259. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  8260. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  8261. try {
  8262. getMutableRegistryHub()
  8263. .registerTest(
  8264. makeTestCase(
  8265. invoker,
  8266. extractClassName( classOrMethod ),
  8267. nameAndTags,
  8268. lineInfo));
  8269. } catch (...) {
  8270. // Do not throw when constructing global objects, instead register the exception to be processed later
  8271. getMutableRegistryHub().registerStartupException();
  8272. }
  8273. }
  8274. AutoReg::~AutoReg() = default;
  8275. }
  8276. // end catch_test_registry.cpp
  8277. // start catch_test_spec.cpp
  8278. #include <algorithm>
  8279. #include <string>
  8280. #include <vector>
  8281. #include <memory>
  8282. namespace Catch {
  8283. TestSpec::Pattern::~Pattern() = default;
  8284. TestSpec::NamePattern::~NamePattern() = default;
  8285. TestSpec::TagPattern::~TagPattern() = default;
  8286. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  8287. TestSpec::NamePattern::NamePattern( std::string const& name )
  8288. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  8289. {}
  8290. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  8291. return m_wildcardPattern.matches( toLower( testCase.name ) );
  8292. }
  8293. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  8294. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  8295. return std::find(begin(testCase.lcaseTags),
  8296. end(testCase.lcaseTags),
  8297. m_tag) != end(testCase.lcaseTags);
  8298. }
  8299. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  8300. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  8301. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  8302. // All patterns in a filter must match for the filter to be a match
  8303. for( auto const& pattern : m_patterns ) {
  8304. if( !pattern->matches( testCase ) )
  8305. return false;
  8306. }
  8307. return true;
  8308. }
  8309. bool TestSpec::hasFilters() const {
  8310. return !m_filters.empty();
  8311. }
  8312. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  8313. // A TestSpec matches if any filter matches
  8314. for( auto const& filter : m_filters )
  8315. if( filter.matches( testCase ) )
  8316. return true;
  8317. return false;
  8318. }
  8319. }
  8320. // end catch_test_spec.cpp
  8321. // start catch_test_spec_parser.cpp
  8322. namespace Catch {
  8323. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  8324. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  8325. m_mode = None;
  8326. m_exclusion = false;
  8327. m_start = std::string::npos;
  8328. m_arg = m_tagAliases->expandAliases( arg );
  8329. m_escapeChars.clear();
  8330. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  8331. visitChar( m_arg[m_pos] );
  8332. if( m_mode == Name )
  8333. addPattern<TestSpec::NamePattern>();
  8334. return *this;
  8335. }
  8336. TestSpec TestSpecParser::testSpec() {
  8337. addFilter();
  8338. return m_testSpec;
  8339. }
  8340. void TestSpecParser::visitChar( char c ) {
  8341. if( m_mode == None ) {
  8342. switch( c ) {
  8343. case ' ': return;
  8344. case '~': m_exclusion = true; return;
  8345. case '[': return startNewMode( Tag, ++m_pos );
  8346. case '"': return startNewMode( QuotedName, ++m_pos );
  8347. case '\\': return escape();
  8348. default: startNewMode( Name, m_pos ); break;
  8349. }
  8350. }
  8351. if( m_mode == Name ) {
  8352. if( c == ',' ) {
  8353. addPattern<TestSpec::NamePattern>();
  8354. addFilter();
  8355. }
  8356. else if( c == '[' ) {
  8357. if( subString() == "exclude:" )
  8358. m_exclusion = true;
  8359. else
  8360. addPattern<TestSpec::NamePattern>();
  8361. startNewMode( Tag, ++m_pos );
  8362. }
  8363. else if( c == '\\' )
  8364. escape();
  8365. }
  8366. else if( m_mode == EscapedName )
  8367. m_mode = Name;
  8368. else if( m_mode == QuotedName && c == '"' )
  8369. addPattern<TestSpec::NamePattern>();
  8370. else if( m_mode == Tag && c == ']' )
  8371. addPattern<TestSpec::TagPattern>();
  8372. }
  8373. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  8374. m_mode = mode;
  8375. m_start = start;
  8376. }
  8377. void TestSpecParser::escape() {
  8378. if( m_mode == None )
  8379. m_start = m_pos;
  8380. m_mode = EscapedName;
  8381. m_escapeChars.push_back( m_pos );
  8382. }
  8383. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  8384. void TestSpecParser::addFilter() {
  8385. if( !m_currentFilter.m_patterns.empty() ) {
  8386. m_testSpec.m_filters.push_back( m_currentFilter );
  8387. m_currentFilter = TestSpec::Filter();
  8388. }
  8389. }
  8390. TestSpec parseTestSpec( std::string const& arg ) {
  8391. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  8392. }
  8393. } // namespace Catch
  8394. // end catch_test_spec_parser.cpp
  8395. // start catch_timer.cpp
  8396. #include <chrono>
  8397. namespace Catch {
  8398. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  8399. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  8400. }
  8401. auto estimateClockResolution() -> uint64_t {
  8402. uint64_t sum = 0;
  8403. static const uint64_t iterations = 1000000;
  8404. for( std::size_t i = 0; i < iterations; ++i ) {
  8405. uint64_t ticks;
  8406. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  8407. do {
  8408. ticks = getCurrentNanosecondsSinceEpoch();
  8409. }
  8410. while( ticks == baseTicks );
  8411. auto delta = ticks - baseTicks;
  8412. sum += delta;
  8413. }
  8414. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  8415. // - and potentially do more iterations if there's a high variance.
  8416. return sum/iterations;
  8417. }
  8418. auto getEstimatedClockResolution() -> uint64_t {
  8419. static auto s_resolution = estimateClockResolution();
  8420. return s_resolution;
  8421. }
  8422. void Timer::start() {
  8423. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  8424. }
  8425. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  8426. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  8427. }
  8428. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  8429. return getElapsedNanoseconds()/1000;
  8430. }
  8431. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  8432. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  8433. }
  8434. auto Timer::getElapsedSeconds() const -> double {
  8435. return getElapsedMicroseconds()/1000000.0;
  8436. }
  8437. } // namespace Catch
  8438. // end catch_timer.cpp
  8439. // start catch_tostring.cpp
  8440. #if defined(__clang__)
  8441. # pragma clang diagnostic push
  8442. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8443. # pragma clang diagnostic ignored "-Wglobal-constructors"
  8444. #endif
  8445. // Enable specific decls locally
  8446. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  8447. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  8448. #endif
  8449. #include <cmath>
  8450. #include <iomanip>
  8451. namespace Catch {
  8452. namespace Detail {
  8453. const std::string unprintableString = "{?}";
  8454. namespace {
  8455. const int hexThreshold = 255;
  8456. struct Endianness {
  8457. enum Arch { Big, Little };
  8458. static Arch which() {
  8459. union _{
  8460. int asInt;
  8461. char asChar[sizeof (int)];
  8462. } u;
  8463. u.asInt = 1;
  8464. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  8465. }
  8466. };
  8467. }
  8468. std::string rawMemoryToString( const void *object, std::size_t size ) {
  8469. // Reverse order for little endian architectures
  8470. int i = 0, end = static_cast<int>( size ), inc = 1;
  8471. if( Endianness::which() == Endianness::Little ) {
  8472. i = end-1;
  8473. end = inc = -1;
  8474. }
  8475. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  8476. ReusableStringStream rss;
  8477. rss << "0x" << std::setfill('0') << std::hex;
  8478. for( ; i != end; i += inc )
  8479. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  8480. return rss.str();
  8481. }
  8482. }
  8483. template<typename T>
  8484. std::string fpToString( T value, int precision ) {
  8485. if (std::isnan(value)) {
  8486. return "nan";
  8487. }
  8488. ReusableStringStream rss;
  8489. rss << std::setprecision( precision )
  8490. << std::fixed
  8491. << value;
  8492. std::string d = rss.str();
  8493. std::size_t i = d.find_last_not_of( '0' );
  8494. if( i != std::string::npos && i != d.size()-1 ) {
  8495. if( d[i] == '.' )
  8496. i++;
  8497. d = d.substr( 0, i+1 );
  8498. }
  8499. return d;
  8500. }
  8501. //// ======================================================= ////
  8502. //
  8503. // Out-of-line defs for full specialization of StringMaker
  8504. //
  8505. //// ======================================================= ////
  8506. std::string StringMaker<std::string>::convert(const std::string& str) {
  8507. if (!getCurrentContext().getConfig()->showInvisibles()) {
  8508. return '"' + str + '"';
  8509. }
  8510. std::string s("\"");
  8511. for (char c : str) {
  8512. switch (c) {
  8513. case '\n':
  8514. s.append("\\n");
  8515. break;
  8516. case '\t':
  8517. s.append("\\t");
  8518. break;
  8519. default:
  8520. s.push_back(c);
  8521. break;
  8522. }
  8523. }
  8524. s.append("\"");
  8525. return s;
  8526. }
  8527. #ifdef CATCH_CONFIG_WCHAR
  8528. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  8529. std::string s;
  8530. s.reserve(wstr.size());
  8531. for (auto c : wstr) {
  8532. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  8533. }
  8534. return ::Catch::Detail::stringify(s);
  8535. }
  8536. #endif
  8537. std::string StringMaker<char const*>::convert(char const* str) {
  8538. if (str) {
  8539. return ::Catch::Detail::stringify(std::string{ str });
  8540. } else {
  8541. return{ "{null string}" };
  8542. }
  8543. }
  8544. std::string StringMaker<char*>::convert(char* str) {
  8545. if (str) {
  8546. return ::Catch::Detail::stringify(std::string{ str });
  8547. } else {
  8548. return{ "{null string}" };
  8549. }
  8550. }
  8551. #ifdef CATCH_CONFIG_WCHAR
  8552. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  8553. if (str) {
  8554. return ::Catch::Detail::stringify(std::wstring{ str });
  8555. } else {
  8556. return{ "{null string}" };
  8557. }
  8558. }
  8559. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  8560. if (str) {
  8561. return ::Catch::Detail::stringify(std::wstring{ str });
  8562. } else {
  8563. return{ "{null string}" };
  8564. }
  8565. }
  8566. #endif
  8567. std::string StringMaker<int>::convert(int value) {
  8568. return ::Catch::Detail::stringify(static_cast<long long>(value));
  8569. }
  8570. std::string StringMaker<long>::convert(long value) {
  8571. return ::Catch::Detail::stringify(static_cast<long long>(value));
  8572. }
  8573. std::string StringMaker<long long>::convert(long long value) {
  8574. ReusableStringStream rss;
  8575. rss << value;
  8576. if (value > Detail::hexThreshold) {
  8577. rss << " (0x" << std::hex << value << ')';
  8578. }
  8579. return rss.str();
  8580. }
  8581. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  8582. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  8583. }
  8584. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  8585. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  8586. }
  8587. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  8588. ReusableStringStream rss;
  8589. rss << value;
  8590. if (value > Detail::hexThreshold) {
  8591. rss << " (0x" << std::hex << value << ')';
  8592. }
  8593. return rss.str();
  8594. }
  8595. std::string StringMaker<bool>::convert(bool b) {
  8596. return b ? "true" : "false";
  8597. }
  8598. std::string StringMaker<char>::convert(char value) {
  8599. if (value == '\r') {
  8600. return "'\\r'";
  8601. } else if (value == '\f') {
  8602. return "'\\f'";
  8603. } else if (value == '\n') {
  8604. return "'\\n'";
  8605. } else if (value == '\t') {
  8606. return "'\\t'";
  8607. } else if ('\0' <= value && value < ' ') {
  8608. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  8609. } else {
  8610. char chstr[] = "' '";
  8611. chstr[1] = value;
  8612. return chstr;
  8613. }
  8614. }
  8615. std::string StringMaker<signed char>::convert(signed char c) {
  8616. return ::Catch::Detail::stringify(static_cast<char>(c));
  8617. }
  8618. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  8619. return ::Catch::Detail::stringify(static_cast<char>(c));
  8620. }
  8621. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  8622. return "nullptr";
  8623. }
  8624. std::string StringMaker<float>::convert(float value) {
  8625. return fpToString(value, 5) + 'f';
  8626. }
  8627. std::string StringMaker<double>::convert(double value) {
  8628. return fpToString(value, 10);
  8629. }
  8630. std::string ratio_string<std::atto>::symbol() { return "a"; }
  8631. std::string ratio_string<std::femto>::symbol() { return "f"; }
  8632. std::string ratio_string<std::pico>::symbol() { return "p"; }
  8633. std::string ratio_string<std::nano>::symbol() { return "n"; }
  8634. std::string ratio_string<std::micro>::symbol() { return "u"; }
  8635. std::string ratio_string<std::milli>::symbol() { return "m"; }
  8636. } // end namespace Catch
  8637. #if defined(__clang__)
  8638. # pragma clang diagnostic pop
  8639. #endif
  8640. // end catch_tostring.cpp
  8641. // start catch_totals.cpp
  8642. namespace Catch {
  8643. Counts Counts::operator - ( Counts const& other ) const {
  8644. Counts diff;
  8645. diff.passed = passed - other.passed;
  8646. diff.failed = failed - other.failed;
  8647. diff.failedButOk = failedButOk - other.failedButOk;
  8648. return diff;
  8649. }
  8650. Counts& Counts::operator += ( Counts const& other ) {
  8651. passed += other.passed;
  8652. failed += other.failed;
  8653. failedButOk += other.failedButOk;
  8654. return *this;
  8655. }
  8656. std::size_t Counts::total() const {
  8657. return passed + failed + failedButOk;
  8658. }
  8659. bool Counts::allPassed() const {
  8660. return failed == 0 && failedButOk == 0;
  8661. }
  8662. bool Counts::allOk() const {
  8663. return failed == 0;
  8664. }
  8665. Totals Totals::operator - ( Totals const& other ) const {
  8666. Totals diff;
  8667. diff.assertions = assertions - other.assertions;
  8668. diff.testCases = testCases - other.testCases;
  8669. return diff;
  8670. }
  8671. Totals& Totals::operator += ( Totals const& other ) {
  8672. assertions += other.assertions;
  8673. testCases += other.testCases;
  8674. return *this;
  8675. }
  8676. Totals Totals::delta( Totals const& prevTotals ) const {
  8677. Totals diff = *this - prevTotals;
  8678. if( diff.assertions.failed > 0 )
  8679. ++diff.testCases.failed;
  8680. else if( diff.assertions.failedButOk > 0 )
  8681. ++diff.testCases.failedButOk;
  8682. else
  8683. ++diff.testCases.passed;
  8684. return diff;
  8685. }
  8686. }
  8687. // end catch_totals.cpp
  8688. // start catch_uncaught_exceptions.cpp
  8689. #include <exception>
  8690. namespace Catch {
  8691. bool uncaught_exceptions() {
  8692. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  8693. return std::uncaught_exceptions() > 0;
  8694. #else
  8695. return std::uncaught_exception();
  8696. #endif
  8697. }
  8698. } // end namespace Catch
  8699. // end catch_uncaught_exceptions.cpp
  8700. // start catch_version.cpp
  8701. #include <ostream>
  8702. namespace Catch {
  8703. Version::Version
  8704. ( unsigned int _majorVersion,
  8705. unsigned int _minorVersion,
  8706. unsigned int _patchNumber,
  8707. char const * const _branchName,
  8708. unsigned int _buildNumber )
  8709. : majorVersion( _majorVersion ),
  8710. minorVersion( _minorVersion ),
  8711. patchNumber( _patchNumber ),
  8712. branchName( _branchName ),
  8713. buildNumber( _buildNumber )
  8714. {}
  8715. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  8716. os << version.majorVersion << '.'
  8717. << version.minorVersion << '.'
  8718. << version.patchNumber;
  8719. // branchName is never null -> 0th char is \0 if it is empty
  8720. if (version.branchName[0]) {
  8721. os << '-' << version.branchName
  8722. << '.' << version.buildNumber;
  8723. }
  8724. return os;
  8725. }
  8726. Version const& libraryVersion() {
  8727. static Version version( 2, 2, 1, "", 0 );
  8728. return version;
  8729. }
  8730. }
  8731. // end catch_version.cpp
  8732. // start catch_wildcard_pattern.cpp
  8733. #include <sstream>
  8734. namespace Catch {
  8735. WildcardPattern::WildcardPattern( std::string const& pattern,
  8736. CaseSensitive::Choice caseSensitivity )
  8737. : m_caseSensitivity( caseSensitivity ),
  8738. m_pattern( adjustCase( pattern ) )
  8739. {
  8740. if( startsWith( m_pattern, '*' ) ) {
  8741. m_pattern = m_pattern.substr( 1 );
  8742. m_wildcard = WildcardAtStart;
  8743. }
  8744. if( endsWith( m_pattern, '*' ) ) {
  8745. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  8746. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  8747. }
  8748. }
  8749. bool WildcardPattern::matches( std::string const& str ) const {
  8750. switch( m_wildcard ) {
  8751. case NoWildcard:
  8752. return m_pattern == adjustCase( str );
  8753. case WildcardAtStart:
  8754. return endsWith( adjustCase( str ), m_pattern );
  8755. case WildcardAtEnd:
  8756. return startsWith( adjustCase( str ), m_pattern );
  8757. case WildcardAtBothEnds:
  8758. return contains( adjustCase( str ), m_pattern );
  8759. default:
  8760. CATCH_INTERNAL_ERROR( "Unknown enum" );
  8761. }
  8762. }
  8763. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  8764. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  8765. }
  8766. }
  8767. // end catch_wildcard_pattern.cpp
  8768. // start catch_xmlwriter.cpp
  8769. #include <iomanip>
  8770. namespace Catch {
  8771. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  8772. : m_str( str ),
  8773. m_forWhat( forWhat )
  8774. {}
  8775. void XmlEncode::encodeTo( std::ostream& os ) const {
  8776. // Apostrophe escaping not necessary if we always use " to write attributes
  8777. // (see: http://www.w3.org/TR/xml/#syntax)
  8778. for( std::size_t i = 0; i < m_str.size(); ++ i ) {
  8779. char c = m_str[i];
  8780. switch( c ) {
  8781. case '<': os << "&lt;"; break;
  8782. case '&': os << "&amp;"; break;
  8783. case '>':
  8784. // See: http://www.w3.org/TR/xml/#syntax
  8785. if( i > 2 && m_str[i-1] == ']' && m_str[i-2] == ']' )
  8786. os << "&gt;";
  8787. else
  8788. os << c;
  8789. break;
  8790. case '\"':
  8791. if( m_forWhat == ForAttributes )
  8792. os << "&quot;";
  8793. else
  8794. os << c;
  8795. break;
  8796. default:
  8797. // Escape control chars - based on contribution by @espenalb in PR #465 and
  8798. // by @mrpi PR #588
  8799. if ( ( c >= 0 && c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) {
  8800. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  8801. os << "\\x" << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  8802. << static_cast<int>( c );
  8803. }
  8804. else
  8805. os << c;
  8806. }
  8807. }
  8808. }
  8809. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  8810. xmlEncode.encodeTo( os );
  8811. return os;
  8812. }
  8813. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  8814. : m_writer( writer )
  8815. {}
  8816. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  8817. : m_writer( other.m_writer ){
  8818. other.m_writer = nullptr;
  8819. }
  8820. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  8821. if ( m_writer ) {
  8822. m_writer->endElement();
  8823. }
  8824. m_writer = other.m_writer;
  8825. other.m_writer = nullptr;
  8826. return *this;
  8827. }
  8828. XmlWriter::ScopedElement::~ScopedElement() {
  8829. if( m_writer )
  8830. m_writer->endElement();
  8831. }
  8832. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  8833. m_writer->writeText( text, indent );
  8834. return *this;
  8835. }
  8836. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  8837. {
  8838. writeDeclaration();
  8839. }
  8840. XmlWriter::~XmlWriter() {
  8841. while( !m_tags.empty() )
  8842. endElement();
  8843. }
  8844. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  8845. ensureTagClosed();
  8846. newlineIfNecessary();
  8847. m_os << m_indent << '<' << name;
  8848. m_tags.push_back( name );
  8849. m_indent += " ";
  8850. m_tagIsOpen = true;
  8851. return *this;
  8852. }
  8853. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  8854. ScopedElement scoped( this );
  8855. startElement( name );
  8856. return scoped;
  8857. }
  8858. XmlWriter& XmlWriter::endElement() {
  8859. newlineIfNecessary();
  8860. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  8861. if( m_tagIsOpen ) {
  8862. m_os << "/>";
  8863. m_tagIsOpen = false;
  8864. }
  8865. else {
  8866. m_os << m_indent << "</" << m_tags.back() << ">";
  8867. }
  8868. m_os << std::endl;
  8869. m_tags.pop_back();
  8870. return *this;
  8871. }
  8872. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  8873. if( !name.empty() && !attribute.empty() )
  8874. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  8875. return *this;
  8876. }
  8877. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  8878. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  8879. return *this;
  8880. }
  8881. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  8882. if( !text.empty() ){
  8883. bool tagWasOpen = m_tagIsOpen;
  8884. ensureTagClosed();
  8885. if( tagWasOpen && indent )
  8886. m_os << m_indent;
  8887. m_os << XmlEncode( text );
  8888. m_needsNewline = true;
  8889. }
  8890. return *this;
  8891. }
  8892. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  8893. ensureTagClosed();
  8894. m_os << m_indent << "<!--" << text << "-->";
  8895. m_needsNewline = true;
  8896. return *this;
  8897. }
  8898. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  8899. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  8900. }
  8901. XmlWriter& XmlWriter::writeBlankLine() {
  8902. ensureTagClosed();
  8903. m_os << '\n';
  8904. return *this;
  8905. }
  8906. void XmlWriter::ensureTagClosed() {
  8907. if( m_tagIsOpen ) {
  8908. m_os << ">" << std::endl;
  8909. m_tagIsOpen = false;
  8910. }
  8911. }
  8912. void XmlWriter::writeDeclaration() {
  8913. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  8914. }
  8915. void XmlWriter::newlineIfNecessary() {
  8916. if( m_needsNewline ) {
  8917. m_os << std::endl;
  8918. m_needsNewline = false;
  8919. }
  8920. }
  8921. }
  8922. // end catch_xmlwriter.cpp
  8923. // start catch_reporter_bases.cpp
  8924. #include <cstring>
  8925. #include <cfloat>
  8926. #include <cstdio>
  8927. #include <assert.h>
  8928. #include <memory>
  8929. namespace Catch {
  8930. void prepareExpandedExpression(AssertionResult& result) {
  8931. result.getExpandedExpression();
  8932. }
  8933. // Because formatting using c++ streams is stateful, drop down to C is required
  8934. // Alternatively we could use stringstream, but its performance is... not good.
  8935. std::string getFormattedDuration( double duration ) {
  8936. // Max exponent + 1 is required to represent the whole part
  8937. // + 1 for decimal point
  8938. // + 3 for the 3 decimal places
  8939. // + 1 for null terminator
  8940. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  8941. char buffer[maxDoubleSize];
  8942. // Save previous errno, to prevent sprintf from overwriting it
  8943. ErrnoGuard guard;
  8944. #ifdef _MSC_VER
  8945. sprintf_s(buffer, "%.3f", duration);
  8946. #else
  8947. sprintf(buffer, "%.3f", duration);
  8948. #endif
  8949. return std::string(buffer);
  8950. }
  8951. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  8952. :StreamingReporterBase(_config) {}
  8953. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  8954. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  8955. return false;
  8956. }
  8957. } // end namespace Catch
  8958. // end catch_reporter_bases.cpp
  8959. // start catch_reporter_compact.cpp
  8960. namespace {
  8961. #ifdef CATCH_PLATFORM_MAC
  8962. const char* failedString() { return "FAILED"; }
  8963. const char* passedString() { return "PASSED"; }
  8964. #else
  8965. const char* failedString() { return "failed"; }
  8966. const char* passedString() { return "passed"; }
  8967. #endif
  8968. // Colour::LightGrey
  8969. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  8970. std::string bothOrAll( std::size_t count ) {
  8971. return count == 1 ? std::string() :
  8972. count == 2 ? "both " : "all " ;
  8973. }
  8974. } // anon namespace
  8975. namespace Catch {
  8976. namespace {
  8977. // Colour, message variants:
  8978. // - white: No tests ran.
  8979. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  8980. // - white: Passed [both/all] N test cases (no assertions).
  8981. // - red: Failed N tests cases, failed M assertions.
  8982. // - green: Passed [both/all] N tests cases with M assertions.
  8983. void printTotals(std::ostream& out, const Totals& totals) {
  8984. if (totals.testCases.total() == 0) {
  8985. out << "No tests ran.";
  8986. } else if (totals.testCases.failed == totals.testCases.total()) {
  8987. Colour colour(Colour::ResultError);
  8988. const std::string qualify_assertions_failed =
  8989. totals.assertions.failed == totals.assertions.total() ?
  8990. bothOrAll(totals.assertions.failed) : std::string();
  8991. out <<
  8992. "Failed " << bothOrAll(totals.testCases.failed)
  8993. << pluralise(totals.testCases.failed, "test case") << ", "
  8994. "failed " << qualify_assertions_failed <<
  8995. pluralise(totals.assertions.failed, "assertion") << '.';
  8996. } else if (totals.assertions.total() == 0) {
  8997. out <<
  8998. "Passed " << bothOrAll(totals.testCases.total())
  8999. << pluralise(totals.testCases.total(), "test case")
  9000. << " (no assertions).";
  9001. } else if (totals.assertions.failed) {
  9002. Colour colour(Colour::ResultError);
  9003. out <<
  9004. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  9005. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  9006. } else {
  9007. Colour colour(Colour::ResultSuccess);
  9008. out <<
  9009. "Passed " << bothOrAll(totals.testCases.passed)
  9010. << pluralise(totals.testCases.passed, "test case") <<
  9011. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  9012. }
  9013. }
  9014. // Implementation of CompactReporter formatting
  9015. class AssertionPrinter {
  9016. public:
  9017. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  9018. AssertionPrinter(AssertionPrinter const&) = delete;
  9019. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  9020. : stream(_stream)
  9021. , result(_stats.assertionResult)
  9022. , messages(_stats.infoMessages)
  9023. , itMessage(_stats.infoMessages.begin())
  9024. , printInfoMessages(_printInfoMessages) {}
  9025. void print() {
  9026. printSourceInfo();
  9027. itMessage = messages.begin();
  9028. switch (result.getResultType()) {
  9029. case ResultWas::Ok:
  9030. printResultType(Colour::ResultSuccess, passedString());
  9031. printOriginalExpression();
  9032. printReconstructedExpression();
  9033. if (!result.hasExpression())
  9034. printRemainingMessages(Colour::None);
  9035. else
  9036. printRemainingMessages();
  9037. break;
  9038. case ResultWas::ExpressionFailed:
  9039. if (result.isOk())
  9040. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  9041. else
  9042. printResultType(Colour::Error, failedString());
  9043. printOriginalExpression();
  9044. printReconstructedExpression();
  9045. printRemainingMessages();
  9046. break;
  9047. case ResultWas::ThrewException:
  9048. printResultType(Colour::Error, failedString());
  9049. printIssue("unexpected exception with message:");
  9050. printMessage();
  9051. printExpressionWas();
  9052. printRemainingMessages();
  9053. break;
  9054. case ResultWas::FatalErrorCondition:
  9055. printResultType(Colour::Error, failedString());
  9056. printIssue("fatal error condition with message:");
  9057. printMessage();
  9058. printExpressionWas();
  9059. printRemainingMessages();
  9060. break;
  9061. case ResultWas::DidntThrowException:
  9062. printResultType(Colour::Error, failedString());
  9063. printIssue("expected exception, got none");
  9064. printExpressionWas();
  9065. printRemainingMessages();
  9066. break;
  9067. case ResultWas::Info:
  9068. printResultType(Colour::None, "info");
  9069. printMessage();
  9070. printRemainingMessages();
  9071. break;
  9072. case ResultWas::Warning:
  9073. printResultType(Colour::None, "warning");
  9074. printMessage();
  9075. printRemainingMessages();
  9076. break;
  9077. case ResultWas::ExplicitFailure:
  9078. printResultType(Colour::Error, failedString());
  9079. printIssue("explicitly");
  9080. printRemainingMessages(Colour::None);
  9081. break;
  9082. // These cases are here to prevent compiler warnings
  9083. case ResultWas::Unknown:
  9084. case ResultWas::FailureBit:
  9085. case ResultWas::Exception:
  9086. printResultType(Colour::Error, "** internal error **");
  9087. break;
  9088. }
  9089. }
  9090. private:
  9091. void printSourceInfo() const {
  9092. Colour colourGuard(Colour::FileName);
  9093. stream << result.getSourceInfo() << ':';
  9094. }
  9095. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  9096. if (!passOrFail.empty()) {
  9097. {
  9098. Colour colourGuard(colour);
  9099. stream << ' ' << passOrFail;
  9100. }
  9101. stream << ':';
  9102. }
  9103. }
  9104. void printIssue(std::string const& issue) const {
  9105. stream << ' ' << issue;
  9106. }
  9107. void printExpressionWas() {
  9108. if (result.hasExpression()) {
  9109. stream << ';';
  9110. {
  9111. Colour colour(dimColour());
  9112. stream << " expression was:";
  9113. }
  9114. printOriginalExpression();
  9115. }
  9116. }
  9117. void printOriginalExpression() const {
  9118. if (result.hasExpression()) {
  9119. stream << ' ' << result.getExpression();
  9120. }
  9121. }
  9122. void printReconstructedExpression() const {
  9123. if (result.hasExpandedExpression()) {
  9124. {
  9125. Colour colour(dimColour());
  9126. stream << " for: ";
  9127. }
  9128. stream << result.getExpandedExpression();
  9129. }
  9130. }
  9131. void printMessage() {
  9132. if (itMessage != messages.end()) {
  9133. stream << " '" << itMessage->message << '\'';
  9134. ++itMessage;
  9135. }
  9136. }
  9137. void printRemainingMessages(Colour::Code colour = dimColour()) {
  9138. if (itMessage == messages.end())
  9139. return;
  9140. // using messages.end() directly yields (or auto) compilation error:
  9141. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  9142. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  9143. {
  9144. Colour colourGuard(colour);
  9145. stream << " with " << pluralise(N, "message") << ':';
  9146. }
  9147. for (; itMessage != itEnd; ) {
  9148. // If this assertion is a warning ignore any INFO messages
  9149. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  9150. stream << " '" << itMessage->message << '\'';
  9151. if (++itMessage != itEnd) {
  9152. Colour colourGuard(dimColour());
  9153. stream << " and";
  9154. }
  9155. }
  9156. }
  9157. }
  9158. private:
  9159. std::ostream& stream;
  9160. AssertionResult const& result;
  9161. std::vector<MessageInfo> messages;
  9162. std::vector<MessageInfo>::const_iterator itMessage;
  9163. bool printInfoMessages;
  9164. };
  9165. } // anon namespace
  9166. std::string CompactReporter::getDescription() {
  9167. return "Reports test results on a single line, suitable for IDEs";
  9168. }
  9169. ReporterPreferences CompactReporter::getPreferences() const {
  9170. ReporterPreferences prefs;
  9171. prefs.shouldRedirectStdOut = false;
  9172. return prefs;
  9173. }
  9174. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  9175. stream << "No test cases matched '" << spec << '\'' << std::endl;
  9176. }
  9177. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  9178. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  9179. AssertionResult const& result = _assertionStats.assertionResult;
  9180. bool printInfoMessages = true;
  9181. // Drop out if result was successful and we're not printing those
  9182. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  9183. if( result.getResultType() != ResultWas::Warning )
  9184. return false;
  9185. printInfoMessages = false;
  9186. }
  9187. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  9188. printer.print();
  9189. stream << std::endl;
  9190. return true;
  9191. }
  9192. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  9193. if (m_config->showDurations() == ShowDurations::Always) {
  9194. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  9195. }
  9196. }
  9197. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  9198. printTotals( stream, _testRunStats.totals );
  9199. stream << '\n' << std::endl;
  9200. StreamingReporterBase::testRunEnded( _testRunStats );
  9201. }
  9202. CompactReporter::~CompactReporter() {}
  9203. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  9204. } // end namespace Catch
  9205. // end catch_reporter_compact.cpp
  9206. // start catch_reporter_console.cpp
  9207. #include <cfloat>
  9208. #include <cstdio>
  9209. #if defined(_MSC_VER)
  9210. #pragma warning(push)
  9211. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  9212. // Note that 4062 (not all labels are handled
  9213. // and default is missing) is enabled
  9214. #endif
  9215. namespace Catch {
  9216. namespace {
  9217. // Formatter impl for ConsoleReporter
  9218. class ConsoleAssertionPrinter {
  9219. public:
  9220. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  9221. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  9222. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  9223. : stream(_stream),
  9224. stats(_stats),
  9225. result(_stats.assertionResult),
  9226. colour(Colour::None),
  9227. message(result.getMessage()),
  9228. messages(_stats.infoMessages),
  9229. printInfoMessages(_printInfoMessages) {
  9230. switch (result.getResultType()) {
  9231. case ResultWas::Ok:
  9232. colour = Colour::Success;
  9233. passOrFail = "PASSED";
  9234. //if( result.hasMessage() )
  9235. if (_stats.infoMessages.size() == 1)
  9236. messageLabel = "with message";
  9237. if (_stats.infoMessages.size() > 1)
  9238. messageLabel = "with messages";
  9239. break;
  9240. case ResultWas::ExpressionFailed:
  9241. if (result.isOk()) {
  9242. colour = Colour::Success;
  9243. passOrFail = "FAILED - but was ok";
  9244. } else {
  9245. colour = Colour::Error;
  9246. passOrFail = "FAILED";
  9247. }
  9248. if (_stats.infoMessages.size() == 1)
  9249. messageLabel = "with message";
  9250. if (_stats.infoMessages.size() > 1)
  9251. messageLabel = "with messages";
  9252. break;
  9253. case ResultWas::ThrewException:
  9254. colour = Colour::Error;
  9255. passOrFail = "FAILED";
  9256. messageLabel = "due to unexpected exception with ";
  9257. if (_stats.infoMessages.size() == 1)
  9258. messageLabel += "message";
  9259. if (_stats.infoMessages.size() > 1)
  9260. messageLabel += "messages";
  9261. break;
  9262. case ResultWas::FatalErrorCondition:
  9263. colour = Colour::Error;
  9264. passOrFail = "FAILED";
  9265. messageLabel = "due to a fatal error condition";
  9266. break;
  9267. case ResultWas::DidntThrowException:
  9268. colour = Colour::Error;
  9269. passOrFail = "FAILED";
  9270. messageLabel = "because no exception was thrown where one was expected";
  9271. break;
  9272. case ResultWas::Info:
  9273. messageLabel = "info";
  9274. break;
  9275. case ResultWas::Warning:
  9276. messageLabel = "warning";
  9277. break;
  9278. case ResultWas::ExplicitFailure:
  9279. passOrFail = "FAILED";
  9280. colour = Colour::Error;
  9281. if (_stats.infoMessages.size() == 1)
  9282. messageLabel = "explicitly with message";
  9283. if (_stats.infoMessages.size() > 1)
  9284. messageLabel = "explicitly with messages";
  9285. break;
  9286. // These cases are here to prevent compiler warnings
  9287. case ResultWas::Unknown:
  9288. case ResultWas::FailureBit:
  9289. case ResultWas::Exception:
  9290. passOrFail = "** internal error **";
  9291. colour = Colour::Error;
  9292. break;
  9293. }
  9294. }
  9295. void print() const {
  9296. printSourceInfo();
  9297. if (stats.totals.assertions.total() > 0) {
  9298. if (result.isOk())
  9299. stream << '\n';
  9300. printResultType();
  9301. printOriginalExpression();
  9302. printReconstructedExpression();
  9303. } else {
  9304. stream << '\n';
  9305. }
  9306. printMessage();
  9307. }
  9308. private:
  9309. void printResultType() const {
  9310. if (!passOrFail.empty()) {
  9311. Colour colourGuard(colour);
  9312. stream << passOrFail << ":\n";
  9313. }
  9314. }
  9315. void printOriginalExpression() const {
  9316. if (result.hasExpression()) {
  9317. Colour colourGuard(Colour::OriginalExpression);
  9318. stream << " ";
  9319. stream << result.getExpressionInMacro();
  9320. stream << '\n';
  9321. }
  9322. }
  9323. void printReconstructedExpression() const {
  9324. if (result.hasExpandedExpression()) {
  9325. stream << "with expansion:\n";
  9326. Colour colourGuard(Colour::ReconstructedExpression);
  9327. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  9328. }
  9329. }
  9330. void printMessage() const {
  9331. if (!messageLabel.empty())
  9332. stream << messageLabel << ':' << '\n';
  9333. for (auto const& msg : messages) {
  9334. // If this assertion is a warning ignore any INFO messages
  9335. if (printInfoMessages || msg.type != ResultWas::Info)
  9336. stream << Column(msg.message).indent(2) << '\n';
  9337. }
  9338. }
  9339. void printSourceInfo() const {
  9340. Colour colourGuard(Colour::FileName);
  9341. stream << result.getSourceInfo() << ": ";
  9342. }
  9343. std::ostream& stream;
  9344. AssertionStats const& stats;
  9345. AssertionResult const& result;
  9346. Colour::Code colour;
  9347. std::string passOrFail;
  9348. std::string messageLabel;
  9349. std::string message;
  9350. std::vector<MessageInfo> messages;
  9351. bool printInfoMessages;
  9352. };
  9353. std::size_t makeRatio(std::size_t number, std::size_t total) {
  9354. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  9355. return (ratio == 0 && number > 0) ? 1 : ratio;
  9356. }
  9357. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  9358. if (i > j && i > k)
  9359. return i;
  9360. else if (j > k)
  9361. return j;
  9362. else
  9363. return k;
  9364. }
  9365. struct ColumnInfo {
  9366. enum Justification { Left, Right };
  9367. std::string name;
  9368. int width;
  9369. Justification justification;
  9370. };
  9371. struct ColumnBreak {};
  9372. struct RowBreak {};
  9373. class Duration {
  9374. enum class Unit {
  9375. Auto,
  9376. Nanoseconds,
  9377. Microseconds,
  9378. Milliseconds,
  9379. Seconds,
  9380. Minutes
  9381. };
  9382. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  9383. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  9384. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  9385. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  9386. uint64_t m_inNanoseconds;
  9387. Unit m_units;
  9388. public:
  9389. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  9390. : m_inNanoseconds(inNanoseconds),
  9391. m_units(units) {
  9392. if (m_units == Unit::Auto) {
  9393. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  9394. m_units = Unit::Nanoseconds;
  9395. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  9396. m_units = Unit::Microseconds;
  9397. else if (m_inNanoseconds < s_nanosecondsInASecond)
  9398. m_units = Unit::Milliseconds;
  9399. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  9400. m_units = Unit::Seconds;
  9401. else
  9402. m_units = Unit::Minutes;
  9403. }
  9404. }
  9405. auto value() const -> double {
  9406. switch (m_units) {
  9407. case Unit::Microseconds:
  9408. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  9409. case Unit::Milliseconds:
  9410. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  9411. case Unit::Seconds:
  9412. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  9413. case Unit::Minutes:
  9414. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  9415. default:
  9416. return static_cast<double>(m_inNanoseconds);
  9417. }
  9418. }
  9419. auto unitsAsString() const -> std::string {
  9420. switch (m_units) {
  9421. case Unit::Nanoseconds:
  9422. return "ns";
  9423. case Unit::Microseconds:
  9424. return "µs";
  9425. case Unit::Milliseconds:
  9426. return "ms";
  9427. case Unit::Seconds:
  9428. return "s";
  9429. case Unit::Minutes:
  9430. return "m";
  9431. default:
  9432. return "** internal error **";
  9433. }
  9434. }
  9435. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  9436. return os << duration.value() << " " << duration.unitsAsString();
  9437. }
  9438. };
  9439. } // end anon namespace
  9440. class TablePrinter {
  9441. std::ostream& m_os;
  9442. std::vector<ColumnInfo> m_columnInfos;
  9443. std::ostringstream m_oss;
  9444. int m_currentColumn = -1;
  9445. bool m_isOpen = false;
  9446. public:
  9447. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  9448. : m_os( os ),
  9449. m_columnInfos( std::move( columnInfos ) ) {}
  9450. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  9451. return m_columnInfos;
  9452. }
  9453. void open() {
  9454. if (!m_isOpen) {
  9455. m_isOpen = true;
  9456. *this << RowBreak();
  9457. for (auto const& info : m_columnInfos)
  9458. *this << info.name << ColumnBreak();
  9459. *this << RowBreak();
  9460. m_os << Catch::getLineOfChars<'-'>() << "\n";
  9461. }
  9462. }
  9463. void close() {
  9464. if (m_isOpen) {
  9465. *this << RowBreak();
  9466. m_os << std::endl;
  9467. m_isOpen = false;
  9468. }
  9469. }
  9470. template<typename T>
  9471. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  9472. tp.m_oss << value;
  9473. return tp;
  9474. }
  9475. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  9476. auto colStr = tp.m_oss.str();
  9477. // This takes account of utf8 encodings
  9478. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  9479. tp.m_oss.str("");
  9480. tp.open();
  9481. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  9482. tp.m_currentColumn = -1;
  9483. tp.m_os << "\n";
  9484. }
  9485. tp.m_currentColumn++;
  9486. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  9487. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  9488. ? std::string(colInfo.width - (strSize + 2), ' ')
  9489. : std::string();
  9490. if (colInfo.justification == ColumnInfo::Left)
  9491. tp.m_os << colStr << padding << " ";
  9492. else
  9493. tp.m_os << padding << colStr << " ";
  9494. return tp;
  9495. }
  9496. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  9497. if (tp.m_currentColumn > 0) {
  9498. tp.m_os << "\n";
  9499. tp.m_currentColumn = -1;
  9500. }
  9501. return tp;
  9502. }
  9503. };
  9504. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  9505. : StreamingReporterBase(config),
  9506. m_tablePrinter(new TablePrinter(config.stream(),
  9507. {
  9508. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  9509. { "iters", 8, ColumnInfo::Right },
  9510. { "elapsed ns", 14, ColumnInfo::Right },
  9511. { "average", 14, ColumnInfo::Right }
  9512. })) {}
  9513. ConsoleReporter::~ConsoleReporter() = default;
  9514. std::string ConsoleReporter::getDescription() {
  9515. return "Reports test results as plain lines of text";
  9516. }
  9517. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  9518. stream << "No test cases matched '" << spec << '\'' << std::endl;
  9519. }
  9520. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  9521. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  9522. AssertionResult const& result = _assertionStats.assertionResult;
  9523. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  9524. // Drop out if result was successful but we're not printing them.
  9525. if (!includeResults && result.getResultType() != ResultWas::Warning)
  9526. return false;
  9527. lazyPrint();
  9528. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  9529. printer.print();
  9530. stream << std::endl;
  9531. return true;
  9532. }
  9533. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  9534. m_headerPrinted = false;
  9535. StreamingReporterBase::sectionStarting(_sectionInfo);
  9536. }
  9537. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  9538. m_tablePrinter->close();
  9539. if (_sectionStats.missingAssertions) {
  9540. lazyPrint();
  9541. Colour colour(Colour::ResultError);
  9542. if (m_sectionStack.size() > 1)
  9543. stream << "\nNo assertions in section";
  9544. else
  9545. stream << "\nNo assertions in test case";
  9546. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  9547. }
  9548. if (m_config->showDurations() == ShowDurations::Always) {
  9549. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  9550. }
  9551. if (m_headerPrinted) {
  9552. m_headerPrinted = false;
  9553. }
  9554. StreamingReporterBase::sectionEnded(_sectionStats);
  9555. }
  9556. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  9557. lazyPrintWithoutClosingBenchmarkTable();
  9558. auto nameCol = Column( info.name ).width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) );
  9559. bool firstLine = true;
  9560. for (auto line : nameCol) {
  9561. if (!firstLine)
  9562. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  9563. else
  9564. firstLine = false;
  9565. (*m_tablePrinter) << line << ColumnBreak();
  9566. }
  9567. }
  9568. void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) {
  9569. Duration average(stats.elapsedTimeInNanoseconds / stats.iterations);
  9570. (*m_tablePrinter)
  9571. << stats.iterations << ColumnBreak()
  9572. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  9573. << average << ColumnBreak();
  9574. }
  9575. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  9576. m_tablePrinter->close();
  9577. StreamingReporterBase::testCaseEnded(_testCaseStats);
  9578. m_headerPrinted = false;
  9579. }
  9580. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  9581. if (currentGroupInfo.used) {
  9582. printSummaryDivider();
  9583. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  9584. printTotals(_testGroupStats.totals);
  9585. stream << '\n' << std::endl;
  9586. }
  9587. StreamingReporterBase::testGroupEnded(_testGroupStats);
  9588. }
  9589. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  9590. printTotalsDivider(_testRunStats.totals);
  9591. printTotals(_testRunStats.totals);
  9592. stream << std::endl;
  9593. StreamingReporterBase::testRunEnded(_testRunStats);
  9594. }
  9595. void ConsoleReporter::lazyPrint() {
  9596. m_tablePrinter->close();
  9597. lazyPrintWithoutClosingBenchmarkTable();
  9598. }
  9599. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  9600. if (!currentTestRunInfo.used)
  9601. lazyPrintRunInfo();
  9602. if (!currentGroupInfo.used)
  9603. lazyPrintGroupInfo();
  9604. if (!m_headerPrinted) {
  9605. printTestCaseAndSectionHeader();
  9606. m_headerPrinted = true;
  9607. }
  9608. }
  9609. void ConsoleReporter::lazyPrintRunInfo() {
  9610. stream << '\n' << getLineOfChars<'~'>() << '\n';
  9611. Colour colour(Colour::SecondaryText);
  9612. stream << currentTestRunInfo->name
  9613. << " is a Catch v" << libraryVersion() << " host application.\n"
  9614. << "Run with -? for options\n\n";
  9615. if (m_config->rngSeed() != 0)
  9616. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  9617. currentTestRunInfo.used = true;
  9618. }
  9619. void ConsoleReporter::lazyPrintGroupInfo() {
  9620. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  9621. printClosedHeader("Group: " + currentGroupInfo->name);
  9622. currentGroupInfo.used = true;
  9623. }
  9624. }
  9625. void ConsoleReporter::printTestCaseAndSectionHeader() {
  9626. assert(!m_sectionStack.empty());
  9627. printOpenHeader(currentTestCaseInfo->name);
  9628. if (m_sectionStack.size() > 1) {
  9629. Colour colourGuard(Colour::Headers);
  9630. auto
  9631. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  9632. itEnd = m_sectionStack.end();
  9633. for (; it != itEnd; ++it)
  9634. printHeaderString(it->name, 2);
  9635. }
  9636. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  9637. if (!lineInfo.empty()) {
  9638. stream << getLineOfChars<'-'>() << '\n';
  9639. Colour colourGuard(Colour::FileName);
  9640. stream << lineInfo << '\n';
  9641. }
  9642. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  9643. }
  9644. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  9645. printOpenHeader(_name);
  9646. stream << getLineOfChars<'.'>() << '\n';
  9647. }
  9648. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  9649. stream << getLineOfChars<'-'>() << '\n';
  9650. {
  9651. Colour colourGuard(Colour::Headers);
  9652. printHeaderString(_name);
  9653. }
  9654. }
  9655. // if string has a : in first line will set indent to follow it on
  9656. // subsequent lines
  9657. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  9658. std::size_t i = _string.find(": ");
  9659. if (i != std::string::npos)
  9660. i += 2;
  9661. else
  9662. i = 0;
  9663. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  9664. }
  9665. struct SummaryColumn {
  9666. SummaryColumn( std::string _label, Colour::Code _colour )
  9667. : label( std::move( _label ) ),
  9668. colour( _colour ) {}
  9669. SummaryColumn addRow( std::size_t count ) {
  9670. ReusableStringStream rss;
  9671. rss << count;
  9672. std::string row = rss.str();
  9673. for (auto& oldRow : rows) {
  9674. while (oldRow.size() < row.size())
  9675. oldRow = ' ' + oldRow;
  9676. while (oldRow.size() > row.size())
  9677. row = ' ' + row;
  9678. }
  9679. rows.push_back(row);
  9680. return *this;
  9681. }
  9682. std::string label;
  9683. Colour::Code colour;
  9684. std::vector<std::string> rows;
  9685. };
  9686. void ConsoleReporter::printTotals( Totals const& totals ) {
  9687. if (totals.testCases.total() == 0) {
  9688. stream << Colour(Colour::Warning) << "No tests ran\n";
  9689. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  9690. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  9691. stream << " ("
  9692. << pluralise(totals.assertions.passed, "assertion") << " in "
  9693. << pluralise(totals.testCases.passed, "test case") << ')'
  9694. << '\n';
  9695. } else {
  9696. std::vector<SummaryColumn> columns;
  9697. columns.push_back(SummaryColumn("", Colour::None)
  9698. .addRow(totals.testCases.total())
  9699. .addRow(totals.assertions.total()));
  9700. columns.push_back(SummaryColumn("passed", Colour::Success)
  9701. .addRow(totals.testCases.passed)
  9702. .addRow(totals.assertions.passed));
  9703. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  9704. .addRow(totals.testCases.failed)
  9705. .addRow(totals.assertions.failed));
  9706. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  9707. .addRow(totals.testCases.failedButOk)
  9708. .addRow(totals.assertions.failedButOk));
  9709. printSummaryRow("test cases", columns, 0);
  9710. printSummaryRow("assertions", columns, 1);
  9711. }
  9712. }
  9713. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  9714. for (auto col : cols) {
  9715. std::string value = col.rows[row];
  9716. if (col.label.empty()) {
  9717. stream << label << ": ";
  9718. if (value != "0")
  9719. stream << value;
  9720. else
  9721. stream << Colour(Colour::Warning) << "- none -";
  9722. } else if (value != "0") {
  9723. stream << Colour(Colour::LightGrey) << " | ";
  9724. stream << Colour(col.colour)
  9725. << value << ' ' << col.label;
  9726. }
  9727. }
  9728. stream << '\n';
  9729. }
  9730. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  9731. if (totals.testCases.total() > 0) {
  9732. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  9733. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  9734. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  9735. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  9736. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  9737. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  9738. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  9739. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  9740. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  9741. if (totals.testCases.allPassed())
  9742. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  9743. else
  9744. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  9745. } else {
  9746. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  9747. }
  9748. stream << '\n';
  9749. }
  9750. void ConsoleReporter::printSummaryDivider() {
  9751. stream << getLineOfChars<'-'>() << '\n';
  9752. }
  9753. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  9754. } // end namespace Catch
  9755. #if defined(_MSC_VER)
  9756. #pragma warning(pop)
  9757. #endif
  9758. // end catch_reporter_console.cpp
  9759. // start catch_reporter_junit.cpp
  9760. #include <assert.h>
  9761. #include <sstream>
  9762. #include <ctime>
  9763. #include <algorithm>
  9764. namespace Catch {
  9765. namespace {
  9766. std::string getCurrentTimestamp() {
  9767. // Beware, this is not reentrant because of backward compatibility issues
  9768. // Also, UTC only, again because of backward compatibility (%z is C++11)
  9769. time_t rawtime;
  9770. std::time(&rawtime);
  9771. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  9772. #ifdef _MSC_VER
  9773. std::tm timeInfo = {};
  9774. gmtime_s(&timeInfo, &rawtime);
  9775. #else
  9776. std::tm* timeInfo;
  9777. timeInfo = std::gmtime(&rawtime);
  9778. #endif
  9779. char timeStamp[timeStampSize];
  9780. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  9781. #ifdef _MSC_VER
  9782. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  9783. #else
  9784. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  9785. #endif
  9786. return std::string(timeStamp);
  9787. }
  9788. std::string fileNameTag(const std::vector<std::string> &tags) {
  9789. auto it = std::find_if(begin(tags),
  9790. end(tags),
  9791. [] (std::string const& tag) {return tag.front() == '#'; });
  9792. if (it != tags.end())
  9793. return it->substr(1);
  9794. return std::string();
  9795. }
  9796. } // anonymous namespace
  9797. JunitReporter::JunitReporter( ReporterConfig const& _config )
  9798. : CumulativeReporterBase( _config ),
  9799. xml( _config.stream() )
  9800. {
  9801. m_reporterPrefs.shouldRedirectStdOut = true;
  9802. }
  9803. JunitReporter::~JunitReporter() {}
  9804. std::string JunitReporter::getDescription() {
  9805. return "Reports test results in an XML format that looks like Ant's junitreport target";
  9806. }
  9807. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  9808. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  9809. CumulativeReporterBase::testRunStarting( runInfo );
  9810. xml.startElement( "testsuites" );
  9811. }
  9812. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  9813. suiteTimer.start();
  9814. stdOutForSuite.clear();
  9815. stdErrForSuite.clear();
  9816. unexpectedExceptions = 0;
  9817. CumulativeReporterBase::testGroupStarting( groupInfo );
  9818. }
  9819. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  9820. m_okToFail = testCaseInfo.okToFail();
  9821. }
  9822. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  9823. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  9824. unexpectedExceptions++;
  9825. return CumulativeReporterBase::assertionEnded( assertionStats );
  9826. }
  9827. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  9828. stdOutForSuite += testCaseStats.stdOut;
  9829. stdErrForSuite += testCaseStats.stdErr;
  9830. CumulativeReporterBase::testCaseEnded( testCaseStats );
  9831. }
  9832. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  9833. double suiteTime = suiteTimer.getElapsedSeconds();
  9834. CumulativeReporterBase::testGroupEnded( testGroupStats );
  9835. writeGroup( *m_testGroups.back(), suiteTime );
  9836. }
  9837. void JunitReporter::testRunEndedCumulative() {
  9838. xml.endElement();
  9839. }
  9840. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  9841. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  9842. TestGroupStats const& stats = groupNode.value;
  9843. xml.writeAttribute( "name", stats.groupInfo.name );
  9844. xml.writeAttribute( "errors", unexpectedExceptions );
  9845. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  9846. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  9847. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  9848. if( m_config->showDurations() == ShowDurations::Never )
  9849. xml.writeAttribute( "time", "" );
  9850. else
  9851. xml.writeAttribute( "time", suiteTime );
  9852. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  9853. // Write test cases
  9854. for( auto const& child : groupNode.children )
  9855. writeTestCase( *child );
  9856. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  9857. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  9858. }
  9859. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  9860. TestCaseStats const& stats = testCaseNode.value;
  9861. // All test cases have exactly one section - which represents the
  9862. // test case itself. That section may have 0-n nested sections
  9863. assert( testCaseNode.children.size() == 1 );
  9864. SectionNode const& rootSection = *testCaseNode.children.front();
  9865. std::string className = stats.testInfo.className;
  9866. if( className.empty() ) {
  9867. className = fileNameTag(stats.testInfo.tags);
  9868. if ( className.empty() )
  9869. className = "global";
  9870. }
  9871. if ( !m_config->name().empty() )
  9872. className = m_config->name() + "." + className;
  9873. writeSection( className, "", rootSection );
  9874. }
  9875. void JunitReporter::writeSection( std::string const& className,
  9876. std::string const& rootName,
  9877. SectionNode const& sectionNode ) {
  9878. std::string name = trim( sectionNode.stats.sectionInfo.name );
  9879. if( !rootName.empty() )
  9880. name = rootName + '/' + name;
  9881. if( !sectionNode.assertions.empty() ||
  9882. !sectionNode.stdOut.empty() ||
  9883. !sectionNode.stdErr.empty() ) {
  9884. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  9885. if( className.empty() ) {
  9886. xml.writeAttribute( "classname", name );
  9887. xml.writeAttribute( "name", "root" );
  9888. }
  9889. else {
  9890. xml.writeAttribute( "classname", className );
  9891. xml.writeAttribute( "name", name );
  9892. }
  9893. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  9894. writeAssertions( sectionNode );
  9895. if( !sectionNode.stdOut.empty() )
  9896. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  9897. if( !sectionNode.stdErr.empty() )
  9898. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  9899. }
  9900. for( auto const& childNode : sectionNode.childSections )
  9901. if( className.empty() )
  9902. writeSection( name, "", *childNode );
  9903. else
  9904. writeSection( className, name, *childNode );
  9905. }
  9906. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  9907. for( auto const& assertion : sectionNode.assertions )
  9908. writeAssertion( assertion );
  9909. }
  9910. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  9911. AssertionResult const& result = stats.assertionResult;
  9912. if( !result.isOk() ) {
  9913. std::string elementName;
  9914. switch( result.getResultType() ) {
  9915. case ResultWas::ThrewException:
  9916. case ResultWas::FatalErrorCondition:
  9917. elementName = "error";
  9918. break;
  9919. case ResultWas::ExplicitFailure:
  9920. elementName = "failure";
  9921. break;
  9922. case ResultWas::ExpressionFailed:
  9923. elementName = "failure";
  9924. break;
  9925. case ResultWas::DidntThrowException:
  9926. elementName = "failure";
  9927. break;
  9928. // We should never see these here:
  9929. case ResultWas::Info:
  9930. case ResultWas::Warning:
  9931. case ResultWas::Ok:
  9932. case ResultWas::Unknown:
  9933. case ResultWas::FailureBit:
  9934. case ResultWas::Exception:
  9935. elementName = "internalError";
  9936. break;
  9937. }
  9938. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  9939. xml.writeAttribute( "message", result.getExpandedExpression() );
  9940. xml.writeAttribute( "type", result.getTestMacroName() );
  9941. ReusableStringStream rss;
  9942. if( !result.getMessage().empty() )
  9943. rss << result.getMessage() << '\n';
  9944. for( auto const& msg : stats.infoMessages )
  9945. if( msg.type == ResultWas::Info )
  9946. rss << msg.message << '\n';
  9947. rss << "at " << result.getSourceInfo();
  9948. xml.writeText( rss.str(), false );
  9949. }
  9950. }
  9951. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  9952. } // end namespace Catch
  9953. // end catch_reporter_junit.cpp
  9954. // start catch_reporter_multi.cpp
  9955. namespace Catch {
  9956. void MultipleReporters::add( IStreamingReporterPtr&& reporter ) {
  9957. m_reporters.push_back( std::move( reporter ) );
  9958. }
  9959. ReporterPreferences MultipleReporters::getPreferences() const {
  9960. return m_reporters[0]->getPreferences();
  9961. }
  9962. std::set<Verbosity> MultipleReporters::getSupportedVerbosities() {
  9963. return std::set<Verbosity>{ };
  9964. }
  9965. void MultipleReporters::noMatchingTestCases( std::string const& spec ) {
  9966. for( auto const& reporter : m_reporters )
  9967. reporter->noMatchingTestCases( spec );
  9968. }
  9969. void MultipleReporters::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  9970. for( auto const& reporter : m_reporters )
  9971. reporter->benchmarkStarting( benchmarkInfo );
  9972. }
  9973. void MultipleReporters::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
  9974. for( auto const& reporter : m_reporters )
  9975. reporter->benchmarkEnded( benchmarkStats );
  9976. }
  9977. void MultipleReporters::testRunStarting( TestRunInfo const& testRunInfo ) {
  9978. for( auto const& reporter : m_reporters )
  9979. reporter->testRunStarting( testRunInfo );
  9980. }
  9981. void MultipleReporters::testGroupStarting( GroupInfo const& groupInfo ) {
  9982. for( auto const& reporter : m_reporters )
  9983. reporter->testGroupStarting( groupInfo );
  9984. }
  9985. void MultipleReporters::testCaseStarting( TestCaseInfo const& testInfo ) {
  9986. for( auto const& reporter : m_reporters )
  9987. reporter->testCaseStarting( testInfo );
  9988. }
  9989. void MultipleReporters::sectionStarting( SectionInfo const& sectionInfo ) {
  9990. for( auto const& reporter : m_reporters )
  9991. reporter->sectionStarting( sectionInfo );
  9992. }
  9993. void MultipleReporters::assertionStarting( AssertionInfo const& assertionInfo ) {
  9994. for( auto const& reporter : m_reporters )
  9995. reporter->assertionStarting( assertionInfo );
  9996. }
  9997. // The return value indicates if the messages buffer should be cleared:
  9998. bool MultipleReporters::assertionEnded( AssertionStats const& assertionStats ) {
  9999. bool clearBuffer = false;
  10000. for( auto const& reporter : m_reporters )
  10001. clearBuffer |= reporter->assertionEnded( assertionStats );
  10002. return clearBuffer;
  10003. }
  10004. void MultipleReporters::sectionEnded( SectionStats const& sectionStats ) {
  10005. for( auto const& reporter : m_reporters )
  10006. reporter->sectionEnded( sectionStats );
  10007. }
  10008. void MultipleReporters::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10009. for( auto const& reporter : m_reporters )
  10010. reporter->testCaseEnded( testCaseStats );
  10011. }
  10012. void MultipleReporters::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10013. for( auto const& reporter : m_reporters )
  10014. reporter->testGroupEnded( testGroupStats );
  10015. }
  10016. void MultipleReporters::testRunEnded( TestRunStats const& testRunStats ) {
  10017. for( auto const& reporter : m_reporters )
  10018. reporter->testRunEnded( testRunStats );
  10019. }
  10020. void MultipleReporters::skipTest( TestCaseInfo const& testInfo ) {
  10021. for( auto const& reporter : m_reporters )
  10022. reporter->skipTest( testInfo );
  10023. }
  10024. bool MultipleReporters::isMulti() const {
  10025. return true;
  10026. }
  10027. } // end namespace Catch
  10028. // end catch_reporter_multi.cpp
  10029. // start catch_reporter_xml.cpp
  10030. #if defined(_MSC_VER)
  10031. #pragma warning(push)
  10032. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  10033. // Note that 4062 (not all labels are handled
  10034. // and default is missing) is enabled
  10035. #endif
  10036. namespace Catch {
  10037. XmlReporter::XmlReporter( ReporterConfig const& _config )
  10038. : StreamingReporterBase( _config ),
  10039. m_xml(_config.stream())
  10040. {
  10041. m_reporterPrefs.shouldRedirectStdOut = true;
  10042. }
  10043. XmlReporter::~XmlReporter() = default;
  10044. std::string XmlReporter::getDescription() {
  10045. return "Reports test results as an XML document";
  10046. }
  10047. std::string XmlReporter::getStylesheetRef() const {
  10048. return std::string();
  10049. }
  10050. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  10051. m_xml
  10052. .writeAttribute( "filename", sourceInfo.file )
  10053. .writeAttribute( "line", sourceInfo.line );
  10054. }
  10055. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  10056. StreamingReporterBase::noMatchingTestCases( s );
  10057. }
  10058. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  10059. StreamingReporterBase::testRunStarting( testInfo );
  10060. std::string stylesheetRef = getStylesheetRef();
  10061. if( !stylesheetRef.empty() )
  10062. m_xml.writeStylesheetRef( stylesheetRef );
  10063. m_xml.startElement( "Catch" );
  10064. if( !m_config->name().empty() )
  10065. m_xml.writeAttribute( "name", m_config->name() );
  10066. }
  10067. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  10068. StreamingReporterBase::testGroupStarting( groupInfo );
  10069. m_xml.startElement( "Group" )
  10070. .writeAttribute( "name", groupInfo.name );
  10071. }
  10072. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  10073. StreamingReporterBase::testCaseStarting(testInfo);
  10074. m_xml.startElement( "TestCase" )
  10075. .writeAttribute( "name", trim( testInfo.name ) )
  10076. .writeAttribute( "description", testInfo.description )
  10077. .writeAttribute( "tags", testInfo.tagsAsString() );
  10078. writeSourceInfo( testInfo.lineInfo );
  10079. if ( m_config->showDurations() == ShowDurations::Always )
  10080. m_testCaseTimer.start();
  10081. m_xml.ensureTagClosed();
  10082. }
  10083. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  10084. StreamingReporterBase::sectionStarting( sectionInfo );
  10085. if( m_sectionDepth++ > 0 ) {
  10086. m_xml.startElement( "Section" )
  10087. .writeAttribute( "name", trim( sectionInfo.name ) )
  10088. .writeAttribute( "description", sectionInfo.description );
  10089. writeSourceInfo( sectionInfo.lineInfo );
  10090. m_xml.ensureTagClosed();
  10091. }
  10092. }
  10093. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  10094. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10095. AssertionResult const& result = assertionStats.assertionResult;
  10096. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  10097. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  10098. // Print any info messages in <Info> tags.
  10099. for( auto const& msg : assertionStats.infoMessages ) {
  10100. if( msg.type == ResultWas::Info && includeResults ) {
  10101. m_xml.scopedElement( "Info" )
  10102. .writeText( msg.message );
  10103. } else if ( msg.type == ResultWas::Warning ) {
  10104. m_xml.scopedElement( "Warning" )
  10105. .writeText( msg.message );
  10106. }
  10107. }
  10108. }
  10109. // Drop out if result was successful but we're not printing them.
  10110. if( !includeResults && result.getResultType() != ResultWas::Warning )
  10111. return true;
  10112. // Print the expression if there is one.
  10113. if( result.hasExpression() ) {
  10114. m_xml.startElement( "Expression" )
  10115. .writeAttribute( "success", result.succeeded() )
  10116. .writeAttribute( "type", result.getTestMacroName() );
  10117. writeSourceInfo( result.getSourceInfo() );
  10118. m_xml.scopedElement( "Original" )
  10119. .writeText( result.getExpression() );
  10120. m_xml.scopedElement( "Expanded" )
  10121. .writeText( result.getExpandedExpression() );
  10122. }
  10123. // And... Print a result applicable to each result type.
  10124. switch( result.getResultType() ) {
  10125. case ResultWas::ThrewException:
  10126. m_xml.startElement( "Exception" );
  10127. writeSourceInfo( result.getSourceInfo() );
  10128. m_xml.writeText( result.getMessage() );
  10129. m_xml.endElement();
  10130. break;
  10131. case ResultWas::FatalErrorCondition:
  10132. m_xml.startElement( "FatalErrorCondition" );
  10133. writeSourceInfo( result.getSourceInfo() );
  10134. m_xml.writeText( result.getMessage() );
  10135. m_xml.endElement();
  10136. break;
  10137. case ResultWas::Info:
  10138. m_xml.scopedElement( "Info" )
  10139. .writeText( result.getMessage() );
  10140. break;
  10141. case ResultWas::Warning:
  10142. // Warning will already have been written
  10143. break;
  10144. case ResultWas::ExplicitFailure:
  10145. m_xml.startElement( "Failure" );
  10146. writeSourceInfo( result.getSourceInfo() );
  10147. m_xml.writeText( result.getMessage() );
  10148. m_xml.endElement();
  10149. break;
  10150. default:
  10151. break;
  10152. }
  10153. if( result.hasExpression() )
  10154. m_xml.endElement();
  10155. return true;
  10156. }
  10157. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  10158. StreamingReporterBase::sectionEnded( sectionStats );
  10159. if( --m_sectionDepth > 0 ) {
  10160. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  10161. e.writeAttribute( "successes", sectionStats.assertions.passed );
  10162. e.writeAttribute( "failures", sectionStats.assertions.failed );
  10163. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  10164. if ( m_config->showDurations() == ShowDurations::Always )
  10165. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  10166. m_xml.endElement();
  10167. }
  10168. }
  10169. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10170. StreamingReporterBase::testCaseEnded( testCaseStats );
  10171. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  10172. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  10173. if ( m_config->showDurations() == ShowDurations::Always )
  10174. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  10175. if( !testCaseStats.stdOut.empty() )
  10176. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  10177. if( !testCaseStats.stdErr.empty() )
  10178. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  10179. m_xml.endElement();
  10180. }
  10181. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10182. StreamingReporterBase::testGroupEnded( testGroupStats );
  10183. // TODO: Check testGroupStats.aborting and act accordingly.
  10184. m_xml.scopedElement( "OverallResults" )
  10185. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  10186. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  10187. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  10188. m_xml.endElement();
  10189. }
  10190. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  10191. StreamingReporterBase::testRunEnded( testRunStats );
  10192. m_xml.scopedElement( "OverallResults" )
  10193. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  10194. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  10195. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  10196. m_xml.endElement();
  10197. }
  10198. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  10199. } // end namespace Catch
  10200. #if defined(_MSC_VER)
  10201. #pragma warning(pop)
  10202. #endif
  10203. // end catch_reporter_xml.cpp
  10204. namespace Catch {
  10205. LeakDetector leakDetector;
  10206. }
  10207. #ifdef __clang__
  10208. #pragma clang diagnostic pop
  10209. #endif
  10210. // end catch_impl.hpp
  10211. #endif
  10212. #ifdef CATCH_CONFIG_MAIN
  10213. // start catch_default_main.hpp
  10214. #ifndef __OBJC__
  10215. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  10216. // Standard C/C++ Win32 Unicode wmain entry point
  10217. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  10218. #else
  10219. // Standard C/C++ main entry point
  10220. int main (int argc, char * argv[]) {
  10221. #endif
  10222. return Catch::Session().run( argc, argv );
  10223. }
  10224. #else // __OBJC__
  10225. // Objective-C entry point
  10226. int main (int argc, char * const argv[]) {
  10227. #if !CATCH_ARC_ENABLED
  10228. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  10229. #endif
  10230. Catch::registerTestMethods();
  10231. int result = Catch::Session().run( argc, (char**)argv );
  10232. #if !CATCH_ARC_ENABLED
  10233. [pool drain];
  10234. #endif
  10235. return result;
  10236. }
  10237. #endif // __OBJC__
  10238. // end catch_default_main.hpp
  10239. #endif
  10240. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  10241. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  10242. # undef CLARA_CONFIG_MAIN
  10243. #endif
  10244. #if !defined(CATCH_CONFIG_DISABLE)
  10245. //////
  10246. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  10247. #ifdef CATCH_CONFIG_PREFIX_ALL
  10248. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10249. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10250. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", __VA_ARGS__ )
  10251. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  10252. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  10253. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10254. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  10255. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  10256. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10257. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10258. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10259. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10260. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10261. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  10262. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", __VA_ARGS__ )
  10263. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  10264. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10265. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10266. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10267. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10268. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10269. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10270. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  10271. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  10272. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10273. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  10274. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  10275. #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  10276. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  10277. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  10278. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  10279. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  10280. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  10281. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10282. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10283. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10284. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  10285. // "BDD-style" convenience wrappers
  10286. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  10287. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  10288. #define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( "Given: ") + desc )
  10289. #define CATCH_WHEN( desc ) CATCH_SECTION( std::string( " When: ") + desc )
  10290. #define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  10291. #define CATCH_THEN( desc ) CATCH_SECTION( std::string( " Then: ") + desc )
  10292. #define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( " And: ") + desc )
  10293. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  10294. #else
  10295. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10296. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10297. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10298. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  10299. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  10300. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10301. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  10302. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10303. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10304. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10305. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10306. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10307. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10308. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  10309. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10310. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  10311. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10312. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10313. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10314. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10315. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10316. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10317. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  10318. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  10319. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10320. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  10321. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  10322. #define CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  10323. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  10324. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  10325. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  10326. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  10327. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  10328. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10329. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10330. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10331. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  10332. #endif
  10333. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  10334. // "BDD-style" convenience wrappers
  10335. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  10336. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  10337. #define GIVEN( desc ) SECTION( std::string(" Given: ") + desc )
  10338. #define WHEN( desc ) SECTION( std::string(" When: ") + desc )
  10339. #define AND_WHEN( desc ) SECTION( std::string("And when: ") + desc )
  10340. #define THEN( desc ) SECTION( std::string(" Then: ") + desc )
  10341. #define AND_THEN( desc ) SECTION( std::string(" And: ") + desc )
  10342. using Catch::Detail::Approx;
  10343. #else
  10344. //////
  10345. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  10346. #ifdef CATCH_CONFIG_PREFIX_ALL
  10347. #define CATCH_REQUIRE( ... ) (void)(0)
  10348. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  10349. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  10350. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  10351. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  10352. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10353. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10354. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  10355. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  10356. #define CATCH_CHECK( ... ) (void)(0)
  10357. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  10358. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  10359. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  10360. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  10361. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  10362. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  10363. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  10364. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10365. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10366. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10367. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  10368. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10369. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  10370. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  10371. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10372. #define CATCH_INFO( msg ) (void)(0)
  10373. #define CATCH_WARN( msg ) (void)(0)
  10374. #define CATCH_CAPTURE( msg ) (void)(0)
  10375. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10376. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10377. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  10378. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  10379. #define CATCH_SECTION( ... )
  10380. #define CATCH_FAIL( ... ) (void)(0)
  10381. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  10382. #define CATCH_SUCCEED( ... ) (void)(0)
  10383. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10384. // "BDD-style" convenience wrappers
  10385. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10386. #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 )
  10387. #define CATCH_GIVEN( desc )
  10388. #define CATCH_WHEN( desc )
  10389. #define CATCH_AND_WHEN( desc )
  10390. #define CATCH_THEN( desc )
  10391. #define CATCH_AND_THEN( desc )
  10392. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  10393. #else
  10394. #define REQUIRE( ... ) (void)(0)
  10395. #define REQUIRE_FALSE( ... ) (void)(0)
  10396. #define REQUIRE_THROWS( ... ) (void)(0)
  10397. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  10398. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  10399. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10400. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10401. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10402. #define REQUIRE_NOTHROW( ... ) (void)(0)
  10403. #define CHECK( ... ) (void)(0)
  10404. #define CHECK_FALSE( ... ) (void)(0)
  10405. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  10406. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  10407. #define CHECK_NOFAIL( ... ) (void)(0)
  10408. #define CHECK_THROWS( ... ) (void)(0)
  10409. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  10410. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  10411. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10412. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10413. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10414. #define CHECK_NOTHROW( ... ) (void)(0)
  10415. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10416. #define CHECK_THAT( arg, matcher ) (void)(0)
  10417. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  10418. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10419. #define INFO( msg ) (void)(0)
  10420. #define WARN( msg ) (void)(0)
  10421. #define CAPTURE( msg ) (void)(0)
  10422. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10423. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10424. #define METHOD_AS_TEST_CASE( method, ... )
  10425. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  10426. #define SECTION( ... )
  10427. #define FAIL( ... ) (void)(0)
  10428. #define FAIL_CHECK( ... ) (void)(0)
  10429. #define SUCCEED( ... ) (void)(0)
  10430. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10431. #endif
  10432. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  10433. // "BDD-style" convenience wrappers
  10434. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  10435. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  10436. #define GIVEN( desc )
  10437. #define WHEN( desc )
  10438. #define AND_WHEN( desc )
  10439. #define THEN( desc )
  10440. #define AND_THEN( desc )
  10441. using Catch::Detail::Approx;
  10442. #endif
  10443. #endif // ! CATCH_CONFIG_IMPL_ONLY
  10444. // start catch_reenable_warnings.h
  10445. #ifdef __clang__
  10446. # ifdef __ICC // icpc defines the __clang__ macro
  10447. # pragma warning(pop)
  10448. # else
  10449. # pragma clang diagnostic pop
  10450. # endif
  10451. #elif defined __GNUC__
  10452. # pragma GCC diagnostic pop
  10453. #endif
  10454. // end catch_reenable_warnings.h
  10455. // end catch.hpp
  10456. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED