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.

13360 lines
443KB

  1. /*
  2. * Catch v2.3.0
  3. * Generated: 2018-07-23 10:09:14.936841
  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 3
  16. #define CATCH_VERSION_PATCH 0
  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 push
  29. # pragma clang diagnostic ignored "-Wpadded"
  30. # pragma clang diagnostic ignored "-Wswitch-enum"
  31. # pragma clang diagnostic ignored "-Wcovered-switch-default"
  32. # endif
  33. #elif defined __GNUC__
  34. // GCC likes to warn on REQUIREs, and we cannot suppress them
  35. // locally because g++'s support for _Pragma is lacking in older,
  36. // still supported, versions
  37. # pragma GCC diagnostic ignored "-Wparentheses"
  38. # pragma GCC diagnostic push
  39. # pragma GCC diagnostic ignored "-Wunused-variable"
  40. # pragma GCC diagnostic ignored "-Wpadded"
  41. #endif
  42. // end catch_suppress_warnings.h
  43. #if defined(CATCH_CONFIG_MAIN) || defined(CATCH_CONFIG_RUNNER)
  44. # define CATCH_IMPL
  45. # define CATCH_CONFIG_ALL_PARTS
  46. #endif
  47. // In the impl file, we want to have access to all parts of the headers
  48. // Can also be used to sanely support PCHs
  49. #if defined(CATCH_CONFIG_ALL_PARTS)
  50. # define CATCH_CONFIG_EXTERNAL_INTERFACES
  51. # if defined(CATCH_CONFIG_DISABLE_MATCHERS)
  52. # undef CATCH_CONFIG_DISABLE_MATCHERS
  53. # endif
  54. # if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  55. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  56. # endif
  57. #endif
  58. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  59. // start catch_platform.h
  60. #ifdef __APPLE__
  61. # include <TargetConditionals.h>
  62. # if TARGET_OS_OSX == 1
  63. # define CATCH_PLATFORM_MAC
  64. # elif TARGET_OS_IPHONE == 1
  65. # define CATCH_PLATFORM_IPHONE
  66. # endif
  67. #elif defined(linux) || defined(__linux) || defined(__linux__)
  68. # define CATCH_PLATFORM_LINUX
  69. #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) || defined(__MINGW32__)
  70. # define CATCH_PLATFORM_WINDOWS
  71. #endif
  72. // end catch_platform.h
  73. #ifdef CATCH_IMPL
  74. # ifndef CLARA_CONFIG_MAIN
  75. # define CLARA_CONFIG_MAIN_NOT_DEFINED
  76. # define CLARA_CONFIG_MAIN
  77. # endif
  78. #endif
  79. // start catch_user_interfaces.h
  80. namespace Catch {
  81. unsigned int rngSeed();
  82. }
  83. // end catch_user_interfaces.h
  84. // start catch_tag_alias_autoregistrar.h
  85. // start catch_common.h
  86. // start catch_compiler_capabilities.h
  87. // Detect a number of compiler features - by compiler
  88. // The following features are defined:
  89. //
  90. // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported?
  91. // CATCH_CONFIG_WINDOWS_SEH : is Windows SEH supported?
  92. // CATCH_CONFIG_POSIX_SIGNALS : are POSIX signals supported?
  93. // ****************
  94. // Note to maintainers: if new toggles are added please document them
  95. // in configuration.md, too
  96. // ****************
  97. // In general each macro has a _NO_<feature name> form
  98. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  99. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  100. // can be combined, en-mass, with the _NO_ forms later.
  101. #ifdef __cplusplus
  102. # if __cplusplus >= 201402L
  103. # define CATCH_CPP14_OR_GREATER
  104. # endif
  105. # if __cplusplus >= 201703L
  106. # define CATCH_CPP17_OR_GREATER
  107. # endif
  108. #endif
  109. #if defined(CATCH_CPP17_OR_GREATER)
  110. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  111. #endif
  112. #ifdef __clang__
  113. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  114. _Pragma( "clang diagnostic push" ) \
  115. _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
  116. _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
  117. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  118. _Pragma( "clang diagnostic pop" )
  119. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  120. _Pragma( "clang diagnostic push" ) \
  121. _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
  122. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  123. _Pragma( "clang diagnostic pop" )
  124. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  125. _Pragma( "clang diagnostic push" ) \
  126. _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
  127. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS \
  128. _Pragma( "clang diagnostic pop" )
  129. #endif // __clang__
  130. ////////////////////////////////////////////////////////////////////////////////
  131. // Assume that non-Windows platforms support posix signals by default
  132. #if !defined(CATCH_PLATFORM_WINDOWS)
  133. #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
  134. #endif
  135. ////////////////////////////////////////////////////////////////////////////////
  136. // We know some environments not to support full POSIX signals
  137. #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
  138. #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  139. #endif
  140. #ifdef __OS400__
  141. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  142. # define CATCH_CONFIG_COLOUR_NONE
  143. #endif
  144. ////////////////////////////////////////////////////////////////////////////////
  145. // Android somehow still does not support std::to_string
  146. #if defined(__ANDROID__)
  147. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  148. #endif
  149. ////////////////////////////////////////////////////////////////////////////////
  150. // Not all Windows environments support SEH properly
  151. #if defined(__MINGW32__)
  152. # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
  153. #endif
  154. ////////////////////////////////////////////////////////////////////////////////
  155. // PS4
  156. #if defined(__ORBIS__)
  157. # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
  158. #endif
  159. ////////////////////////////////////////////////////////////////////////////////
  160. // Cygwin
  161. #ifdef __CYGWIN__
  162. // Required for some versions of Cygwin to declare gettimeofday
  163. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  164. # define _BSD_SOURCE
  165. #endif // __CYGWIN__
  166. ////////////////////////////////////////////////////////////////////////////////
  167. // Visual C++
  168. #ifdef _MSC_VER
  169. # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
  170. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  171. # endif
  172. // Universal Windows platform does not support SEH
  173. // Or console colours (or console at all...)
  174. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  175. # define CATCH_CONFIG_COLOUR_NONE
  176. # else
  177. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  178. # endif
  179. #endif // _MSC_VER
  180. ////////////////////////////////////////////////////////////////////////////////
  181. // DJGPP
  182. #ifdef __DJGPP__
  183. # define CATCH_INTERNAL_CONFIG_NO_WCHAR
  184. #endif // __DJGPP__
  185. ////////////////////////////////////////////////////////////////////////////////
  186. // Use of __COUNTER__ is suppressed during code analysis in
  187. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  188. // handled by it.
  189. // Otherwise all supported compilers support COUNTER macro,
  190. // but user still might want to turn it off
  191. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  192. #define CATCH_INTERNAL_CONFIG_COUNTER
  193. #endif
  194. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  195. # define CATCH_CONFIG_COUNTER
  196. #endif
  197. #if defined(CATCH_INTERNAL_CONFIG_WINDOWS_SEH) && !defined(CATCH_CONFIG_NO_WINDOWS_SEH) && !defined(CATCH_CONFIG_WINDOWS_SEH) && !defined(CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH)
  198. # define CATCH_CONFIG_WINDOWS_SEH
  199. #endif
  200. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  201. #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)
  202. # define CATCH_CONFIG_POSIX_SIGNALS
  203. #endif
  204. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  205. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  206. # define CATCH_CONFIG_WCHAR
  207. #endif
  208. #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
  209. # define CATCH_CONFIG_CPP11_TO_STRING
  210. #endif
  211. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  212. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  213. #endif
  214. #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  215. # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
  216. #endif
  217. #if defined(CATCH_INTERNAL_CONFIG_NEW_CAPTURE) && !defined(CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NO_NEW_CAPTURE) && !defined(CATCH_CONFIG_NEW_CAPTURE)
  218. # define CATCH_CONFIG_NEW_CAPTURE
  219. #endif
  220. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  221. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  222. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  223. #endif
  224. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  225. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  226. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  227. #endif
  228. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
  229. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
  230. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  231. #endif
  232. // end catch_compiler_capabilities.h
  233. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  234. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  235. #ifdef CATCH_CONFIG_COUNTER
  236. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  237. #else
  238. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  239. #endif
  240. #include <iosfwd>
  241. #include <string>
  242. #include <cstdint>
  243. namespace Catch {
  244. struct CaseSensitive { enum Choice {
  245. Yes,
  246. No
  247. }; };
  248. class NonCopyable {
  249. NonCopyable( NonCopyable const& ) = delete;
  250. NonCopyable( NonCopyable && ) = delete;
  251. NonCopyable& operator = ( NonCopyable const& ) = delete;
  252. NonCopyable& operator = ( NonCopyable && ) = delete;
  253. protected:
  254. NonCopyable();
  255. virtual ~NonCopyable();
  256. };
  257. struct SourceLineInfo {
  258. SourceLineInfo() = delete;
  259. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  260. : file( _file ),
  261. line( _line )
  262. {}
  263. SourceLineInfo( SourceLineInfo const& other ) = default;
  264. SourceLineInfo( SourceLineInfo && ) = default;
  265. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  266. SourceLineInfo& operator = ( SourceLineInfo && ) = default;
  267. bool empty() const noexcept;
  268. bool operator == ( SourceLineInfo const& other ) const noexcept;
  269. bool operator < ( SourceLineInfo const& other ) const noexcept;
  270. char const* file;
  271. std::size_t line;
  272. };
  273. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  274. // Use this in variadic streaming macros to allow
  275. // >> +StreamEndStop
  276. // as well as
  277. // >> stuff +StreamEndStop
  278. struct StreamEndStop {
  279. std::string operator+() const;
  280. };
  281. template<typename T>
  282. T const& operator + ( T const& value, StreamEndStop ) {
  283. return value;
  284. }
  285. }
  286. #define CATCH_INTERNAL_LINEINFO \
  287. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  288. // end catch_common.h
  289. namespace Catch {
  290. struct RegistrarForTagAliases {
  291. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  292. };
  293. } // end namespace Catch
  294. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  295. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  296. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  297. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  298. // end catch_tag_alias_autoregistrar.h
  299. // start catch_test_registry.h
  300. // start catch_interfaces_testcase.h
  301. #include <vector>
  302. #include <memory>
  303. namespace Catch {
  304. class TestSpec;
  305. struct ITestInvoker {
  306. virtual void invoke () const = 0;
  307. virtual ~ITestInvoker();
  308. };
  309. using ITestCasePtr = std::shared_ptr<ITestInvoker>;
  310. class TestCase;
  311. struct IConfig;
  312. struct ITestCaseRegistry {
  313. virtual ~ITestCaseRegistry();
  314. virtual std::vector<TestCase> const& getAllTests() const = 0;
  315. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  316. };
  317. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  318. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  319. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  320. }
  321. // end catch_interfaces_testcase.h
  322. // start catch_stringref.h
  323. #include <cstddef>
  324. #include <string>
  325. #include <iosfwd>
  326. namespace Catch {
  327. class StringData;
  328. /// A non-owning string class (similar to the forthcoming std::string_view)
  329. /// Note that, because a StringRef may be a substring of another string,
  330. /// it may not be null terminated. c_str() must return a null terminated
  331. /// string, however, and so the StringRef will internally take ownership
  332. /// (taking a copy), if necessary. In theory this ownership is not externally
  333. /// visible - but it does mean (substring) StringRefs should not be shared between
  334. /// threads.
  335. class StringRef {
  336. public:
  337. using size_type = std::size_t;
  338. private:
  339. friend struct StringRefTestAccess;
  340. char const* m_start;
  341. size_type m_size;
  342. char* m_data = nullptr;
  343. void takeOwnership();
  344. static constexpr char const* const s_empty = "";
  345. public: // construction/ assignment
  346. StringRef() noexcept
  347. : StringRef( s_empty, 0 )
  348. {}
  349. StringRef( StringRef const& other ) noexcept
  350. : m_start( other.m_start ),
  351. m_size( other.m_size )
  352. {}
  353. StringRef( StringRef&& other ) noexcept
  354. : m_start( other.m_start ),
  355. m_size( other.m_size ),
  356. m_data( other.m_data )
  357. {
  358. other.m_data = nullptr;
  359. }
  360. StringRef( char const* rawChars ) noexcept;
  361. StringRef( char const* rawChars, size_type size ) noexcept
  362. : m_start( rawChars ),
  363. m_size( size )
  364. {}
  365. StringRef( std::string const& stdString ) noexcept
  366. : m_start( stdString.c_str() ),
  367. m_size( stdString.size() )
  368. {}
  369. ~StringRef() noexcept {
  370. delete[] m_data;
  371. }
  372. auto operator = ( StringRef const &other ) noexcept -> StringRef& {
  373. delete[] m_data;
  374. m_data = nullptr;
  375. m_start = other.m_start;
  376. m_size = other.m_size;
  377. return *this;
  378. }
  379. operator std::string() const;
  380. void swap( StringRef& other ) noexcept;
  381. public: // operators
  382. auto operator == ( StringRef const& other ) const noexcept -> bool;
  383. auto operator != ( StringRef const& other ) const noexcept -> bool;
  384. auto operator[] ( size_type index ) const noexcept -> char;
  385. public: // named queries
  386. auto empty() const noexcept -> bool {
  387. return m_size == 0;
  388. }
  389. auto size() const noexcept -> size_type {
  390. return m_size;
  391. }
  392. auto numberOfCharacters() const noexcept -> size_type;
  393. auto c_str() const -> char const*;
  394. public: // substrings and searches
  395. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  396. // Returns the current start pointer.
  397. // Note that the pointer can change when if the StringRef is a substring
  398. auto currentData() const noexcept -> char const*;
  399. private: // ownership queries - may not be consistent between calls
  400. auto isOwned() const noexcept -> bool;
  401. auto isSubstring() const noexcept -> bool;
  402. };
  403. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  404. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  405. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  406. auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
  407. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  408. inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  409. return StringRef( rawChars, size );
  410. }
  411. } // namespace Catch
  412. // end catch_stringref.h
  413. namespace Catch {
  414. template<typename C>
  415. class TestInvokerAsMethod : public ITestInvoker {
  416. void (C::*m_testAsMethod)();
  417. public:
  418. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  419. void invoke() const override {
  420. C obj;
  421. (obj.*m_testAsMethod)();
  422. }
  423. };
  424. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  425. template<typename C>
  426. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  427. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  428. }
  429. struct NameAndTags {
  430. NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
  431. StringRef name;
  432. StringRef tags;
  433. };
  434. struct AutoReg : NonCopyable {
  435. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  436. ~AutoReg();
  437. };
  438. } // end namespace Catch
  439. #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
  440. #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
  441. #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
  442. #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  443. #if defined(CATCH_CONFIG_DISABLE)
  444. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  445. static void TestName()
  446. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  447. namespace{ \
  448. struct TestName : INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF ClassName) { \
  449. void test(); \
  450. }; \
  451. } \
  452. void TestName::test()
  453. #endif
  454. ///////////////////////////////////////////////////////////////////////////////
  455. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  456. static void TestName(); \
  457. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  458. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  459. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  460. static void TestName()
  461. #define INTERNAL_CATCH_TESTCASE( ... ) \
  462. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  463. ///////////////////////////////////////////////////////////////////////////////
  464. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  465. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  466. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  467. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  468. ///////////////////////////////////////////////////////////////////////////////
  469. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  470. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  471. namespace{ \
  472. struct TestName : INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF ClassName) { \
  473. void test(); \
  474. }; \
  475. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  476. } \
  477. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  478. void TestName::test()
  479. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  480. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  481. ///////////////////////////////////////////////////////////////////////////////
  482. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  483. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  484. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  485. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  486. // end catch_test_registry.h
  487. // start catch_capture.hpp
  488. // start catch_assertionhandler.h
  489. // start catch_assertioninfo.h
  490. // start catch_result_type.h
  491. namespace Catch {
  492. // ResultWas::OfType enum
  493. struct ResultWas { enum OfType {
  494. Unknown = -1,
  495. Ok = 0,
  496. Info = 1,
  497. Warning = 2,
  498. FailureBit = 0x10,
  499. ExpressionFailed = FailureBit | 1,
  500. ExplicitFailure = FailureBit | 2,
  501. Exception = 0x100 | FailureBit,
  502. ThrewException = Exception | 1,
  503. DidntThrowException = Exception | 2,
  504. FatalErrorCondition = 0x200 | FailureBit
  505. }; };
  506. bool isOk( ResultWas::OfType resultType );
  507. bool isJustInfo( int flags );
  508. // ResultDisposition::Flags enum
  509. struct ResultDisposition { enum Flags {
  510. Normal = 0x01,
  511. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  512. FalseTest = 0x04, // Prefix expression with !
  513. SuppressFail = 0x08 // Failures are reported but do not fail the test
  514. }; };
  515. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  516. bool shouldContinueOnFailure( int flags );
  517. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  518. bool shouldSuppressFailure( int flags );
  519. } // end namespace Catch
  520. // end catch_result_type.h
  521. namespace Catch {
  522. struct AssertionInfo
  523. {
  524. StringRef macroName;
  525. SourceLineInfo lineInfo;
  526. StringRef capturedExpression;
  527. ResultDisposition::Flags resultDisposition;
  528. // We want to delete this constructor but a compiler bug in 4.8 means
  529. // the struct is then treated as non-aggregate
  530. //AssertionInfo() = delete;
  531. };
  532. } // end namespace Catch
  533. // end catch_assertioninfo.h
  534. // start catch_decomposer.h
  535. // start catch_tostring.h
  536. #include <vector>
  537. #include <cstddef>
  538. #include <type_traits>
  539. #include <string>
  540. // start catch_stream.h
  541. #include <iosfwd>
  542. #include <cstddef>
  543. #include <ostream>
  544. namespace Catch {
  545. std::ostream& cout();
  546. std::ostream& cerr();
  547. std::ostream& clog();
  548. class StringRef;
  549. struct IStream {
  550. virtual ~IStream();
  551. virtual std::ostream& stream() const = 0;
  552. };
  553. auto makeStream( StringRef const &filename ) -> IStream const*;
  554. class ReusableStringStream {
  555. std::size_t m_index;
  556. std::ostream* m_oss;
  557. public:
  558. ReusableStringStream();
  559. ~ReusableStringStream();
  560. auto str() const -> std::string;
  561. template<typename T>
  562. auto operator << ( T const& value ) -> ReusableStringStream& {
  563. *m_oss << value;
  564. return *this;
  565. }
  566. auto get() -> std::ostream& { return *m_oss; }
  567. static void cleanup();
  568. };
  569. }
  570. // end catch_stream.h
  571. #ifdef __OBJC__
  572. // start catch_objc_arc.hpp
  573. #import <Foundation/Foundation.h>
  574. #ifdef __has_feature
  575. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  576. #else
  577. #define CATCH_ARC_ENABLED 0
  578. #endif
  579. void arcSafeRelease( NSObject* obj );
  580. id performOptionalSelector( id obj, SEL sel );
  581. #if !CATCH_ARC_ENABLED
  582. inline void arcSafeRelease( NSObject* obj ) {
  583. [obj release];
  584. }
  585. inline id performOptionalSelector( id obj, SEL sel ) {
  586. if( [obj respondsToSelector: sel] )
  587. return [obj performSelector: sel];
  588. return nil;
  589. }
  590. #define CATCH_UNSAFE_UNRETAINED
  591. #define CATCH_ARC_STRONG
  592. #else
  593. inline void arcSafeRelease( NSObject* ){}
  594. inline id performOptionalSelector( id obj, SEL sel ) {
  595. #ifdef __clang__
  596. #pragma clang diagnostic push
  597. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  598. #endif
  599. if( [obj respondsToSelector: sel] )
  600. return [obj performSelector: sel];
  601. #ifdef __clang__
  602. #pragma clang diagnostic pop
  603. #endif
  604. return nil;
  605. }
  606. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  607. #define CATCH_ARC_STRONG __strong
  608. #endif
  609. // end catch_objc_arc.hpp
  610. #endif
  611. #ifdef _MSC_VER
  612. #pragma warning(push)
  613. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  614. #endif
  615. // We need a dummy global operator<< so we can bring it into Catch namespace later
  616. struct Catch_global_namespace_dummy {};
  617. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  618. namespace Catch {
  619. // Bring in operator<< from global namespace into Catch namespace
  620. using ::operator<<;
  621. namespace Detail {
  622. extern const std::string unprintableString;
  623. std::string rawMemoryToString( const void *object, std::size_t size );
  624. template<typename T>
  625. std::string rawMemoryToString( const T& object ) {
  626. return rawMemoryToString( &object, sizeof(object) );
  627. }
  628. template<typename T>
  629. class IsStreamInsertable {
  630. template<typename SS, typename TT>
  631. static auto test(int)
  632. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  633. template<typename, typename>
  634. static auto test(...)->std::false_type;
  635. public:
  636. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  637. };
  638. template<typename E>
  639. std::string convertUnknownEnumToString( E e );
  640. template<typename T>
  641. typename std::enable_if<
  642. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  643. std::string>::type convertUnstreamable( T const& ) {
  644. return Detail::unprintableString;
  645. }
  646. template<typename T>
  647. typename std::enable_if<
  648. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  649. std::string>::type convertUnstreamable(T const& ex) {
  650. return ex.what();
  651. }
  652. template<typename T>
  653. typename std::enable_if<
  654. std::is_enum<T>::value
  655. , std::string>::type convertUnstreamable( T const& value ) {
  656. return convertUnknownEnumToString( value );
  657. }
  658. #if defined(_MANAGED)
  659. //! Convert a CLR string to a utf8 std::string
  660. template<typename T>
  661. std::string clrReferenceToString( T^ ref ) {
  662. if (ref == nullptr)
  663. return std::string("null");
  664. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  665. cli::pin_ptr<System::Byte> p = &bytes[0];
  666. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  667. }
  668. #endif
  669. } // namespace Detail
  670. // If we decide for C++14, change these to enable_if_ts
  671. template <typename T, typename = void>
  672. struct StringMaker {
  673. template <typename Fake = T>
  674. static
  675. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  676. convert(const Fake& value) {
  677. ReusableStringStream rss;
  678. // NB: call using the function-like syntax to avoid ambiguity with
  679. // user-defined templated operator<< under clang.
  680. rss.operator<<(value);
  681. return rss.str();
  682. }
  683. template <typename Fake = T>
  684. static
  685. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  686. convert( const Fake& value ) {
  687. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  688. return Detail::convertUnstreamable(value);
  689. #else
  690. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  691. #endif
  692. }
  693. };
  694. namespace Detail {
  695. // This function dispatches all stringification requests inside of Catch.
  696. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  697. template <typename T>
  698. std::string stringify(const T& e) {
  699. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  700. }
  701. template<typename E>
  702. std::string convertUnknownEnumToString( E e ) {
  703. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  704. }
  705. #if defined(_MANAGED)
  706. template <typename T>
  707. std::string stringify( T^ e ) {
  708. return ::Catch::StringMaker<T^>::convert(e);
  709. }
  710. #endif
  711. } // namespace Detail
  712. // Some predefined specializations
  713. template<>
  714. struct StringMaker<std::string> {
  715. static std::string convert(const std::string& str);
  716. };
  717. #ifdef CATCH_CONFIG_WCHAR
  718. template<>
  719. struct StringMaker<std::wstring> {
  720. static std::string convert(const std::wstring& wstr);
  721. };
  722. #endif
  723. template<>
  724. struct StringMaker<char const *> {
  725. static std::string convert(char const * str);
  726. };
  727. template<>
  728. struct StringMaker<char *> {
  729. static std::string convert(char * str);
  730. };
  731. #ifdef CATCH_CONFIG_WCHAR
  732. template<>
  733. struct StringMaker<wchar_t const *> {
  734. static std::string convert(wchar_t const * str);
  735. };
  736. template<>
  737. struct StringMaker<wchar_t *> {
  738. static std::string convert(wchar_t * str);
  739. };
  740. #endif
  741. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  742. // while keeping string semantics?
  743. template<int SZ>
  744. struct StringMaker<char[SZ]> {
  745. static std::string convert(char const* str) {
  746. return ::Catch::Detail::stringify(std::string{ str });
  747. }
  748. };
  749. template<int SZ>
  750. struct StringMaker<signed char[SZ]> {
  751. static std::string convert(signed char const* str) {
  752. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  753. }
  754. };
  755. template<int SZ>
  756. struct StringMaker<unsigned char[SZ]> {
  757. static std::string convert(unsigned char const* str) {
  758. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  759. }
  760. };
  761. template<>
  762. struct StringMaker<int> {
  763. static std::string convert(int value);
  764. };
  765. template<>
  766. struct StringMaker<long> {
  767. static std::string convert(long value);
  768. };
  769. template<>
  770. struct StringMaker<long long> {
  771. static std::string convert(long long value);
  772. };
  773. template<>
  774. struct StringMaker<unsigned int> {
  775. static std::string convert(unsigned int value);
  776. };
  777. template<>
  778. struct StringMaker<unsigned long> {
  779. static std::string convert(unsigned long value);
  780. };
  781. template<>
  782. struct StringMaker<unsigned long long> {
  783. static std::string convert(unsigned long long value);
  784. };
  785. template<>
  786. struct StringMaker<bool> {
  787. static std::string convert(bool b);
  788. };
  789. template<>
  790. struct StringMaker<char> {
  791. static std::string convert(char c);
  792. };
  793. template<>
  794. struct StringMaker<signed char> {
  795. static std::string convert(signed char c);
  796. };
  797. template<>
  798. struct StringMaker<unsigned char> {
  799. static std::string convert(unsigned char c);
  800. };
  801. template<>
  802. struct StringMaker<std::nullptr_t> {
  803. static std::string convert(std::nullptr_t);
  804. };
  805. template<>
  806. struct StringMaker<float> {
  807. static std::string convert(float value);
  808. };
  809. template<>
  810. struct StringMaker<double> {
  811. static std::string convert(double value);
  812. };
  813. template <typename T>
  814. struct StringMaker<T*> {
  815. template <typename U>
  816. static std::string convert(U* p) {
  817. if (p) {
  818. return ::Catch::Detail::rawMemoryToString(p);
  819. } else {
  820. return "nullptr";
  821. }
  822. }
  823. };
  824. template <typename R, typename C>
  825. struct StringMaker<R C::*> {
  826. static std::string convert(R C::* p) {
  827. if (p) {
  828. return ::Catch::Detail::rawMemoryToString(p);
  829. } else {
  830. return "nullptr";
  831. }
  832. }
  833. };
  834. #if defined(_MANAGED)
  835. template <typename T>
  836. struct StringMaker<T^> {
  837. static std::string convert( T^ ref ) {
  838. return ::Catch::Detail::clrReferenceToString(ref);
  839. }
  840. };
  841. #endif
  842. namespace Detail {
  843. template<typename InputIterator>
  844. std::string rangeToString(InputIterator first, InputIterator last) {
  845. ReusableStringStream rss;
  846. rss << "{ ";
  847. if (first != last) {
  848. rss << ::Catch::Detail::stringify(*first);
  849. for (++first; first != last; ++first)
  850. rss << ", " << ::Catch::Detail::stringify(*first);
  851. }
  852. rss << " }";
  853. return rss.str();
  854. }
  855. }
  856. #ifdef __OBJC__
  857. template<>
  858. struct StringMaker<NSString*> {
  859. static std::string convert(NSString * nsstring) {
  860. if (!nsstring)
  861. return "nil";
  862. return std::string("@") + [nsstring UTF8String];
  863. }
  864. };
  865. template<>
  866. struct StringMaker<NSObject*> {
  867. static std::string convert(NSObject* nsObject) {
  868. return ::Catch::Detail::stringify([nsObject description]);
  869. }
  870. };
  871. namespace Detail {
  872. inline std::string stringify( NSString* nsstring ) {
  873. return StringMaker<NSString*>::convert( nsstring );
  874. }
  875. } // namespace Detail
  876. #endif // __OBJC__
  877. } // namespace Catch
  878. //////////////////////////////////////////////////////
  879. // Separate std-lib types stringification, so it can be selectively enabled
  880. // This means that we do not bring in
  881. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  882. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  883. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  884. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  885. #endif
  886. // Separate std::pair specialization
  887. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  888. #include <utility>
  889. namespace Catch {
  890. template<typename T1, typename T2>
  891. struct StringMaker<std::pair<T1, T2> > {
  892. static std::string convert(const std::pair<T1, T2>& pair) {
  893. ReusableStringStream rss;
  894. rss << "{ "
  895. << ::Catch::Detail::stringify(pair.first)
  896. << ", "
  897. << ::Catch::Detail::stringify(pair.second)
  898. << " }";
  899. return rss.str();
  900. }
  901. };
  902. }
  903. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  904. // Separate std::tuple specialization
  905. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  906. #include <tuple>
  907. namespace Catch {
  908. namespace Detail {
  909. template<
  910. typename Tuple,
  911. std::size_t N = 0,
  912. bool = (N < std::tuple_size<Tuple>::value)
  913. >
  914. struct TupleElementPrinter {
  915. static void print(const Tuple& tuple, std::ostream& os) {
  916. os << (N ? ", " : " ")
  917. << ::Catch::Detail::stringify(std::get<N>(tuple));
  918. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  919. }
  920. };
  921. template<
  922. typename Tuple,
  923. std::size_t N
  924. >
  925. struct TupleElementPrinter<Tuple, N, false> {
  926. static void print(const Tuple&, std::ostream&) {}
  927. };
  928. }
  929. template<typename ...Types>
  930. struct StringMaker<std::tuple<Types...>> {
  931. static std::string convert(const std::tuple<Types...>& tuple) {
  932. ReusableStringStream rss;
  933. rss << '{';
  934. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  935. rss << " }";
  936. return rss.str();
  937. }
  938. };
  939. }
  940. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  941. namespace Catch {
  942. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  943. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  944. using std::begin;
  945. using std::end;
  946. not_this_one begin( ... );
  947. not_this_one end( ... );
  948. template <typename T>
  949. struct is_range {
  950. static const bool value =
  951. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  952. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  953. };
  954. #if defined(_MANAGED) // Managed types are never ranges
  955. template <typename T>
  956. struct is_range<T^> {
  957. static const bool value = false;
  958. };
  959. #endif
  960. template<typename Range>
  961. std::string rangeToString( Range const& range ) {
  962. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  963. }
  964. // Handle vector<bool> specially
  965. template<typename Allocator>
  966. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  967. ReusableStringStream rss;
  968. rss << "{ ";
  969. bool first = true;
  970. for( bool b : v ) {
  971. if( first )
  972. first = false;
  973. else
  974. rss << ", ";
  975. rss << ::Catch::Detail::stringify( b );
  976. }
  977. rss << " }";
  978. return rss.str();
  979. }
  980. template<typename R>
  981. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  982. static std::string convert( R const& range ) {
  983. return rangeToString( range );
  984. }
  985. };
  986. template <typename T, int SZ>
  987. struct StringMaker<T[SZ]> {
  988. static std::string convert(T const(&arr)[SZ]) {
  989. return rangeToString(arr);
  990. }
  991. };
  992. } // namespace Catch
  993. // Separate std::chrono::duration specialization
  994. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  995. #include <ctime>
  996. #include <ratio>
  997. #include <chrono>
  998. namespace Catch {
  999. template <class Ratio>
  1000. struct ratio_string {
  1001. static std::string symbol();
  1002. };
  1003. template <class Ratio>
  1004. std::string ratio_string<Ratio>::symbol() {
  1005. Catch::ReusableStringStream rss;
  1006. rss << '[' << Ratio::num << '/'
  1007. << Ratio::den << ']';
  1008. return rss.str();
  1009. }
  1010. template <>
  1011. struct ratio_string<std::atto> {
  1012. static std::string symbol();
  1013. };
  1014. template <>
  1015. struct ratio_string<std::femto> {
  1016. static std::string symbol();
  1017. };
  1018. template <>
  1019. struct ratio_string<std::pico> {
  1020. static std::string symbol();
  1021. };
  1022. template <>
  1023. struct ratio_string<std::nano> {
  1024. static std::string symbol();
  1025. };
  1026. template <>
  1027. struct ratio_string<std::micro> {
  1028. static std::string symbol();
  1029. };
  1030. template <>
  1031. struct ratio_string<std::milli> {
  1032. static std::string symbol();
  1033. };
  1034. ////////////
  1035. // std::chrono::duration specializations
  1036. template<typename Value, typename Ratio>
  1037. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  1038. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  1039. ReusableStringStream rss;
  1040. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  1041. return rss.str();
  1042. }
  1043. };
  1044. template<typename Value>
  1045. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  1046. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  1047. ReusableStringStream rss;
  1048. rss << duration.count() << " s";
  1049. return rss.str();
  1050. }
  1051. };
  1052. template<typename Value>
  1053. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1054. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1055. ReusableStringStream rss;
  1056. rss << duration.count() << " m";
  1057. return rss.str();
  1058. }
  1059. };
  1060. template<typename Value>
  1061. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1062. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1063. ReusableStringStream rss;
  1064. rss << duration.count() << " h";
  1065. return rss.str();
  1066. }
  1067. };
  1068. ////////////
  1069. // std::chrono::time_point specialization
  1070. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1071. template<typename Clock, typename Duration>
  1072. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1073. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1074. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1075. }
  1076. };
  1077. // std::chrono::time_point<system_clock> specialization
  1078. template<typename Duration>
  1079. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1080. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1081. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1082. #ifdef _MSC_VER
  1083. std::tm timeInfo = {};
  1084. gmtime_s(&timeInfo, &converted);
  1085. #else
  1086. std::tm* timeInfo = std::gmtime(&converted);
  1087. #endif
  1088. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1089. char timeStamp[timeStampSize];
  1090. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1091. #ifdef _MSC_VER
  1092. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1093. #else
  1094. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1095. #endif
  1096. return std::string(timeStamp);
  1097. }
  1098. };
  1099. }
  1100. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1101. #ifdef _MSC_VER
  1102. #pragma warning(pop)
  1103. #endif
  1104. // end catch_tostring.h
  1105. #include <iosfwd>
  1106. #ifdef _MSC_VER
  1107. #pragma warning(push)
  1108. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1109. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1110. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1111. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1112. #endif
  1113. namespace Catch {
  1114. struct ITransientExpression {
  1115. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1116. auto getResult() const -> bool { return m_result; }
  1117. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1118. ITransientExpression( bool isBinaryExpression, bool result )
  1119. : m_isBinaryExpression( isBinaryExpression ),
  1120. m_result( result )
  1121. {}
  1122. // We don't actually need a virtual destructor, but many static analysers
  1123. // complain if it's not here :-(
  1124. virtual ~ITransientExpression();
  1125. bool m_isBinaryExpression;
  1126. bool m_result;
  1127. };
  1128. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1129. template<typename LhsT, typename RhsT>
  1130. class BinaryExpr : public ITransientExpression {
  1131. LhsT m_lhs;
  1132. StringRef m_op;
  1133. RhsT m_rhs;
  1134. void streamReconstructedExpression( std::ostream &os ) const override {
  1135. formatReconstructedExpression
  1136. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1137. }
  1138. public:
  1139. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1140. : ITransientExpression{ true, comparisonResult },
  1141. m_lhs( lhs ),
  1142. m_op( op ),
  1143. m_rhs( rhs )
  1144. {}
  1145. };
  1146. template<typename LhsT>
  1147. class UnaryExpr : public ITransientExpression {
  1148. LhsT m_lhs;
  1149. void streamReconstructedExpression( std::ostream &os ) const override {
  1150. os << Catch::Detail::stringify( m_lhs );
  1151. }
  1152. public:
  1153. explicit UnaryExpr( LhsT lhs )
  1154. : ITransientExpression{ false, lhs ? true : false },
  1155. m_lhs( lhs )
  1156. {}
  1157. };
  1158. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1159. template<typename LhsT, typename RhsT>
  1160. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1161. template<typename T>
  1162. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1163. template<typename T>
  1164. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1165. template<typename T>
  1166. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1167. template<typename T>
  1168. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1169. template<typename LhsT, typename RhsT>
  1170. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1171. template<typename T>
  1172. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1173. template<typename T>
  1174. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1175. template<typename T>
  1176. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1177. template<typename T>
  1178. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1179. template<typename LhsT>
  1180. class ExprLhs {
  1181. LhsT m_lhs;
  1182. public:
  1183. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1184. template<typename RhsT>
  1185. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1186. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1187. }
  1188. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1189. return { m_lhs == rhs, m_lhs, "==", rhs };
  1190. }
  1191. template<typename RhsT>
  1192. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1193. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1194. }
  1195. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1196. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1197. }
  1198. template<typename RhsT>
  1199. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1200. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1201. }
  1202. template<typename RhsT>
  1203. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1204. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  1205. }
  1206. template<typename RhsT>
  1207. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1208. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  1209. }
  1210. template<typename RhsT>
  1211. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1212. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  1213. }
  1214. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  1215. return UnaryExpr<LhsT>{ m_lhs };
  1216. }
  1217. };
  1218. void handleExpression( ITransientExpression const& expr );
  1219. template<typename T>
  1220. void handleExpression( ExprLhs<T> const& expr ) {
  1221. handleExpression( expr.makeUnaryExpr() );
  1222. }
  1223. struct Decomposer {
  1224. template<typename T>
  1225. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  1226. return ExprLhs<T const&>{ lhs };
  1227. }
  1228. auto operator <=( bool value ) -> ExprLhs<bool> {
  1229. return ExprLhs<bool>{ value };
  1230. }
  1231. };
  1232. } // end namespace Catch
  1233. #ifdef _MSC_VER
  1234. #pragma warning(pop)
  1235. #endif
  1236. // end catch_decomposer.h
  1237. // start catch_interfaces_capture.h
  1238. #include <string>
  1239. namespace Catch {
  1240. class AssertionResult;
  1241. struct AssertionInfo;
  1242. struct SectionInfo;
  1243. struct SectionEndInfo;
  1244. struct MessageInfo;
  1245. struct Counts;
  1246. struct BenchmarkInfo;
  1247. struct BenchmarkStats;
  1248. struct AssertionReaction;
  1249. struct ITransientExpression;
  1250. struct IResultCapture {
  1251. virtual ~IResultCapture();
  1252. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  1253. Counts& assertions ) = 0;
  1254. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  1255. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  1256. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  1257. virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;
  1258. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  1259. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  1260. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  1261. virtual void handleExpr
  1262. ( AssertionInfo const& info,
  1263. ITransientExpression const& expr,
  1264. AssertionReaction& reaction ) = 0;
  1265. virtual void handleMessage
  1266. ( AssertionInfo const& info,
  1267. ResultWas::OfType resultType,
  1268. StringRef const& message,
  1269. AssertionReaction& reaction ) = 0;
  1270. virtual void handleUnexpectedExceptionNotThrown
  1271. ( AssertionInfo const& info,
  1272. AssertionReaction& reaction ) = 0;
  1273. virtual void handleUnexpectedInflightException
  1274. ( AssertionInfo const& info,
  1275. std::string const& message,
  1276. AssertionReaction& reaction ) = 0;
  1277. virtual void handleIncomplete
  1278. ( AssertionInfo const& info ) = 0;
  1279. virtual void handleNonExpr
  1280. ( AssertionInfo const &info,
  1281. ResultWas::OfType resultType,
  1282. AssertionReaction &reaction ) = 0;
  1283. virtual bool lastAssertionPassed() = 0;
  1284. virtual void assertionPassed() = 0;
  1285. // Deprecated, do not use:
  1286. virtual std::string getCurrentTestName() const = 0;
  1287. virtual const AssertionResult* getLastResult() const = 0;
  1288. virtual void exceptionEarlyReported() = 0;
  1289. };
  1290. IResultCapture& getResultCapture();
  1291. }
  1292. // end catch_interfaces_capture.h
  1293. namespace Catch {
  1294. struct TestFailureException{};
  1295. struct AssertionResultData;
  1296. struct IResultCapture;
  1297. class RunContext;
  1298. class LazyExpression {
  1299. friend class AssertionHandler;
  1300. friend struct AssertionStats;
  1301. friend class RunContext;
  1302. ITransientExpression const* m_transientExpression = nullptr;
  1303. bool m_isNegated;
  1304. public:
  1305. LazyExpression( bool isNegated );
  1306. LazyExpression( LazyExpression const& other );
  1307. LazyExpression& operator = ( LazyExpression const& ) = delete;
  1308. explicit operator bool() const;
  1309. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  1310. };
  1311. struct AssertionReaction {
  1312. bool shouldDebugBreak = false;
  1313. bool shouldThrow = false;
  1314. };
  1315. class AssertionHandler {
  1316. AssertionInfo m_assertionInfo;
  1317. AssertionReaction m_reaction;
  1318. bool m_completed = false;
  1319. IResultCapture& m_resultCapture;
  1320. public:
  1321. AssertionHandler
  1322. ( StringRef macroName,
  1323. SourceLineInfo const& lineInfo,
  1324. StringRef capturedExpression,
  1325. ResultDisposition::Flags resultDisposition );
  1326. ~AssertionHandler() {
  1327. if ( !m_completed ) {
  1328. m_resultCapture.handleIncomplete( m_assertionInfo );
  1329. }
  1330. }
  1331. template<typename T>
  1332. void handleExpr( ExprLhs<T> const& expr ) {
  1333. handleExpr( expr.makeUnaryExpr() );
  1334. }
  1335. void handleExpr( ITransientExpression const& expr );
  1336. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  1337. void handleExceptionThrownAsExpected();
  1338. void handleUnexpectedExceptionNotThrown();
  1339. void handleExceptionNotThrownAsExpected();
  1340. void handleThrowingCallSkipped();
  1341. void handleUnexpectedInflightException();
  1342. void complete();
  1343. void setCompleted();
  1344. // query
  1345. auto allowThrows() const -> bool;
  1346. };
  1347. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString );
  1348. } // namespace Catch
  1349. // end catch_assertionhandler.h
  1350. // start catch_message.h
  1351. #include <string>
  1352. namespace Catch {
  1353. struct MessageInfo {
  1354. MessageInfo( std::string const& _macroName,
  1355. SourceLineInfo const& _lineInfo,
  1356. ResultWas::OfType _type );
  1357. std::string macroName;
  1358. std::string message;
  1359. SourceLineInfo lineInfo;
  1360. ResultWas::OfType type;
  1361. unsigned int sequence;
  1362. bool operator == ( MessageInfo const& other ) const;
  1363. bool operator < ( MessageInfo const& other ) const;
  1364. private:
  1365. static unsigned int globalCount;
  1366. };
  1367. struct MessageStream {
  1368. template<typename T>
  1369. MessageStream& operator << ( T const& value ) {
  1370. m_stream << value;
  1371. return *this;
  1372. }
  1373. ReusableStringStream m_stream;
  1374. };
  1375. struct MessageBuilder : MessageStream {
  1376. MessageBuilder( std::string const& macroName,
  1377. SourceLineInfo const& lineInfo,
  1378. ResultWas::OfType type );
  1379. template<typename T>
  1380. MessageBuilder& operator << ( T const& value ) {
  1381. m_stream << value;
  1382. return *this;
  1383. }
  1384. MessageInfo m_info;
  1385. };
  1386. class ScopedMessage {
  1387. public:
  1388. explicit ScopedMessage( MessageBuilder const& builder );
  1389. ~ScopedMessage();
  1390. MessageInfo m_info;
  1391. };
  1392. } // end namespace Catch
  1393. // end catch_message.h
  1394. #if !defined(CATCH_CONFIG_DISABLE)
  1395. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  1396. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  1397. #else
  1398. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  1399. #endif
  1400. #if defined(CATCH_CONFIG_FAST_COMPILE)
  1401. ///////////////////////////////////////////////////////////////////////////////
  1402. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  1403. // macros.
  1404. #define INTERNAL_CATCH_TRY
  1405. #define INTERNAL_CATCH_CATCH( capturer )
  1406. #else // CATCH_CONFIG_FAST_COMPILE
  1407. #define INTERNAL_CATCH_TRY try
  1408. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  1409. #endif
  1410. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  1411. ///////////////////////////////////////////////////////////////////////////////
  1412. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  1413. do { \
  1414. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1415. INTERNAL_CATCH_TRY { \
  1416. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  1417. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  1418. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  1419. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1420. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1421. } 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
  1422. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  1423. ///////////////////////////////////////////////////////////////////////////////
  1424. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  1425. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1426. if( Catch::getResultCapture().lastAssertionPassed() )
  1427. ///////////////////////////////////////////////////////////////////////////////
  1428. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  1429. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1430. if( !Catch::getResultCapture().lastAssertionPassed() )
  1431. ///////////////////////////////////////////////////////////////////////////////
  1432. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  1433. do { \
  1434. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1435. try { \
  1436. static_cast<void>(__VA_ARGS__); \
  1437. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  1438. } \
  1439. catch( ... ) { \
  1440. catchAssertionHandler.handleUnexpectedInflightException(); \
  1441. } \
  1442. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1443. } while( false )
  1444. ///////////////////////////////////////////////////////////////////////////////
  1445. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  1446. do { \
  1447. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  1448. if( catchAssertionHandler.allowThrows() ) \
  1449. try { \
  1450. static_cast<void>(__VA_ARGS__); \
  1451. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1452. } \
  1453. catch( ... ) { \
  1454. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1455. } \
  1456. else \
  1457. catchAssertionHandler.handleThrowingCallSkipped(); \
  1458. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1459. } while( false )
  1460. ///////////////////////////////////////////////////////////////////////////////
  1461. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  1462. do { \
  1463. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  1464. if( catchAssertionHandler.allowThrows() ) \
  1465. try { \
  1466. static_cast<void>(expr); \
  1467. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1468. } \
  1469. catch( exceptionType const& ) { \
  1470. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1471. } \
  1472. catch( ... ) { \
  1473. catchAssertionHandler.handleUnexpectedInflightException(); \
  1474. } \
  1475. else \
  1476. catchAssertionHandler.handleThrowingCallSkipped(); \
  1477. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1478. } while( false )
  1479. ///////////////////////////////////////////////////////////////////////////////
  1480. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  1481. do { \
  1482. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
  1483. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  1484. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1485. } while( false )
  1486. ///////////////////////////////////////////////////////////////////////////////
  1487. #define INTERNAL_CATCH_INFO( macroName, log ) \
  1488. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  1489. ///////////////////////////////////////////////////////////////////////////////
  1490. // Although this is matcher-based, it can be used with just a string
  1491. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  1492. do { \
  1493. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1494. if( catchAssertionHandler.allowThrows() ) \
  1495. try { \
  1496. static_cast<void>(__VA_ARGS__); \
  1497. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1498. } \
  1499. catch( ... ) { \
  1500. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher ); \
  1501. } \
  1502. else \
  1503. catchAssertionHandler.handleThrowingCallSkipped(); \
  1504. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1505. } while( false )
  1506. #endif // CATCH_CONFIG_DISABLE
  1507. // end catch_capture.hpp
  1508. // start catch_section.h
  1509. // start catch_section_info.h
  1510. // start catch_totals.h
  1511. #include <cstddef>
  1512. namespace Catch {
  1513. struct Counts {
  1514. Counts operator - ( Counts const& other ) const;
  1515. Counts& operator += ( Counts const& other );
  1516. std::size_t total() const;
  1517. bool allPassed() const;
  1518. bool allOk() const;
  1519. std::size_t passed = 0;
  1520. std::size_t failed = 0;
  1521. std::size_t failedButOk = 0;
  1522. };
  1523. struct Totals {
  1524. Totals operator - ( Totals const& other ) const;
  1525. Totals& operator += ( Totals const& other );
  1526. Totals delta( Totals const& prevTotals ) const;
  1527. int error = 0;
  1528. Counts assertions;
  1529. Counts testCases;
  1530. };
  1531. }
  1532. // end catch_totals.h
  1533. #include <string>
  1534. namespace Catch {
  1535. struct SectionInfo {
  1536. SectionInfo
  1537. ( SourceLineInfo const& _lineInfo,
  1538. std::string const& _name );
  1539. // Deprecated
  1540. SectionInfo
  1541. ( SourceLineInfo const& _lineInfo,
  1542. std::string const& _name,
  1543. std::string const& ) : SectionInfo( _lineInfo, _name ) {}
  1544. std::string name;
  1545. std::string description; // !Deprecated: this will always be empty
  1546. SourceLineInfo lineInfo;
  1547. };
  1548. struct SectionEndInfo {
  1549. SectionInfo sectionInfo;
  1550. Counts prevAssertions;
  1551. double durationInSeconds;
  1552. };
  1553. } // end namespace Catch
  1554. // end catch_section_info.h
  1555. // start catch_timer.h
  1556. #include <cstdint>
  1557. namespace Catch {
  1558. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  1559. auto getEstimatedClockResolution() -> uint64_t;
  1560. class Timer {
  1561. uint64_t m_nanoseconds = 0;
  1562. public:
  1563. void start();
  1564. auto getElapsedNanoseconds() const -> uint64_t;
  1565. auto getElapsedMicroseconds() const -> uint64_t;
  1566. auto getElapsedMilliseconds() const -> unsigned int;
  1567. auto getElapsedSeconds() const -> double;
  1568. };
  1569. } // namespace Catch
  1570. // end catch_timer.h
  1571. #include <string>
  1572. namespace Catch {
  1573. class Section : NonCopyable {
  1574. public:
  1575. Section( SectionInfo const& info );
  1576. ~Section();
  1577. // This indicates whether the section should be executed or not
  1578. explicit operator bool() const;
  1579. private:
  1580. SectionInfo m_info;
  1581. std::string m_name;
  1582. Counts m_assertions;
  1583. bool m_sectionIncluded;
  1584. Timer m_timer;
  1585. };
  1586. } // end namespace Catch
  1587. #define INTERNAL_CATCH_SECTION( ... ) \
  1588. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  1589. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
  1590. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  1591. #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
  1592. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  1593. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
  1594. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  1595. // end catch_section.h
  1596. // start catch_benchmark.h
  1597. #include <cstdint>
  1598. #include <string>
  1599. namespace Catch {
  1600. class BenchmarkLooper {
  1601. std::string m_name;
  1602. std::size_t m_count = 0;
  1603. std::size_t m_iterationsToRun = 1;
  1604. uint64_t m_resolution;
  1605. Timer m_timer;
  1606. static auto getResolution() -> uint64_t;
  1607. public:
  1608. // Keep most of this inline as it's on the code path that is being timed
  1609. BenchmarkLooper( StringRef name )
  1610. : m_name( name ),
  1611. m_resolution( getResolution() )
  1612. {
  1613. reportStart();
  1614. m_timer.start();
  1615. }
  1616. explicit operator bool() {
  1617. if( m_count < m_iterationsToRun )
  1618. return true;
  1619. return needsMoreIterations();
  1620. }
  1621. void increment() {
  1622. ++m_count;
  1623. }
  1624. void reportStart();
  1625. auto needsMoreIterations() -> bool;
  1626. };
  1627. } // end namespace Catch
  1628. #define BENCHMARK( name ) \
  1629. for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )
  1630. // end catch_benchmark.h
  1631. // start catch_interfaces_exception.h
  1632. // start catch_interfaces_registry_hub.h
  1633. #include <string>
  1634. #include <memory>
  1635. namespace Catch {
  1636. class TestCase;
  1637. struct ITestCaseRegistry;
  1638. struct IExceptionTranslatorRegistry;
  1639. struct IExceptionTranslator;
  1640. struct IReporterRegistry;
  1641. struct IReporterFactory;
  1642. struct ITagAliasRegistry;
  1643. class StartupExceptionRegistry;
  1644. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  1645. struct IRegistryHub {
  1646. virtual ~IRegistryHub();
  1647. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  1648. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  1649. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  1650. virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0;
  1651. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  1652. };
  1653. struct IMutableRegistryHub {
  1654. virtual ~IMutableRegistryHub();
  1655. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  1656. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  1657. virtual void registerTest( TestCase const& testInfo ) = 0;
  1658. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  1659. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  1660. virtual void registerStartupException() noexcept = 0;
  1661. };
  1662. IRegistryHub& getRegistryHub();
  1663. IMutableRegistryHub& getMutableRegistryHub();
  1664. void cleanUp();
  1665. std::string translateActiveException();
  1666. }
  1667. // end catch_interfaces_registry_hub.h
  1668. #if defined(CATCH_CONFIG_DISABLE)
  1669. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  1670. static std::string translatorName( signature )
  1671. #endif
  1672. #include <exception>
  1673. #include <string>
  1674. #include <vector>
  1675. namespace Catch {
  1676. using exceptionTranslateFunction = std::string(*)();
  1677. struct IExceptionTranslator;
  1678. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  1679. struct IExceptionTranslator {
  1680. virtual ~IExceptionTranslator();
  1681. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  1682. };
  1683. struct IExceptionTranslatorRegistry {
  1684. virtual ~IExceptionTranslatorRegistry();
  1685. virtual std::string translateActiveException() const = 0;
  1686. };
  1687. class ExceptionTranslatorRegistrar {
  1688. template<typename T>
  1689. class ExceptionTranslator : public IExceptionTranslator {
  1690. public:
  1691. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  1692. : m_translateFunction( translateFunction )
  1693. {}
  1694. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  1695. try {
  1696. if( it == itEnd )
  1697. std::rethrow_exception(std::current_exception());
  1698. else
  1699. return (*it)->translate( it+1, itEnd );
  1700. }
  1701. catch( T& ex ) {
  1702. return m_translateFunction( ex );
  1703. }
  1704. }
  1705. protected:
  1706. std::string(*m_translateFunction)( T& );
  1707. };
  1708. public:
  1709. template<typename T>
  1710. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  1711. getMutableRegistryHub().registerTranslator
  1712. ( new ExceptionTranslator<T>( translateFunction ) );
  1713. }
  1714. };
  1715. }
  1716. ///////////////////////////////////////////////////////////////////////////////
  1717. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  1718. static std::string translatorName( signature ); \
  1719. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1720. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  1721. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1722. static std::string translatorName( signature )
  1723. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  1724. // end catch_interfaces_exception.h
  1725. // start catch_approx.h
  1726. #include <type_traits>
  1727. #include <stdexcept>
  1728. namespace Catch {
  1729. namespace Detail {
  1730. class Approx {
  1731. private:
  1732. bool equalityComparisonImpl(double other) const;
  1733. public:
  1734. explicit Approx ( double value );
  1735. static Approx custom();
  1736. Approx operator-() const;
  1737. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1738. Approx operator()( T const& value ) {
  1739. Approx approx( static_cast<double>(value) );
  1740. approx.epsilon( m_epsilon );
  1741. approx.margin( m_margin );
  1742. approx.scale( m_scale );
  1743. return approx;
  1744. }
  1745. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1746. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  1747. {}
  1748. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1749. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  1750. auto lhs_v = static_cast<double>(lhs);
  1751. return rhs.equalityComparisonImpl(lhs_v);
  1752. }
  1753. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1754. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  1755. return operator==( rhs, lhs );
  1756. }
  1757. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1758. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  1759. return !operator==( lhs, rhs );
  1760. }
  1761. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1762. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  1763. return !operator==( rhs, lhs );
  1764. }
  1765. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1766. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  1767. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  1768. }
  1769. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1770. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  1771. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  1772. }
  1773. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1774. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  1775. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  1776. }
  1777. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1778. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  1779. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  1780. }
  1781. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1782. Approx& epsilon( T const& newEpsilon ) {
  1783. double epsilonAsDouble = static_cast<double>(newEpsilon);
  1784. if( epsilonAsDouble < 0 || epsilonAsDouble > 1.0 ) {
  1785. throw std::domain_error
  1786. ( "Invalid Approx::epsilon: " +
  1787. Catch::Detail::stringify( epsilonAsDouble ) +
  1788. ", Approx::epsilon has to be between 0 and 1" );
  1789. }
  1790. m_epsilon = epsilonAsDouble;
  1791. return *this;
  1792. }
  1793. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1794. Approx& margin( T const& newMargin ) {
  1795. double marginAsDouble = static_cast<double>(newMargin);
  1796. if( marginAsDouble < 0 ) {
  1797. throw std::domain_error
  1798. ( "Invalid Approx::margin: " +
  1799. Catch::Detail::stringify( marginAsDouble ) +
  1800. ", Approx::Margin has to be non-negative." );
  1801. }
  1802. m_margin = marginAsDouble;
  1803. return *this;
  1804. }
  1805. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1806. Approx& scale( T const& newScale ) {
  1807. m_scale = static_cast<double>(newScale);
  1808. return *this;
  1809. }
  1810. std::string toString() const;
  1811. private:
  1812. double m_epsilon;
  1813. double m_margin;
  1814. double m_scale;
  1815. double m_value;
  1816. };
  1817. } // end namespace Detail
  1818. namespace literals {
  1819. Detail::Approx operator "" _a(long double val);
  1820. Detail::Approx operator "" _a(unsigned long long val);
  1821. } // end namespace literals
  1822. template<>
  1823. struct StringMaker<Catch::Detail::Approx> {
  1824. static std::string convert(Catch::Detail::Approx const& value);
  1825. };
  1826. } // end namespace Catch
  1827. // end catch_approx.h
  1828. // start catch_string_manip.h
  1829. #include <string>
  1830. #include <iosfwd>
  1831. namespace Catch {
  1832. bool startsWith( std::string const& s, std::string const& prefix );
  1833. bool startsWith( std::string const& s, char prefix );
  1834. bool endsWith( std::string const& s, std::string const& suffix );
  1835. bool endsWith( std::string const& s, char suffix );
  1836. bool contains( std::string const& s, std::string const& infix );
  1837. void toLowerInPlace( std::string& s );
  1838. std::string toLower( std::string const& s );
  1839. std::string trim( std::string const& str );
  1840. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  1841. struct pluralise {
  1842. pluralise( std::size_t count, std::string const& label );
  1843. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  1844. std::size_t m_count;
  1845. std::string m_label;
  1846. };
  1847. }
  1848. // end catch_string_manip.h
  1849. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  1850. // start catch_capture_matchers.h
  1851. // start catch_matchers.h
  1852. #include <string>
  1853. #include <vector>
  1854. namespace Catch {
  1855. namespace Matchers {
  1856. namespace Impl {
  1857. template<typename ArgT> struct MatchAllOf;
  1858. template<typename ArgT> struct MatchAnyOf;
  1859. template<typename ArgT> struct MatchNotOf;
  1860. class MatcherUntypedBase {
  1861. public:
  1862. MatcherUntypedBase() = default;
  1863. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  1864. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  1865. std::string toString() const;
  1866. protected:
  1867. virtual ~MatcherUntypedBase();
  1868. virtual std::string describe() const = 0;
  1869. mutable std::string m_cachedToString;
  1870. };
  1871. template<typename ObjectT>
  1872. struct MatcherMethod {
  1873. virtual bool match( ObjectT const& arg ) const = 0;
  1874. };
  1875. template<typename PtrT>
  1876. struct MatcherMethod<PtrT*> {
  1877. virtual bool match( PtrT* arg ) const = 0;
  1878. };
  1879. template<typename T>
  1880. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  1881. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  1882. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  1883. MatchNotOf<T> operator ! () const;
  1884. };
  1885. template<typename ArgT>
  1886. struct MatchAllOf : MatcherBase<ArgT> {
  1887. bool match( ArgT const& arg ) const override {
  1888. for( auto matcher : m_matchers ) {
  1889. if (!matcher->match(arg))
  1890. return false;
  1891. }
  1892. return true;
  1893. }
  1894. std::string describe() const override {
  1895. std::string description;
  1896. description.reserve( 4 + m_matchers.size()*32 );
  1897. description += "( ";
  1898. bool first = true;
  1899. for( auto matcher : m_matchers ) {
  1900. if( first )
  1901. first = false;
  1902. else
  1903. description += " and ";
  1904. description += matcher->toString();
  1905. }
  1906. description += " )";
  1907. return description;
  1908. }
  1909. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  1910. m_matchers.push_back( &other );
  1911. return *this;
  1912. }
  1913. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1914. };
  1915. template<typename ArgT>
  1916. struct MatchAnyOf : MatcherBase<ArgT> {
  1917. bool match( ArgT const& arg ) const override {
  1918. for( auto matcher : m_matchers ) {
  1919. if (matcher->match(arg))
  1920. return true;
  1921. }
  1922. return false;
  1923. }
  1924. std::string describe() const override {
  1925. std::string description;
  1926. description.reserve( 4 + m_matchers.size()*32 );
  1927. description += "( ";
  1928. bool first = true;
  1929. for( auto matcher : m_matchers ) {
  1930. if( first )
  1931. first = false;
  1932. else
  1933. description += " or ";
  1934. description += matcher->toString();
  1935. }
  1936. description += " )";
  1937. return description;
  1938. }
  1939. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  1940. m_matchers.push_back( &other );
  1941. return *this;
  1942. }
  1943. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1944. };
  1945. template<typename ArgT>
  1946. struct MatchNotOf : MatcherBase<ArgT> {
  1947. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  1948. bool match( ArgT const& arg ) const override {
  1949. return !m_underlyingMatcher.match( arg );
  1950. }
  1951. std::string describe() const override {
  1952. return "not " + m_underlyingMatcher.toString();
  1953. }
  1954. MatcherBase<ArgT> const& m_underlyingMatcher;
  1955. };
  1956. template<typename T>
  1957. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  1958. return MatchAllOf<T>() && *this && other;
  1959. }
  1960. template<typename T>
  1961. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  1962. return MatchAnyOf<T>() || *this || other;
  1963. }
  1964. template<typename T>
  1965. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  1966. return MatchNotOf<T>( *this );
  1967. }
  1968. } // namespace Impl
  1969. } // namespace Matchers
  1970. using namespace Matchers;
  1971. using Matchers::Impl::MatcherBase;
  1972. } // namespace Catch
  1973. // end catch_matchers.h
  1974. // start catch_matchers_floating.h
  1975. #include <type_traits>
  1976. #include <cmath>
  1977. namespace Catch {
  1978. namespace Matchers {
  1979. namespace Floating {
  1980. enum class FloatingPointKind : uint8_t;
  1981. struct WithinAbsMatcher : MatcherBase<double> {
  1982. WithinAbsMatcher(double target, double margin);
  1983. bool match(double const& matchee) const override;
  1984. std::string describe() const override;
  1985. private:
  1986. double m_target;
  1987. double m_margin;
  1988. };
  1989. struct WithinUlpsMatcher : MatcherBase<double> {
  1990. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  1991. bool match(double const& matchee) const override;
  1992. std::string describe() const override;
  1993. private:
  1994. double m_target;
  1995. int m_ulps;
  1996. FloatingPointKind m_type;
  1997. };
  1998. } // namespace Floating
  1999. // The following functions create the actual matcher objects.
  2000. // This allows the types to be inferred
  2001. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  2002. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  2003. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  2004. } // namespace Matchers
  2005. } // namespace Catch
  2006. // end catch_matchers_floating.h
  2007. // start catch_matchers_generic.hpp
  2008. #include <functional>
  2009. #include <string>
  2010. namespace Catch {
  2011. namespace Matchers {
  2012. namespace Generic {
  2013. namespace Detail {
  2014. std::string finalizeDescription(const std::string& desc);
  2015. }
  2016. template <typename T>
  2017. class PredicateMatcher : public MatcherBase<T> {
  2018. std::function<bool(T const&)> m_predicate;
  2019. std::string m_description;
  2020. public:
  2021. PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
  2022. :m_predicate(std::move(elem)),
  2023. m_description(Detail::finalizeDescription(descr))
  2024. {}
  2025. bool match( T const& item ) const override {
  2026. return m_predicate(item);
  2027. }
  2028. std::string describe() const override {
  2029. return m_description;
  2030. }
  2031. };
  2032. } // namespace Generic
  2033. // The following functions create the actual matcher objects.
  2034. // The user has to explicitly specify type to the function, because
  2035. // infering std::function<bool(T const&)> is hard (but possible) and
  2036. // requires a lot of TMP.
  2037. template<typename T>
  2038. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
  2039. return Generic::PredicateMatcher<T>(predicate, description);
  2040. }
  2041. } // namespace Matchers
  2042. } // namespace Catch
  2043. // end catch_matchers_generic.hpp
  2044. // start catch_matchers_string.h
  2045. #include <string>
  2046. namespace Catch {
  2047. namespace Matchers {
  2048. namespace StdString {
  2049. struct CasedString
  2050. {
  2051. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  2052. std::string adjustString( std::string const& str ) const;
  2053. std::string caseSensitivitySuffix() const;
  2054. CaseSensitive::Choice m_caseSensitivity;
  2055. std::string m_str;
  2056. };
  2057. struct StringMatcherBase : MatcherBase<std::string> {
  2058. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  2059. std::string describe() const override;
  2060. CasedString m_comparator;
  2061. std::string m_operation;
  2062. };
  2063. struct EqualsMatcher : StringMatcherBase {
  2064. EqualsMatcher( CasedString const& comparator );
  2065. bool match( std::string const& source ) const override;
  2066. };
  2067. struct ContainsMatcher : StringMatcherBase {
  2068. ContainsMatcher( CasedString const& comparator );
  2069. bool match( std::string const& source ) const override;
  2070. };
  2071. struct StartsWithMatcher : StringMatcherBase {
  2072. StartsWithMatcher( CasedString const& comparator );
  2073. bool match( std::string const& source ) const override;
  2074. };
  2075. struct EndsWithMatcher : StringMatcherBase {
  2076. EndsWithMatcher( CasedString const& comparator );
  2077. bool match( std::string const& source ) const override;
  2078. };
  2079. struct RegexMatcher : MatcherBase<std::string> {
  2080. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  2081. bool match( std::string const& matchee ) const override;
  2082. std::string describe() const override;
  2083. private:
  2084. std::string m_regex;
  2085. CaseSensitive::Choice m_caseSensitivity;
  2086. };
  2087. } // namespace StdString
  2088. // The following functions create the actual matcher objects.
  2089. // This allows the types to be inferred
  2090. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2091. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2092. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2093. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2094. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2095. } // namespace Matchers
  2096. } // namespace Catch
  2097. // end catch_matchers_string.h
  2098. // start catch_matchers_vector.h
  2099. #include <algorithm>
  2100. namespace Catch {
  2101. namespace Matchers {
  2102. namespace Vector {
  2103. namespace Detail {
  2104. template <typename InputIterator, typename T>
  2105. size_t count(InputIterator first, InputIterator last, T const& item) {
  2106. size_t cnt = 0;
  2107. for (; first != last; ++first) {
  2108. if (*first == item) {
  2109. ++cnt;
  2110. }
  2111. }
  2112. return cnt;
  2113. }
  2114. template <typename InputIterator, typename T>
  2115. bool contains(InputIterator first, InputIterator last, T const& item) {
  2116. for (; first != last; ++first) {
  2117. if (*first == item) {
  2118. return true;
  2119. }
  2120. }
  2121. return false;
  2122. }
  2123. }
  2124. template<typename T>
  2125. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  2126. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  2127. bool match(std::vector<T> const &v) const override {
  2128. for (auto const& el : v) {
  2129. if (el == m_comparator) {
  2130. return true;
  2131. }
  2132. }
  2133. return false;
  2134. }
  2135. std::string describe() const override {
  2136. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2137. }
  2138. T const& m_comparator;
  2139. };
  2140. template<typename T>
  2141. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  2142. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2143. bool match(std::vector<T> const &v) const override {
  2144. // !TBD: see note in EqualsMatcher
  2145. if (m_comparator.size() > v.size())
  2146. return false;
  2147. for (auto const& comparator : m_comparator) {
  2148. auto present = false;
  2149. for (const auto& el : v) {
  2150. if (el == comparator) {
  2151. present = true;
  2152. break;
  2153. }
  2154. }
  2155. if (!present) {
  2156. return false;
  2157. }
  2158. }
  2159. return true;
  2160. }
  2161. std::string describe() const override {
  2162. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2163. }
  2164. std::vector<T> const& m_comparator;
  2165. };
  2166. template<typename T>
  2167. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  2168. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2169. bool match(std::vector<T> const &v) const override {
  2170. // !TBD: This currently works if all elements can be compared using !=
  2171. // - a more general approach would be via a compare template that defaults
  2172. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  2173. // - then just call that directly
  2174. if (m_comparator.size() != v.size())
  2175. return false;
  2176. for (std::size_t i = 0; i < v.size(); ++i)
  2177. if (m_comparator[i] != v[i])
  2178. return false;
  2179. return true;
  2180. }
  2181. std::string describe() const override {
  2182. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2183. }
  2184. std::vector<T> const& m_comparator;
  2185. };
  2186. template<typename T>
  2187. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2188. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2189. bool match(std::vector<T> const& vec) const override {
  2190. // Note: This is a reimplementation of std::is_permutation,
  2191. // because I don't want to include <algorithm> inside the common path
  2192. if (m_target.size() != vec.size()) {
  2193. return false;
  2194. }
  2195. auto lfirst = m_target.begin(), llast = m_target.end();
  2196. auto rfirst = vec.begin(), rlast = vec.end();
  2197. // Cut common prefix to optimize checking of permuted parts
  2198. while (lfirst != llast && *lfirst != *rfirst) {
  2199. ++lfirst; ++rfirst;
  2200. }
  2201. if (lfirst == llast) {
  2202. return true;
  2203. }
  2204. for (auto mid = lfirst; mid != llast; ++mid) {
  2205. // Skip already counted items
  2206. if (Detail::contains(lfirst, mid, *mid)) {
  2207. continue;
  2208. }
  2209. size_t num_vec = Detail::count(rfirst, rlast, *mid);
  2210. if (num_vec == 0 || Detail::count(lfirst, llast, *mid) != num_vec) {
  2211. return false;
  2212. }
  2213. }
  2214. return true;
  2215. }
  2216. std::string describe() const override {
  2217. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  2218. }
  2219. private:
  2220. std::vector<T> const& m_target;
  2221. };
  2222. } // namespace Vector
  2223. // The following functions create the actual matcher objects.
  2224. // This allows the types to be inferred
  2225. template<typename T>
  2226. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  2227. return Vector::ContainsMatcher<T>( comparator );
  2228. }
  2229. template<typename T>
  2230. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  2231. return Vector::ContainsElementMatcher<T>( comparator );
  2232. }
  2233. template<typename T>
  2234. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  2235. return Vector::EqualsMatcher<T>( comparator );
  2236. }
  2237. template<typename T>
  2238. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  2239. return Vector::UnorderedEqualsMatcher<T>(target);
  2240. }
  2241. } // namespace Matchers
  2242. } // namespace Catch
  2243. // end catch_matchers_vector.h
  2244. namespace Catch {
  2245. template<typename ArgT, typename MatcherT>
  2246. class MatchExpr : public ITransientExpression {
  2247. ArgT const& m_arg;
  2248. MatcherT m_matcher;
  2249. StringRef m_matcherString;
  2250. public:
  2251. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString )
  2252. : ITransientExpression{ true, matcher.match( arg ) },
  2253. m_arg( arg ),
  2254. m_matcher( matcher ),
  2255. m_matcherString( matcherString )
  2256. {}
  2257. void streamReconstructedExpression( std::ostream &os ) const override {
  2258. auto matcherAsString = m_matcher.toString();
  2259. os << Catch::Detail::stringify( m_arg ) << ' ';
  2260. if( matcherAsString == Detail::unprintableString )
  2261. os << m_matcherString;
  2262. else
  2263. os << matcherAsString;
  2264. }
  2265. };
  2266. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  2267. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString );
  2268. template<typename ArgT, typename MatcherT>
  2269. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef matcherString ) -> MatchExpr<ArgT, MatcherT> {
  2270. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  2271. }
  2272. } // namespace Catch
  2273. ///////////////////////////////////////////////////////////////////////////////
  2274. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  2275. do { \
  2276. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2277. INTERNAL_CATCH_TRY { \
  2278. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher ) ); \
  2279. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2280. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2281. } while( false )
  2282. ///////////////////////////////////////////////////////////////////////////////
  2283. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  2284. do { \
  2285. Catch::AssertionHandler catchAssertionHandler( macroName, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2286. if( catchAssertionHandler.allowThrows() ) \
  2287. try { \
  2288. static_cast<void>(__VA_ARGS__ ); \
  2289. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2290. } \
  2291. catch( exceptionType const& ex ) { \
  2292. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher ) ); \
  2293. } \
  2294. catch( ... ) { \
  2295. catchAssertionHandler.handleUnexpectedInflightException(); \
  2296. } \
  2297. else \
  2298. catchAssertionHandler.handleThrowingCallSkipped(); \
  2299. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2300. } while( false )
  2301. // end catch_capture_matchers.h
  2302. #endif
  2303. // These files are included here so the single_include script doesn't put them
  2304. // in the conditionally compiled sections
  2305. // start catch_test_case_info.h
  2306. #include <string>
  2307. #include <vector>
  2308. #include <memory>
  2309. #ifdef __clang__
  2310. #pragma clang diagnostic push
  2311. #pragma clang diagnostic ignored "-Wpadded"
  2312. #endif
  2313. namespace Catch {
  2314. struct ITestInvoker;
  2315. struct TestCaseInfo {
  2316. enum SpecialProperties{
  2317. None = 0,
  2318. IsHidden = 1 << 1,
  2319. ShouldFail = 1 << 2,
  2320. MayFail = 1 << 3,
  2321. Throws = 1 << 4,
  2322. NonPortable = 1 << 5,
  2323. Benchmark = 1 << 6
  2324. };
  2325. TestCaseInfo( std::string const& _name,
  2326. std::string const& _className,
  2327. std::string const& _description,
  2328. std::vector<std::string> const& _tags,
  2329. SourceLineInfo const& _lineInfo );
  2330. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  2331. bool isHidden() const;
  2332. bool throws() const;
  2333. bool okToFail() const;
  2334. bool expectedToFail() const;
  2335. std::string tagsAsString() const;
  2336. std::string name;
  2337. std::string className;
  2338. std::string description;
  2339. std::vector<std::string> tags;
  2340. std::vector<std::string> lcaseTags;
  2341. SourceLineInfo lineInfo;
  2342. SpecialProperties properties;
  2343. };
  2344. class TestCase : public TestCaseInfo {
  2345. public:
  2346. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  2347. TestCase withName( std::string const& _newName ) const;
  2348. void invoke() const;
  2349. TestCaseInfo const& getTestCaseInfo() const;
  2350. bool operator == ( TestCase const& other ) const;
  2351. bool operator < ( TestCase const& other ) const;
  2352. private:
  2353. std::shared_ptr<ITestInvoker> test;
  2354. };
  2355. TestCase makeTestCase( ITestInvoker* testCase,
  2356. std::string const& className,
  2357. NameAndTags const& nameAndTags,
  2358. SourceLineInfo const& lineInfo );
  2359. }
  2360. #ifdef __clang__
  2361. #pragma clang diagnostic pop
  2362. #endif
  2363. // end catch_test_case_info.h
  2364. // start catch_interfaces_runner.h
  2365. namespace Catch {
  2366. struct IRunner {
  2367. virtual ~IRunner();
  2368. virtual bool aborting() const = 0;
  2369. };
  2370. }
  2371. // end catch_interfaces_runner.h
  2372. #ifdef __OBJC__
  2373. // start catch_objc.hpp
  2374. #import <objc/runtime.h>
  2375. #include <string>
  2376. // NB. Any general catch headers included here must be included
  2377. // in catch.hpp first to make sure they are included by the single
  2378. // header for non obj-usage
  2379. ///////////////////////////////////////////////////////////////////////////////
  2380. // This protocol is really only here for (self) documenting purposes, since
  2381. // all its methods are optional.
  2382. @protocol OcFixture
  2383. @optional
  2384. -(void) setUp;
  2385. -(void) tearDown;
  2386. @end
  2387. namespace Catch {
  2388. class OcMethod : public ITestInvoker {
  2389. public:
  2390. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  2391. virtual void invoke() const {
  2392. id obj = [[m_cls alloc] init];
  2393. performOptionalSelector( obj, @selector(setUp) );
  2394. performOptionalSelector( obj, m_sel );
  2395. performOptionalSelector( obj, @selector(tearDown) );
  2396. arcSafeRelease( obj );
  2397. }
  2398. private:
  2399. virtual ~OcMethod() {}
  2400. Class m_cls;
  2401. SEL m_sel;
  2402. };
  2403. namespace Detail{
  2404. inline std::string getAnnotation( Class cls,
  2405. std::string const& annotationName,
  2406. std::string const& testCaseName ) {
  2407. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  2408. SEL sel = NSSelectorFromString( selStr );
  2409. arcSafeRelease( selStr );
  2410. id value = performOptionalSelector( cls, sel );
  2411. if( value )
  2412. return [(NSString*)value UTF8String];
  2413. return "";
  2414. }
  2415. }
  2416. inline std::size_t registerTestMethods() {
  2417. std::size_t noTestMethods = 0;
  2418. int noClasses = objc_getClassList( nullptr, 0 );
  2419. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  2420. objc_getClassList( classes, noClasses );
  2421. for( int c = 0; c < noClasses; c++ ) {
  2422. Class cls = classes[c];
  2423. {
  2424. u_int count;
  2425. Method* methods = class_copyMethodList( cls, &count );
  2426. for( u_int m = 0; m < count ; m++ ) {
  2427. SEL selector = method_getName(methods[m]);
  2428. std::string methodName = sel_getName(selector);
  2429. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  2430. std::string testCaseName = methodName.substr( 15 );
  2431. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  2432. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  2433. const char* className = class_getName( cls );
  2434. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
  2435. noTestMethods++;
  2436. }
  2437. }
  2438. free(methods);
  2439. }
  2440. }
  2441. return noTestMethods;
  2442. }
  2443. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  2444. namespace Matchers {
  2445. namespace Impl {
  2446. namespace NSStringMatchers {
  2447. struct StringHolder : MatcherBase<NSString*>{
  2448. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  2449. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  2450. StringHolder() {
  2451. arcSafeRelease( m_substr );
  2452. }
  2453. bool match( NSString* arg ) const override {
  2454. return false;
  2455. }
  2456. NSString* CATCH_ARC_STRONG m_substr;
  2457. };
  2458. struct Equals : StringHolder {
  2459. Equals( NSString* substr ) : StringHolder( substr ){}
  2460. bool match( NSString* str ) const override {
  2461. return (str != nil || m_substr == nil ) &&
  2462. [str isEqualToString:m_substr];
  2463. }
  2464. std::string describe() const override {
  2465. return "equals string: " + Catch::Detail::stringify( m_substr );
  2466. }
  2467. };
  2468. struct Contains : StringHolder {
  2469. Contains( NSString* substr ) : StringHolder( substr ){}
  2470. bool match( NSString* str ) const {
  2471. return (str != nil || m_substr == nil ) &&
  2472. [str rangeOfString:m_substr].location != NSNotFound;
  2473. }
  2474. std::string describe() const override {
  2475. return "contains string: " + Catch::Detail::stringify( m_substr );
  2476. }
  2477. };
  2478. struct StartsWith : StringHolder {
  2479. StartsWith( NSString* substr ) : StringHolder( substr ){}
  2480. bool match( NSString* str ) const override {
  2481. return (str != nil || m_substr == nil ) &&
  2482. [str rangeOfString:m_substr].location == 0;
  2483. }
  2484. std::string describe() const override {
  2485. return "starts with: " + Catch::Detail::stringify( m_substr );
  2486. }
  2487. };
  2488. struct EndsWith : StringHolder {
  2489. EndsWith( NSString* substr ) : StringHolder( substr ){}
  2490. bool match( NSString* str ) const override {
  2491. return (str != nil || m_substr == nil ) &&
  2492. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  2493. }
  2494. std::string describe() const override {
  2495. return "ends with: " + Catch::Detail::stringify( m_substr );
  2496. }
  2497. };
  2498. } // namespace NSStringMatchers
  2499. } // namespace Impl
  2500. inline Impl::NSStringMatchers::Equals
  2501. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  2502. inline Impl::NSStringMatchers::Contains
  2503. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  2504. inline Impl::NSStringMatchers::StartsWith
  2505. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  2506. inline Impl::NSStringMatchers::EndsWith
  2507. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  2508. } // namespace Matchers
  2509. using namespace Matchers;
  2510. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  2511. } // namespace Catch
  2512. ///////////////////////////////////////////////////////////////////////////////
  2513. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  2514. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  2515. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  2516. { \
  2517. return @ name; \
  2518. } \
  2519. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  2520. { \
  2521. return @ desc; \
  2522. } \
  2523. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  2524. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  2525. // end catch_objc.hpp
  2526. #endif
  2527. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  2528. // start catch_external_interfaces.h
  2529. // start catch_reporter_bases.hpp
  2530. // start catch_interfaces_reporter.h
  2531. // start catch_config.hpp
  2532. // start catch_test_spec_parser.h
  2533. #ifdef __clang__
  2534. #pragma clang diagnostic push
  2535. #pragma clang diagnostic ignored "-Wpadded"
  2536. #endif
  2537. // start catch_test_spec.h
  2538. #ifdef __clang__
  2539. #pragma clang diagnostic push
  2540. #pragma clang diagnostic ignored "-Wpadded"
  2541. #endif
  2542. // start catch_wildcard_pattern.h
  2543. namespace Catch
  2544. {
  2545. class WildcardPattern {
  2546. enum WildcardPosition {
  2547. NoWildcard = 0,
  2548. WildcardAtStart = 1,
  2549. WildcardAtEnd = 2,
  2550. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  2551. };
  2552. public:
  2553. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  2554. virtual ~WildcardPattern() = default;
  2555. virtual bool matches( std::string const& str ) const;
  2556. private:
  2557. std::string adjustCase( std::string const& str ) const;
  2558. CaseSensitive::Choice m_caseSensitivity;
  2559. WildcardPosition m_wildcard = NoWildcard;
  2560. std::string m_pattern;
  2561. };
  2562. }
  2563. // end catch_wildcard_pattern.h
  2564. #include <string>
  2565. #include <vector>
  2566. #include <memory>
  2567. namespace Catch {
  2568. class TestSpec {
  2569. struct Pattern {
  2570. virtual ~Pattern();
  2571. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  2572. };
  2573. using PatternPtr = std::shared_ptr<Pattern>;
  2574. class NamePattern : public Pattern {
  2575. public:
  2576. NamePattern( std::string const& name );
  2577. virtual ~NamePattern();
  2578. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2579. private:
  2580. WildcardPattern m_wildcardPattern;
  2581. };
  2582. class TagPattern : public Pattern {
  2583. public:
  2584. TagPattern( std::string const& tag );
  2585. virtual ~TagPattern();
  2586. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2587. private:
  2588. std::string m_tag;
  2589. };
  2590. class ExcludedPattern : public Pattern {
  2591. public:
  2592. ExcludedPattern( PatternPtr const& underlyingPattern );
  2593. virtual ~ExcludedPattern();
  2594. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2595. private:
  2596. PatternPtr m_underlyingPattern;
  2597. };
  2598. struct Filter {
  2599. std::vector<PatternPtr> m_patterns;
  2600. bool matches( TestCaseInfo const& testCase ) const;
  2601. };
  2602. public:
  2603. bool hasFilters() const;
  2604. bool matches( TestCaseInfo const& testCase ) const;
  2605. private:
  2606. std::vector<Filter> m_filters;
  2607. friend class TestSpecParser;
  2608. };
  2609. }
  2610. #ifdef __clang__
  2611. #pragma clang diagnostic pop
  2612. #endif
  2613. // end catch_test_spec.h
  2614. // start catch_interfaces_tag_alias_registry.h
  2615. #include <string>
  2616. namespace Catch {
  2617. struct TagAlias;
  2618. struct ITagAliasRegistry {
  2619. virtual ~ITagAliasRegistry();
  2620. // Nullptr if not present
  2621. virtual TagAlias const* find( std::string const& alias ) const = 0;
  2622. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  2623. static ITagAliasRegistry const& get();
  2624. };
  2625. } // end namespace Catch
  2626. // end catch_interfaces_tag_alias_registry.h
  2627. namespace Catch {
  2628. class TestSpecParser {
  2629. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  2630. Mode m_mode = None;
  2631. bool m_exclusion = false;
  2632. std::size_t m_start = std::string::npos, m_pos = 0;
  2633. std::string m_arg;
  2634. std::vector<std::size_t> m_escapeChars;
  2635. TestSpec::Filter m_currentFilter;
  2636. TestSpec m_testSpec;
  2637. ITagAliasRegistry const* m_tagAliases = nullptr;
  2638. public:
  2639. TestSpecParser( ITagAliasRegistry const& tagAliases );
  2640. TestSpecParser& parse( std::string const& arg );
  2641. TestSpec testSpec();
  2642. private:
  2643. void visitChar( char c );
  2644. void startNewMode( Mode mode, std::size_t start );
  2645. void escape();
  2646. std::string subString() const;
  2647. template<typename T>
  2648. void addPattern() {
  2649. std::string token = subString();
  2650. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  2651. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  2652. m_escapeChars.clear();
  2653. if( startsWith( token, "exclude:" ) ) {
  2654. m_exclusion = true;
  2655. token = token.substr( 8 );
  2656. }
  2657. if( !token.empty() ) {
  2658. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  2659. if( m_exclusion )
  2660. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  2661. m_currentFilter.m_patterns.push_back( pattern );
  2662. }
  2663. m_exclusion = false;
  2664. m_mode = None;
  2665. }
  2666. void addFilter();
  2667. };
  2668. TestSpec parseTestSpec( std::string const& arg );
  2669. } // namespace Catch
  2670. #ifdef __clang__
  2671. #pragma clang diagnostic pop
  2672. #endif
  2673. // end catch_test_spec_parser.h
  2674. // start catch_interfaces_config.h
  2675. #include <iosfwd>
  2676. #include <string>
  2677. #include <vector>
  2678. #include <memory>
  2679. namespace Catch {
  2680. enum class Verbosity {
  2681. Quiet = 0,
  2682. Normal,
  2683. High
  2684. };
  2685. struct WarnAbout { enum What {
  2686. Nothing = 0x00,
  2687. NoAssertions = 0x01,
  2688. NoTests = 0x02
  2689. }; };
  2690. struct ShowDurations { enum OrNot {
  2691. DefaultForReporter,
  2692. Always,
  2693. Never
  2694. }; };
  2695. struct RunTests { enum InWhatOrder {
  2696. InDeclarationOrder,
  2697. InLexicographicalOrder,
  2698. InRandomOrder
  2699. }; };
  2700. struct UseColour { enum YesOrNo {
  2701. Auto,
  2702. Yes,
  2703. No
  2704. }; };
  2705. struct WaitForKeypress { enum When {
  2706. Never,
  2707. BeforeStart = 1,
  2708. BeforeExit = 2,
  2709. BeforeStartAndExit = BeforeStart | BeforeExit
  2710. }; };
  2711. class TestSpec;
  2712. struct IConfig : NonCopyable {
  2713. virtual ~IConfig();
  2714. virtual bool allowThrows() const = 0;
  2715. virtual std::ostream& stream() const = 0;
  2716. virtual std::string name() const = 0;
  2717. virtual bool includeSuccessfulResults() const = 0;
  2718. virtual bool shouldDebugBreak() const = 0;
  2719. virtual bool warnAboutMissingAssertions() const = 0;
  2720. virtual bool warnAboutNoTests() const = 0;
  2721. virtual int abortAfter() const = 0;
  2722. virtual bool showInvisibles() const = 0;
  2723. virtual ShowDurations::OrNot showDurations() const = 0;
  2724. virtual TestSpec const& testSpec() const = 0;
  2725. virtual bool hasTestFilters() const = 0;
  2726. virtual RunTests::InWhatOrder runOrder() const = 0;
  2727. virtual unsigned int rngSeed() const = 0;
  2728. virtual int benchmarkResolutionMultiple() const = 0;
  2729. virtual UseColour::YesOrNo useColour() const = 0;
  2730. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  2731. virtual Verbosity verbosity() const = 0;
  2732. };
  2733. using IConfigPtr = std::shared_ptr<IConfig const>;
  2734. }
  2735. // end catch_interfaces_config.h
  2736. // Libstdc++ doesn't like incomplete classes for unique_ptr
  2737. #include <memory>
  2738. #include <vector>
  2739. #include <string>
  2740. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  2741. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  2742. #endif
  2743. namespace Catch {
  2744. struct IStream;
  2745. struct ConfigData {
  2746. bool listTests = false;
  2747. bool listTags = false;
  2748. bool listReporters = false;
  2749. bool listTestNamesOnly = false;
  2750. bool showSuccessfulTests = false;
  2751. bool shouldDebugBreak = false;
  2752. bool noThrow = false;
  2753. bool showHelp = false;
  2754. bool showInvisibles = false;
  2755. bool filenamesAsTags = false;
  2756. bool libIdentify = false;
  2757. int abortAfter = -1;
  2758. unsigned int rngSeed = 0;
  2759. int benchmarkResolutionMultiple = 100;
  2760. Verbosity verbosity = Verbosity::Normal;
  2761. WarnAbout::What warnings = WarnAbout::Nothing;
  2762. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  2763. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  2764. UseColour::YesOrNo useColour = UseColour::Auto;
  2765. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  2766. std::string outputFilename;
  2767. std::string name;
  2768. std::string processName;
  2769. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  2770. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  2771. #endif
  2772. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  2773. #undef CATCH_CONFIG_DEFAULT_REPORTER
  2774. std::vector<std::string> testsOrTags;
  2775. std::vector<std::string> sectionsToRun;
  2776. };
  2777. class Config : public IConfig {
  2778. public:
  2779. Config() = default;
  2780. Config( ConfigData const& data );
  2781. virtual ~Config() = default;
  2782. std::string const& getFilename() const;
  2783. bool listTests() const;
  2784. bool listTestNamesOnly() const;
  2785. bool listTags() const;
  2786. bool listReporters() const;
  2787. std::string getProcessName() const;
  2788. std::string const& getReporterName() const;
  2789. std::vector<std::string> const& getTestsOrTags() const;
  2790. std::vector<std::string> const& getSectionsToRun() const override;
  2791. virtual TestSpec const& testSpec() const override;
  2792. bool hasTestFilters() const override;
  2793. bool showHelp() const;
  2794. // IConfig interface
  2795. bool allowThrows() const override;
  2796. std::ostream& stream() const override;
  2797. std::string name() const override;
  2798. bool includeSuccessfulResults() const override;
  2799. bool warnAboutMissingAssertions() const override;
  2800. bool warnAboutNoTests() const override;
  2801. ShowDurations::OrNot showDurations() const override;
  2802. RunTests::InWhatOrder runOrder() const override;
  2803. unsigned int rngSeed() const override;
  2804. int benchmarkResolutionMultiple() const override;
  2805. UseColour::YesOrNo useColour() const override;
  2806. bool shouldDebugBreak() const override;
  2807. int abortAfter() const override;
  2808. bool showInvisibles() const override;
  2809. Verbosity verbosity() const override;
  2810. private:
  2811. IStream const* openStream();
  2812. ConfigData m_data;
  2813. std::unique_ptr<IStream const> m_stream;
  2814. TestSpec m_testSpec;
  2815. bool m_hasTestFilters = false;
  2816. };
  2817. } // end namespace Catch
  2818. // end catch_config.hpp
  2819. // start catch_assertionresult.h
  2820. #include <string>
  2821. namespace Catch {
  2822. struct AssertionResultData
  2823. {
  2824. AssertionResultData() = delete;
  2825. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  2826. std::string message;
  2827. mutable std::string reconstructedExpression;
  2828. LazyExpression lazyExpression;
  2829. ResultWas::OfType resultType;
  2830. std::string reconstructExpression() const;
  2831. };
  2832. class AssertionResult {
  2833. public:
  2834. AssertionResult() = delete;
  2835. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  2836. bool isOk() const;
  2837. bool succeeded() const;
  2838. ResultWas::OfType getResultType() const;
  2839. bool hasExpression() const;
  2840. bool hasMessage() const;
  2841. std::string getExpression() const;
  2842. std::string getExpressionInMacro() const;
  2843. bool hasExpandedExpression() const;
  2844. std::string getExpandedExpression() const;
  2845. std::string getMessage() const;
  2846. SourceLineInfo getSourceInfo() const;
  2847. StringRef getTestMacroName() const;
  2848. //protected:
  2849. AssertionInfo m_info;
  2850. AssertionResultData m_resultData;
  2851. };
  2852. } // end namespace Catch
  2853. // end catch_assertionresult.h
  2854. // start catch_option.hpp
  2855. namespace Catch {
  2856. // An optional type
  2857. template<typename T>
  2858. class Option {
  2859. public:
  2860. Option() : nullableValue( nullptr ) {}
  2861. Option( T const& _value )
  2862. : nullableValue( new( storage ) T( _value ) )
  2863. {}
  2864. Option( Option const& _other )
  2865. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  2866. {}
  2867. ~Option() {
  2868. reset();
  2869. }
  2870. Option& operator= ( Option const& _other ) {
  2871. if( &_other != this ) {
  2872. reset();
  2873. if( _other )
  2874. nullableValue = new( storage ) T( *_other );
  2875. }
  2876. return *this;
  2877. }
  2878. Option& operator = ( T const& _value ) {
  2879. reset();
  2880. nullableValue = new( storage ) T( _value );
  2881. return *this;
  2882. }
  2883. void reset() {
  2884. if( nullableValue )
  2885. nullableValue->~T();
  2886. nullableValue = nullptr;
  2887. }
  2888. T& operator*() { return *nullableValue; }
  2889. T const& operator*() const { return *nullableValue; }
  2890. T* operator->() { return nullableValue; }
  2891. const T* operator->() const { return nullableValue; }
  2892. T valueOr( T const& defaultValue ) const {
  2893. return nullableValue ? *nullableValue : defaultValue;
  2894. }
  2895. bool some() const { return nullableValue != nullptr; }
  2896. bool none() const { return nullableValue == nullptr; }
  2897. bool operator !() const { return nullableValue == nullptr; }
  2898. explicit operator bool() const {
  2899. return some();
  2900. }
  2901. private:
  2902. T *nullableValue;
  2903. alignas(alignof(T)) char storage[sizeof(T)];
  2904. };
  2905. } // end namespace Catch
  2906. // end catch_option.hpp
  2907. #include <string>
  2908. #include <iosfwd>
  2909. #include <map>
  2910. #include <set>
  2911. #include <memory>
  2912. namespace Catch {
  2913. struct ReporterConfig {
  2914. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  2915. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  2916. std::ostream& stream() const;
  2917. IConfigPtr fullConfig() const;
  2918. private:
  2919. std::ostream* m_stream;
  2920. IConfigPtr m_fullConfig;
  2921. };
  2922. struct ReporterPreferences {
  2923. bool shouldRedirectStdOut = false;
  2924. bool shouldReportAllAssertions = false;
  2925. };
  2926. template<typename T>
  2927. struct LazyStat : Option<T> {
  2928. LazyStat& operator=( T const& _value ) {
  2929. Option<T>::operator=( _value );
  2930. used = false;
  2931. return *this;
  2932. }
  2933. void reset() {
  2934. Option<T>::reset();
  2935. used = false;
  2936. }
  2937. bool used = false;
  2938. };
  2939. struct TestRunInfo {
  2940. TestRunInfo( std::string const& _name );
  2941. std::string name;
  2942. };
  2943. struct GroupInfo {
  2944. GroupInfo( std::string const& _name,
  2945. std::size_t _groupIndex,
  2946. std::size_t _groupsCount );
  2947. std::string name;
  2948. std::size_t groupIndex;
  2949. std::size_t groupsCounts;
  2950. };
  2951. struct AssertionStats {
  2952. AssertionStats( AssertionResult const& _assertionResult,
  2953. std::vector<MessageInfo> const& _infoMessages,
  2954. Totals const& _totals );
  2955. AssertionStats( AssertionStats const& ) = default;
  2956. AssertionStats( AssertionStats && ) = default;
  2957. AssertionStats& operator = ( AssertionStats const& ) = default;
  2958. AssertionStats& operator = ( AssertionStats && ) = default;
  2959. virtual ~AssertionStats();
  2960. AssertionResult assertionResult;
  2961. std::vector<MessageInfo> infoMessages;
  2962. Totals totals;
  2963. };
  2964. struct SectionStats {
  2965. SectionStats( SectionInfo const& _sectionInfo,
  2966. Counts const& _assertions,
  2967. double _durationInSeconds,
  2968. bool _missingAssertions );
  2969. SectionStats( SectionStats const& ) = default;
  2970. SectionStats( SectionStats && ) = default;
  2971. SectionStats& operator = ( SectionStats const& ) = default;
  2972. SectionStats& operator = ( SectionStats && ) = default;
  2973. virtual ~SectionStats();
  2974. SectionInfo sectionInfo;
  2975. Counts assertions;
  2976. double durationInSeconds;
  2977. bool missingAssertions;
  2978. };
  2979. struct TestCaseStats {
  2980. TestCaseStats( TestCaseInfo const& _testInfo,
  2981. Totals const& _totals,
  2982. std::string const& _stdOut,
  2983. std::string const& _stdErr,
  2984. bool _aborting );
  2985. TestCaseStats( TestCaseStats const& ) = default;
  2986. TestCaseStats( TestCaseStats && ) = default;
  2987. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  2988. TestCaseStats& operator = ( TestCaseStats && ) = default;
  2989. virtual ~TestCaseStats();
  2990. TestCaseInfo testInfo;
  2991. Totals totals;
  2992. std::string stdOut;
  2993. std::string stdErr;
  2994. bool aborting;
  2995. };
  2996. struct TestGroupStats {
  2997. TestGroupStats( GroupInfo const& _groupInfo,
  2998. Totals const& _totals,
  2999. bool _aborting );
  3000. TestGroupStats( GroupInfo const& _groupInfo );
  3001. TestGroupStats( TestGroupStats const& ) = default;
  3002. TestGroupStats( TestGroupStats && ) = default;
  3003. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  3004. TestGroupStats& operator = ( TestGroupStats && ) = default;
  3005. virtual ~TestGroupStats();
  3006. GroupInfo groupInfo;
  3007. Totals totals;
  3008. bool aborting;
  3009. };
  3010. struct TestRunStats {
  3011. TestRunStats( TestRunInfo const& _runInfo,
  3012. Totals const& _totals,
  3013. bool _aborting );
  3014. TestRunStats( TestRunStats const& ) = default;
  3015. TestRunStats( TestRunStats && ) = default;
  3016. TestRunStats& operator = ( TestRunStats const& ) = default;
  3017. TestRunStats& operator = ( TestRunStats && ) = default;
  3018. virtual ~TestRunStats();
  3019. TestRunInfo runInfo;
  3020. Totals totals;
  3021. bool aborting;
  3022. };
  3023. struct BenchmarkInfo {
  3024. std::string name;
  3025. };
  3026. struct BenchmarkStats {
  3027. BenchmarkInfo info;
  3028. std::size_t iterations;
  3029. uint64_t elapsedTimeInNanoseconds;
  3030. };
  3031. struct IStreamingReporter {
  3032. virtual ~IStreamingReporter() = default;
  3033. // Implementing class must also provide the following static methods:
  3034. // static std::string getDescription();
  3035. // static std::set<Verbosity> getSupportedVerbosities()
  3036. virtual ReporterPreferences getPreferences() const = 0;
  3037. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  3038. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  3039. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  3040. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  3041. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  3042. // *** experimental ***
  3043. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  3044. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  3045. // The return value indicates if the messages buffer should be cleared:
  3046. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  3047. // *** experimental ***
  3048. virtual void benchmarkEnded( BenchmarkStats const& ) {}
  3049. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  3050. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  3051. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  3052. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  3053. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  3054. // Default empty implementation provided
  3055. virtual void fatalErrorEncountered( StringRef name );
  3056. virtual bool isMulti() const;
  3057. };
  3058. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  3059. struct IReporterFactory {
  3060. virtual ~IReporterFactory();
  3061. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  3062. virtual std::string getDescription() const = 0;
  3063. };
  3064. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  3065. struct IReporterRegistry {
  3066. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  3067. using Listeners = std::vector<IReporterFactoryPtr>;
  3068. virtual ~IReporterRegistry();
  3069. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  3070. virtual FactoryMap const& getFactories() const = 0;
  3071. virtual Listeners const& getListeners() const = 0;
  3072. };
  3073. } // end namespace Catch
  3074. // end catch_interfaces_reporter.h
  3075. #include <algorithm>
  3076. #include <cstring>
  3077. #include <cfloat>
  3078. #include <cstdio>
  3079. #include <cassert>
  3080. #include <memory>
  3081. #include <ostream>
  3082. namespace Catch {
  3083. void prepareExpandedExpression(AssertionResult& result);
  3084. // Returns double formatted as %.3f (format expected on output)
  3085. std::string getFormattedDuration( double duration );
  3086. template<typename DerivedT>
  3087. struct StreamingReporterBase : IStreamingReporter {
  3088. StreamingReporterBase( ReporterConfig const& _config )
  3089. : m_config( _config.fullConfig() ),
  3090. stream( _config.stream() )
  3091. {
  3092. m_reporterPrefs.shouldRedirectStdOut = false;
  3093. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3094. throw std::domain_error( "Verbosity level not supported by this reporter" );
  3095. }
  3096. ReporterPreferences getPreferences() const override {
  3097. return m_reporterPrefs;
  3098. }
  3099. static std::set<Verbosity> getSupportedVerbosities() {
  3100. return { Verbosity::Normal };
  3101. }
  3102. ~StreamingReporterBase() override = default;
  3103. void noMatchingTestCases(std::string const&) override {}
  3104. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  3105. currentTestRunInfo = _testRunInfo;
  3106. }
  3107. void testGroupStarting(GroupInfo const& _groupInfo) override {
  3108. currentGroupInfo = _groupInfo;
  3109. }
  3110. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  3111. currentTestCaseInfo = _testInfo;
  3112. }
  3113. void sectionStarting(SectionInfo const& _sectionInfo) override {
  3114. m_sectionStack.push_back(_sectionInfo);
  3115. }
  3116. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  3117. m_sectionStack.pop_back();
  3118. }
  3119. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  3120. currentTestCaseInfo.reset();
  3121. }
  3122. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  3123. currentGroupInfo.reset();
  3124. }
  3125. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  3126. currentTestCaseInfo.reset();
  3127. currentGroupInfo.reset();
  3128. currentTestRunInfo.reset();
  3129. }
  3130. void skipTest(TestCaseInfo const&) override {
  3131. // Don't do anything with this by default.
  3132. // It can optionally be overridden in the derived class.
  3133. }
  3134. IConfigPtr m_config;
  3135. std::ostream& stream;
  3136. LazyStat<TestRunInfo> currentTestRunInfo;
  3137. LazyStat<GroupInfo> currentGroupInfo;
  3138. LazyStat<TestCaseInfo> currentTestCaseInfo;
  3139. std::vector<SectionInfo> m_sectionStack;
  3140. ReporterPreferences m_reporterPrefs;
  3141. };
  3142. template<typename DerivedT>
  3143. struct CumulativeReporterBase : IStreamingReporter {
  3144. template<typename T, typename ChildNodeT>
  3145. struct Node {
  3146. explicit Node( T const& _value ) : value( _value ) {}
  3147. virtual ~Node() {}
  3148. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  3149. T value;
  3150. ChildNodes children;
  3151. };
  3152. struct SectionNode {
  3153. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  3154. virtual ~SectionNode() = default;
  3155. bool operator == (SectionNode const& other) const {
  3156. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  3157. }
  3158. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  3159. return operator==(*other);
  3160. }
  3161. SectionStats stats;
  3162. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  3163. using Assertions = std::vector<AssertionStats>;
  3164. ChildSections childSections;
  3165. Assertions assertions;
  3166. std::string stdOut;
  3167. std::string stdErr;
  3168. };
  3169. struct BySectionInfo {
  3170. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  3171. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  3172. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  3173. return ((node->stats.sectionInfo.name == m_other.name) &&
  3174. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  3175. }
  3176. void operator=(BySectionInfo const&) = delete;
  3177. private:
  3178. SectionInfo const& m_other;
  3179. };
  3180. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  3181. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  3182. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  3183. CumulativeReporterBase( ReporterConfig const& _config )
  3184. : m_config( _config.fullConfig() ),
  3185. stream( _config.stream() )
  3186. {
  3187. m_reporterPrefs.shouldRedirectStdOut = false;
  3188. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3189. throw std::domain_error( "Verbosity level not supported by this reporter" );
  3190. }
  3191. ~CumulativeReporterBase() override = default;
  3192. ReporterPreferences getPreferences() const override {
  3193. return m_reporterPrefs;
  3194. }
  3195. static std::set<Verbosity> getSupportedVerbosities() {
  3196. return { Verbosity::Normal };
  3197. }
  3198. void testRunStarting( TestRunInfo const& ) override {}
  3199. void testGroupStarting( GroupInfo const& ) override {}
  3200. void testCaseStarting( TestCaseInfo const& ) override {}
  3201. void sectionStarting( SectionInfo const& sectionInfo ) override {
  3202. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  3203. std::shared_ptr<SectionNode> node;
  3204. if( m_sectionStack.empty() ) {
  3205. if( !m_rootSection )
  3206. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  3207. node = m_rootSection;
  3208. }
  3209. else {
  3210. SectionNode& parentNode = *m_sectionStack.back();
  3211. auto it =
  3212. std::find_if( parentNode.childSections.begin(),
  3213. parentNode.childSections.end(),
  3214. BySectionInfo( sectionInfo ) );
  3215. if( it == parentNode.childSections.end() ) {
  3216. node = std::make_shared<SectionNode>( incompleteStats );
  3217. parentNode.childSections.push_back( node );
  3218. }
  3219. else
  3220. node = *it;
  3221. }
  3222. m_sectionStack.push_back( node );
  3223. m_deepestSection = std::move(node);
  3224. }
  3225. void assertionStarting(AssertionInfo const&) override {}
  3226. bool assertionEnded(AssertionStats const& assertionStats) override {
  3227. assert(!m_sectionStack.empty());
  3228. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  3229. // which getExpandedExpression() calls to build the expression string.
  3230. // Our section stack copy of the assertionResult will likely outlive the
  3231. // temporary, so it must be expanded or discarded now to avoid calling
  3232. // a destroyed object later.
  3233. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  3234. SectionNode& sectionNode = *m_sectionStack.back();
  3235. sectionNode.assertions.push_back(assertionStats);
  3236. return true;
  3237. }
  3238. void sectionEnded(SectionStats const& sectionStats) override {
  3239. assert(!m_sectionStack.empty());
  3240. SectionNode& node = *m_sectionStack.back();
  3241. node.stats = sectionStats;
  3242. m_sectionStack.pop_back();
  3243. }
  3244. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  3245. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  3246. assert(m_sectionStack.size() == 0);
  3247. node->children.push_back(m_rootSection);
  3248. m_testCases.push_back(node);
  3249. m_rootSection.reset();
  3250. assert(m_deepestSection);
  3251. m_deepestSection->stdOut = testCaseStats.stdOut;
  3252. m_deepestSection->stdErr = testCaseStats.stdErr;
  3253. }
  3254. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  3255. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  3256. node->children.swap(m_testCases);
  3257. m_testGroups.push_back(node);
  3258. }
  3259. void testRunEnded(TestRunStats const& testRunStats) override {
  3260. auto node = std::make_shared<TestRunNode>(testRunStats);
  3261. node->children.swap(m_testGroups);
  3262. m_testRuns.push_back(node);
  3263. testRunEndedCumulative();
  3264. }
  3265. virtual void testRunEndedCumulative() = 0;
  3266. void skipTest(TestCaseInfo const&) override {}
  3267. IConfigPtr m_config;
  3268. std::ostream& stream;
  3269. std::vector<AssertionStats> m_assertions;
  3270. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  3271. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  3272. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  3273. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  3274. std::shared_ptr<SectionNode> m_rootSection;
  3275. std::shared_ptr<SectionNode> m_deepestSection;
  3276. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  3277. ReporterPreferences m_reporterPrefs;
  3278. };
  3279. template<char C>
  3280. char const* getLineOfChars() {
  3281. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  3282. if( !*line ) {
  3283. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  3284. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  3285. }
  3286. return line;
  3287. }
  3288. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  3289. TestEventListenerBase( ReporterConfig const& _config );
  3290. void assertionStarting(AssertionInfo const&) override;
  3291. bool assertionEnded(AssertionStats const&) override;
  3292. };
  3293. } // end namespace Catch
  3294. // end catch_reporter_bases.hpp
  3295. // start catch_console_colour.h
  3296. namespace Catch {
  3297. struct Colour {
  3298. enum Code {
  3299. None = 0,
  3300. White,
  3301. Red,
  3302. Green,
  3303. Blue,
  3304. Cyan,
  3305. Yellow,
  3306. Grey,
  3307. Bright = 0x10,
  3308. BrightRed = Bright | Red,
  3309. BrightGreen = Bright | Green,
  3310. LightGrey = Bright | Grey,
  3311. BrightWhite = Bright | White,
  3312. BrightYellow = Bright | Yellow,
  3313. // By intention
  3314. FileName = LightGrey,
  3315. Warning = BrightYellow,
  3316. ResultError = BrightRed,
  3317. ResultSuccess = BrightGreen,
  3318. ResultExpectedFailure = Warning,
  3319. Error = BrightRed,
  3320. Success = Green,
  3321. OriginalExpression = Cyan,
  3322. ReconstructedExpression = BrightYellow,
  3323. SecondaryText = LightGrey,
  3324. Headers = White
  3325. };
  3326. // Use constructed object for RAII guard
  3327. Colour( Code _colourCode );
  3328. Colour( Colour&& other ) noexcept;
  3329. Colour& operator=( Colour&& other ) noexcept;
  3330. ~Colour();
  3331. // Use static method for one-shot changes
  3332. static void use( Code _colourCode );
  3333. private:
  3334. bool m_moved = false;
  3335. };
  3336. std::ostream& operator << ( std::ostream& os, Colour const& );
  3337. } // end namespace Catch
  3338. // end catch_console_colour.h
  3339. // start catch_reporter_registrars.hpp
  3340. namespace Catch {
  3341. template<typename T>
  3342. class ReporterRegistrar {
  3343. class ReporterFactory : public IReporterFactory {
  3344. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3345. return std::unique_ptr<T>( new T( config ) );
  3346. }
  3347. virtual std::string getDescription() const override {
  3348. return T::getDescription();
  3349. }
  3350. };
  3351. public:
  3352. explicit ReporterRegistrar( std::string const& name ) {
  3353. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  3354. }
  3355. };
  3356. template<typename T>
  3357. class ListenerRegistrar {
  3358. class ListenerFactory : public IReporterFactory {
  3359. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3360. return std::unique_ptr<T>( new T( config ) );
  3361. }
  3362. virtual std::string getDescription() const override {
  3363. return std::string();
  3364. }
  3365. };
  3366. public:
  3367. ListenerRegistrar() {
  3368. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  3369. }
  3370. };
  3371. }
  3372. #if !defined(CATCH_CONFIG_DISABLE)
  3373. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  3374. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3375. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  3376. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  3377. #define CATCH_REGISTER_LISTENER( listenerType ) \
  3378. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3379. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  3380. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  3381. #else // CATCH_CONFIG_DISABLE
  3382. #define CATCH_REGISTER_REPORTER(name, reporterType)
  3383. #define CATCH_REGISTER_LISTENER(listenerType)
  3384. #endif // CATCH_CONFIG_DISABLE
  3385. // end catch_reporter_registrars.hpp
  3386. // Allow users to base their work off existing reporters
  3387. // start catch_reporter_compact.h
  3388. namespace Catch {
  3389. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  3390. using StreamingReporterBase::StreamingReporterBase;
  3391. ~CompactReporter() override;
  3392. static std::string getDescription();
  3393. ReporterPreferences getPreferences() const override;
  3394. void noMatchingTestCases(std::string const& spec) override;
  3395. void assertionStarting(AssertionInfo const&) override;
  3396. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3397. void sectionEnded(SectionStats const& _sectionStats) override;
  3398. void testRunEnded(TestRunStats const& _testRunStats) override;
  3399. };
  3400. } // end namespace Catch
  3401. // end catch_reporter_compact.h
  3402. // start catch_reporter_console.h
  3403. #if defined(_MSC_VER)
  3404. #pragma warning(push)
  3405. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  3406. // Note that 4062 (not all labels are handled
  3407. // and default is missing) is enabled
  3408. #endif
  3409. namespace Catch {
  3410. // Fwd decls
  3411. struct SummaryColumn;
  3412. class TablePrinter;
  3413. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  3414. std::unique_ptr<TablePrinter> m_tablePrinter;
  3415. ConsoleReporter(ReporterConfig const& config);
  3416. ~ConsoleReporter() override;
  3417. static std::string getDescription();
  3418. void noMatchingTestCases(std::string const& spec) override;
  3419. void assertionStarting(AssertionInfo const&) override;
  3420. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3421. void sectionStarting(SectionInfo const& _sectionInfo) override;
  3422. void sectionEnded(SectionStats const& _sectionStats) override;
  3423. void benchmarkStarting(BenchmarkInfo const& info) override;
  3424. void benchmarkEnded(BenchmarkStats const& stats) override;
  3425. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  3426. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  3427. void testRunEnded(TestRunStats const& _testRunStats) override;
  3428. private:
  3429. void lazyPrint();
  3430. void lazyPrintWithoutClosingBenchmarkTable();
  3431. void lazyPrintRunInfo();
  3432. void lazyPrintGroupInfo();
  3433. void printTestCaseAndSectionHeader();
  3434. void printClosedHeader(std::string const& _name);
  3435. void printOpenHeader(std::string const& _name);
  3436. // if string has a : in first line will set indent to follow it on
  3437. // subsequent lines
  3438. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  3439. void printTotals(Totals const& totals);
  3440. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  3441. void printTotalsDivider(Totals const& totals);
  3442. void printSummaryDivider();
  3443. private:
  3444. bool m_headerPrinted = false;
  3445. };
  3446. } // end namespace Catch
  3447. #if defined(_MSC_VER)
  3448. #pragma warning(pop)
  3449. #endif
  3450. // end catch_reporter_console.h
  3451. // start catch_reporter_junit.h
  3452. // start catch_xmlwriter.h
  3453. #include <vector>
  3454. namespace Catch {
  3455. class XmlEncode {
  3456. public:
  3457. enum ForWhat { ForTextNodes, ForAttributes };
  3458. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  3459. void encodeTo( std::ostream& os ) const;
  3460. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  3461. private:
  3462. std::string m_str;
  3463. ForWhat m_forWhat;
  3464. };
  3465. class XmlWriter {
  3466. public:
  3467. class ScopedElement {
  3468. public:
  3469. ScopedElement( XmlWriter* writer );
  3470. ScopedElement( ScopedElement&& other ) noexcept;
  3471. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  3472. ~ScopedElement();
  3473. ScopedElement& writeText( std::string const& text, bool indent = true );
  3474. template<typename T>
  3475. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  3476. m_writer->writeAttribute( name, attribute );
  3477. return *this;
  3478. }
  3479. private:
  3480. mutable XmlWriter* m_writer = nullptr;
  3481. };
  3482. XmlWriter( std::ostream& os = Catch::cout() );
  3483. ~XmlWriter();
  3484. XmlWriter( XmlWriter const& ) = delete;
  3485. XmlWriter& operator=( XmlWriter const& ) = delete;
  3486. XmlWriter& startElement( std::string const& name );
  3487. ScopedElement scopedElement( std::string const& name );
  3488. XmlWriter& endElement();
  3489. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  3490. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  3491. template<typename T>
  3492. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  3493. ReusableStringStream rss;
  3494. rss << attribute;
  3495. return writeAttribute( name, rss.str() );
  3496. }
  3497. XmlWriter& writeText( std::string const& text, bool indent = true );
  3498. XmlWriter& writeComment( std::string const& text );
  3499. void writeStylesheetRef( std::string const& url );
  3500. XmlWriter& writeBlankLine();
  3501. void ensureTagClosed();
  3502. private:
  3503. void writeDeclaration();
  3504. void newlineIfNecessary();
  3505. bool m_tagIsOpen = false;
  3506. bool m_needsNewline = false;
  3507. std::vector<std::string> m_tags;
  3508. std::string m_indent;
  3509. std::ostream& m_os;
  3510. };
  3511. }
  3512. // end catch_xmlwriter.h
  3513. namespace Catch {
  3514. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  3515. public:
  3516. JunitReporter(ReporterConfig const& _config);
  3517. ~JunitReporter() override;
  3518. static std::string getDescription();
  3519. void noMatchingTestCases(std::string const& /*spec*/) override;
  3520. void testRunStarting(TestRunInfo const& runInfo) override;
  3521. void testGroupStarting(GroupInfo const& groupInfo) override;
  3522. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  3523. bool assertionEnded(AssertionStats const& assertionStats) override;
  3524. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3525. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3526. void testRunEndedCumulative() override;
  3527. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  3528. void writeTestCase(TestCaseNode const& testCaseNode);
  3529. void writeSection(std::string const& className,
  3530. std::string const& rootName,
  3531. SectionNode const& sectionNode);
  3532. void writeAssertions(SectionNode const& sectionNode);
  3533. void writeAssertion(AssertionStats const& stats);
  3534. XmlWriter xml;
  3535. Timer suiteTimer;
  3536. std::string stdOutForSuite;
  3537. std::string stdErrForSuite;
  3538. unsigned int unexpectedExceptions = 0;
  3539. bool m_okToFail = false;
  3540. };
  3541. } // end namespace Catch
  3542. // end catch_reporter_junit.h
  3543. // start catch_reporter_xml.h
  3544. namespace Catch {
  3545. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  3546. public:
  3547. XmlReporter(ReporterConfig const& _config);
  3548. ~XmlReporter() override;
  3549. static std::string getDescription();
  3550. virtual std::string getStylesheetRef() const;
  3551. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  3552. public: // StreamingReporterBase
  3553. void noMatchingTestCases(std::string const& s) override;
  3554. void testRunStarting(TestRunInfo const& testInfo) override;
  3555. void testGroupStarting(GroupInfo const& groupInfo) override;
  3556. void testCaseStarting(TestCaseInfo const& testInfo) override;
  3557. void sectionStarting(SectionInfo const& sectionInfo) override;
  3558. void assertionStarting(AssertionInfo const&) override;
  3559. bool assertionEnded(AssertionStats const& assertionStats) override;
  3560. void sectionEnded(SectionStats const& sectionStats) override;
  3561. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3562. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3563. void testRunEnded(TestRunStats const& testRunStats) override;
  3564. private:
  3565. Timer m_testCaseTimer;
  3566. XmlWriter m_xml;
  3567. int m_sectionDepth = 0;
  3568. };
  3569. } // end namespace Catch
  3570. // end catch_reporter_xml.h
  3571. // end catch_external_interfaces.h
  3572. #endif
  3573. #endif // ! CATCH_CONFIG_IMPL_ONLY
  3574. #ifdef CATCH_IMPL
  3575. // start catch_impl.hpp
  3576. #ifdef __clang__
  3577. #pragma clang diagnostic push
  3578. #pragma clang diagnostic ignored "-Wweak-vtables"
  3579. #endif
  3580. // Keep these here for external reporters
  3581. // start catch_test_case_tracker.h
  3582. #include <string>
  3583. #include <vector>
  3584. #include <memory>
  3585. namespace Catch {
  3586. namespace TestCaseTracking {
  3587. struct NameAndLocation {
  3588. std::string name;
  3589. SourceLineInfo location;
  3590. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  3591. };
  3592. struct ITracker;
  3593. using ITrackerPtr = std::shared_ptr<ITracker>;
  3594. struct ITracker {
  3595. virtual ~ITracker();
  3596. // static queries
  3597. virtual NameAndLocation const& nameAndLocation() const = 0;
  3598. // dynamic queries
  3599. virtual bool isComplete() const = 0; // Successfully completed or failed
  3600. virtual bool isSuccessfullyCompleted() const = 0;
  3601. virtual bool isOpen() const = 0; // Started but not complete
  3602. virtual bool hasChildren() const = 0;
  3603. virtual ITracker& parent() = 0;
  3604. // actions
  3605. virtual void close() = 0; // Successfully complete
  3606. virtual void fail() = 0;
  3607. virtual void markAsNeedingAnotherRun() = 0;
  3608. virtual void addChild( ITrackerPtr const& child ) = 0;
  3609. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  3610. virtual void openChild() = 0;
  3611. // Debug/ checking
  3612. virtual bool isSectionTracker() const = 0;
  3613. virtual bool isIndexTracker() const = 0;
  3614. };
  3615. class TrackerContext {
  3616. enum RunState {
  3617. NotStarted,
  3618. Executing,
  3619. CompletedCycle
  3620. };
  3621. ITrackerPtr m_rootTracker;
  3622. ITracker* m_currentTracker = nullptr;
  3623. RunState m_runState = NotStarted;
  3624. public:
  3625. static TrackerContext& instance();
  3626. ITracker& startRun();
  3627. void endRun();
  3628. void startCycle();
  3629. void completeCycle();
  3630. bool completedCycle() const;
  3631. ITracker& currentTracker();
  3632. void setCurrentTracker( ITracker* tracker );
  3633. };
  3634. class TrackerBase : public ITracker {
  3635. protected:
  3636. enum CycleState {
  3637. NotStarted,
  3638. Executing,
  3639. ExecutingChildren,
  3640. NeedsAnotherRun,
  3641. CompletedSuccessfully,
  3642. Failed
  3643. };
  3644. class TrackerHasName {
  3645. NameAndLocation m_nameAndLocation;
  3646. public:
  3647. TrackerHasName( NameAndLocation const& nameAndLocation );
  3648. bool operator ()( ITrackerPtr const& tracker ) const;
  3649. };
  3650. using Children = std::vector<ITrackerPtr>;
  3651. NameAndLocation m_nameAndLocation;
  3652. TrackerContext& m_ctx;
  3653. ITracker* m_parent;
  3654. Children m_children;
  3655. CycleState m_runState = NotStarted;
  3656. public:
  3657. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3658. NameAndLocation const& nameAndLocation() const override;
  3659. bool isComplete() const override;
  3660. bool isSuccessfullyCompleted() const override;
  3661. bool isOpen() const override;
  3662. bool hasChildren() const override;
  3663. void addChild( ITrackerPtr const& child ) override;
  3664. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  3665. ITracker& parent() override;
  3666. void openChild() override;
  3667. bool isSectionTracker() const override;
  3668. bool isIndexTracker() const override;
  3669. void open();
  3670. void close() override;
  3671. void fail() override;
  3672. void markAsNeedingAnotherRun() override;
  3673. private:
  3674. void moveToParent();
  3675. void moveToThis();
  3676. };
  3677. class SectionTracker : public TrackerBase {
  3678. std::vector<std::string> m_filters;
  3679. public:
  3680. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3681. bool isSectionTracker() const override;
  3682. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  3683. void tryOpen();
  3684. void addInitialFilters( std::vector<std::string> const& filters );
  3685. void addNextFilters( std::vector<std::string> const& filters );
  3686. };
  3687. class IndexTracker : public TrackerBase {
  3688. int m_size;
  3689. int m_index = -1;
  3690. public:
  3691. IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size );
  3692. bool isIndexTracker() const override;
  3693. void close() override;
  3694. static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size );
  3695. int index() const;
  3696. void moveNext();
  3697. };
  3698. } // namespace TestCaseTracking
  3699. using TestCaseTracking::ITracker;
  3700. using TestCaseTracking::TrackerContext;
  3701. using TestCaseTracking::SectionTracker;
  3702. using TestCaseTracking::IndexTracker;
  3703. } // namespace Catch
  3704. // end catch_test_case_tracker.h
  3705. // start catch_leak_detector.h
  3706. namespace Catch {
  3707. struct LeakDetector {
  3708. LeakDetector();
  3709. };
  3710. }
  3711. // end catch_leak_detector.h
  3712. // Cpp files will be included in the single-header file here
  3713. // start catch_approx.cpp
  3714. #include <cmath>
  3715. #include <limits>
  3716. namespace {
  3717. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  3718. // But without the subtraction to allow for INFINITY in comparison
  3719. bool marginComparison(double lhs, double rhs, double margin) {
  3720. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  3721. }
  3722. }
  3723. namespace Catch {
  3724. namespace Detail {
  3725. Approx::Approx ( double value )
  3726. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  3727. m_margin( 0.0 ),
  3728. m_scale( 0.0 ),
  3729. m_value( value )
  3730. {}
  3731. Approx Approx::custom() {
  3732. return Approx( 0 );
  3733. }
  3734. Approx Approx::operator-() const {
  3735. auto temp(*this);
  3736. temp.m_value = -temp.m_value;
  3737. return temp;
  3738. }
  3739. std::string Approx::toString() const {
  3740. ReusableStringStream rss;
  3741. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  3742. return rss.str();
  3743. }
  3744. bool Approx::equalityComparisonImpl(const double other) const {
  3745. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  3746. // Thanks to Richard Harris for his help refining the scaled margin value
  3747. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  3748. }
  3749. } // end namespace Detail
  3750. namespace literals {
  3751. Detail::Approx operator "" _a(long double val) {
  3752. return Detail::Approx(val);
  3753. }
  3754. Detail::Approx operator "" _a(unsigned long long val) {
  3755. return Detail::Approx(val);
  3756. }
  3757. } // end namespace literals
  3758. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  3759. return value.toString();
  3760. }
  3761. } // end namespace Catch
  3762. // end catch_approx.cpp
  3763. // start catch_assertionhandler.cpp
  3764. // start catch_context.h
  3765. #include <memory>
  3766. namespace Catch {
  3767. struct IResultCapture;
  3768. struct IRunner;
  3769. struct IConfig;
  3770. struct IMutableContext;
  3771. using IConfigPtr = std::shared_ptr<IConfig const>;
  3772. struct IContext
  3773. {
  3774. virtual ~IContext();
  3775. virtual IResultCapture* getResultCapture() = 0;
  3776. virtual IRunner* getRunner() = 0;
  3777. virtual IConfigPtr const& getConfig() const = 0;
  3778. };
  3779. struct IMutableContext : IContext
  3780. {
  3781. virtual ~IMutableContext();
  3782. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  3783. virtual void setRunner( IRunner* runner ) = 0;
  3784. virtual void setConfig( IConfigPtr const& config ) = 0;
  3785. private:
  3786. static IMutableContext *currentContext;
  3787. friend IMutableContext& getCurrentMutableContext();
  3788. friend void cleanUpContext();
  3789. static void createContext();
  3790. };
  3791. inline IMutableContext& getCurrentMutableContext()
  3792. {
  3793. if( !IMutableContext::currentContext )
  3794. IMutableContext::createContext();
  3795. return *IMutableContext::currentContext;
  3796. }
  3797. inline IContext& getCurrentContext()
  3798. {
  3799. return getCurrentMutableContext();
  3800. }
  3801. void cleanUpContext();
  3802. }
  3803. // end catch_context.h
  3804. // start catch_debugger.h
  3805. namespace Catch {
  3806. bool isDebuggerActive();
  3807. }
  3808. #ifdef CATCH_PLATFORM_MAC
  3809. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  3810. #elif defined(CATCH_PLATFORM_LINUX)
  3811. // If we can use inline assembler, do it because this allows us to break
  3812. // directly at the location of the failing check instead of breaking inside
  3813. // raise() called from it, i.e. one stack frame below.
  3814. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  3815. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  3816. #else // Fall back to the generic way.
  3817. #include <signal.h>
  3818. #define CATCH_TRAP() raise(SIGTRAP)
  3819. #endif
  3820. #elif defined(_MSC_VER)
  3821. #define CATCH_TRAP() __debugbreak()
  3822. #elif defined(__MINGW32__)
  3823. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  3824. #define CATCH_TRAP() DebugBreak()
  3825. #endif
  3826. #ifdef CATCH_TRAP
  3827. #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
  3828. #else
  3829. namespace Catch {
  3830. inline void doNothing() {}
  3831. }
  3832. #define CATCH_BREAK_INTO_DEBUGGER() Catch::doNothing()
  3833. #endif
  3834. // end catch_debugger.h
  3835. // start catch_run_context.h
  3836. // start catch_fatal_condition.h
  3837. // start catch_windows_h_proxy.h
  3838. #if defined(CATCH_PLATFORM_WINDOWS)
  3839. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  3840. # define CATCH_DEFINED_NOMINMAX
  3841. # define NOMINMAX
  3842. #endif
  3843. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  3844. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  3845. # define WIN32_LEAN_AND_MEAN
  3846. #endif
  3847. #ifdef __AFXDLL
  3848. #include <AfxWin.h>
  3849. #else
  3850. #include <windows.h>
  3851. #endif
  3852. #ifdef CATCH_DEFINED_NOMINMAX
  3853. # undef NOMINMAX
  3854. #endif
  3855. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  3856. # undef WIN32_LEAN_AND_MEAN
  3857. #endif
  3858. #endif // defined(CATCH_PLATFORM_WINDOWS)
  3859. // end catch_windows_h_proxy.h
  3860. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  3861. namespace Catch {
  3862. struct FatalConditionHandler {
  3863. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  3864. FatalConditionHandler();
  3865. static void reset();
  3866. ~FatalConditionHandler();
  3867. private:
  3868. static bool isSet;
  3869. static ULONG guaranteeSize;
  3870. static PVOID exceptionHandlerHandle;
  3871. };
  3872. } // namespace Catch
  3873. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  3874. #include <signal.h>
  3875. namespace Catch {
  3876. struct FatalConditionHandler {
  3877. static bool isSet;
  3878. static struct sigaction oldSigActions[];
  3879. static stack_t oldSigStack;
  3880. static char altStackMem[];
  3881. static void handleSignal( int sig );
  3882. FatalConditionHandler();
  3883. ~FatalConditionHandler();
  3884. static void reset();
  3885. };
  3886. } // namespace Catch
  3887. #else
  3888. namespace Catch {
  3889. struct FatalConditionHandler {
  3890. void reset();
  3891. };
  3892. }
  3893. #endif
  3894. // end catch_fatal_condition.h
  3895. #include <string>
  3896. namespace Catch {
  3897. struct IMutableContext;
  3898. ///////////////////////////////////////////////////////////////////////////
  3899. class RunContext : public IResultCapture, public IRunner {
  3900. public:
  3901. RunContext( RunContext const& ) = delete;
  3902. RunContext& operator =( RunContext const& ) = delete;
  3903. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  3904. ~RunContext() override;
  3905. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  3906. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  3907. Totals runTest(TestCase const& testCase);
  3908. IConfigPtr config() const;
  3909. IStreamingReporter& reporter() const;
  3910. public: // IResultCapture
  3911. // Assertion handlers
  3912. void handleExpr
  3913. ( AssertionInfo const& info,
  3914. ITransientExpression const& expr,
  3915. AssertionReaction& reaction ) override;
  3916. void handleMessage
  3917. ( AssertionInfo const& info,
  3918. ResultWas::OfType resultType,
  3919. StringRef const& message,
  3920. AssertionReaction& reaction ) override;
  3921. void handleUnexpectedExceptionNotThrown
  3922. ( AssertionInfo const& info,
  3923. AssertionReaction& reaction ) override;
  3924. void handleUnexpectedInflightException
  3925. ( AssertionInfo const& info,
  3926. std::string const& message,
  3927. AssertionReaction& reaction ) override;
  3928. void handleIncomplete
  3929. ( AssertionInfo const& info ) override;
  3930. void handleNonExpr
  3931. ( AssertionInfo const &info,
  3932. ResultWas::OfType resultType,
  3933. AssertionReaction &reaction ) override;
  3934. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  3935. void sectionEnded( SectionEndInfo const& endInfo ) override;
  3936. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  3937. void benchmarkStarting( BenchmarkInfo const& info ) override;
  3938. void benchmarkEnded( BenchmarkStats const& stats ) override;
  3939. void pushScopedMessage( MessageInfo const& message ) override;
  3940. void popScopedMessage( MessageInfo const& message ) override;
  3941. std::string getCurrentTestName() const override;
  3942. const AssertionResult* getLastResult() const override;
  3943. void exceptionEarlyReported() override;
  3944. void handleFatalErrorCondition( StringRef message ) override;
  3945. bool lastAssertionPassed() override;
  3946. void assertionPassed() override;
  3947. public:
  3948. // !TBD We need to do this another way!
  3949. bool aborting() const final;
  3950. private:
  3951. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  3952. void invokeActiveTestCase();
  3953. void resetAssertionInfo();
  3954. bool testForMissingAssertions( Counts& assertions );
  3955. void assertionEnded( AssertionResult const& result );
  3956. void reportExpr
  3957. ( AssertionInfo const &info,
  3958. ResultWas::OfType resultType,
  3959. ITransientExpression const *expr,
  3960. bool negated );
  3961. void populateReaction( AssertionReaction& reaction );
  3962. private:
  3963. void handleUnfinishedSections();
  3964. TestRunInfo m_runInfo;
  3965. IMutableContext& m_context;
  3966. TestCase const* m_activeTestCase = nullptr;
  3967. ITracker* m_testCaseTracker;
  3968. Option<AssertionResult> m_lastResult;
  3969. IConfigPtr m_config;
  3970. Totals m_totals;
  3971. IStreamingReporterPtr m_reporter;
  3972. std::vector<MessageInfo> m_messages;
  3973. AssertionInfo m_lastAssertionInfo;
  3974. std::vector<SectionEndInfo> m_unfinishedSections;
  3975. std::vector<ITracker*> m_activeSections;
  3976. TrackerContext m_trackerContext;
  3977. bool m_lastAssertionPassed = false;
  3978. bool m_shouldReportUnexpected = true;
  3979. bool m_includeSuccessfulResults;
  3980. };
  3981. } // end namespace Catch
  3982. // end catch_run_context.h
  3983. namespace Catch {
  3984. namespace {
  3985. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  3986. expr.streamReconstructedExpression( os );
  3987. return os;
  3988. }
  3989. }
  3990. LazyExpression::LazyExpression( bool isNegated )
  3991. : m_isNegated( isNegated )
  3992. {}
  3993. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  3994. LazyExpression::operator bool() const {
  3995. return m_transientExpression != nullptr;
  3996. }
  3997. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  3998. if( lazyExpr.m_isNegated )
  3999. os << "!";
  4000. if( lazyExpr ) {
  4001. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  4002. os << "(" << *lazyExpr.m_transientExpression << ")";
  4003. else
  4004. os << *lazyExpr.m_transientExpression;
  4005. }
  4006. else {
  4007. os << "{** error - unchecked empty expression requested **}";
  4008. }
  4009. return os;
  4010. }
  4011. AssertionHandler::AssertionHandler
  4012. ( StringRef macroName,
  4013. SourceLineInfo const& lineInfo,
  4014. StringRef capturedExpression,
  4015. ResultDisposition::Flags resultDisposition )
  4016. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  4017. m_resultCapture( getResultCapture() )
  4018. {}
  4019. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  4020. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  4021. }
  4022. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  4023. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  4024. }
  4025. auto AssertionHandler::allowThrows() const -> bool {
  4026. return getCurrentContext().getConfig()->allowThrows();
  4027. }
  4028. void AssertionHandler::complete() {
  4029. setCompleted();
  4030. if( m_reaction.shouldDebugBreak ) {
  4031. // If you find your debugger stopping you here then go one level up on the
  4032. // call-stack for the code that caused it (typically a failed assertion)
  4033. // (To go back to the test and change execution, jump over the throw, next)
  4034. CATCH_BREAK_INTO_DEBUGGER();
  4035. }
  4036. if( m_reaction.shouldThrow )
  4037. throw Catch::TestFailureException();
  4038. }
  4039. void AssertionHandler::setCompleted() {
  4040. m_completed = true;
  4041. }
  4042. void AssertionHandler::handleUnexpectedInflightException() {
  4043. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  4044. }
  4045. void AssertionHandler::handleExceptionThrownAsExpected() {
  4046. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4047. }
  4048. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  4049. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4050. }
  4051. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  4052. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  4053. }
  4054. void AssertionHandler::handleThrowingCallSkipped() {
  4055. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4056. }
  4057. // This is the overload that takes a string and infers the Equals matcher from it
  4058. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  4059. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef matcherString ) {
  4060. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  4061. }
  4062. } // namespace Catch
  4063. // end catch_assertionhandler.cpp
  4064. // start catch_assertionresult.cpp
  4065. namespace Catch {
  4066. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  4067. lazyExpression(_lazyExpression),
  4068. resultType(_resultType) {}
  4069. std::string AssertionResultData::reconstructExpression() const {
  4070. if( reconstructedExpression.empty() ) {
  4071. if( lazyExpression ) {
  4072. ReusableStringStream rss;
  4073. rss << lazyExpression;
  4074. reconstructedExpression = rss.str();
  4075. }
  4076. }
  4077. return reconstructedExpression;
  4078. }
  4079. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  4080. : m_info( info ),
  4081. m_resultData( data )
  4082. {}
  4083. // Result was a success
  4084. bool AssertionResult::succeeded() const {
  4085. return Catch::isOk( m_resultData.resultType );
  4086. }
  4087. // Result was a success, or failure is suppressed
  4088. bool AssertionResult::isOk() const {
  4089. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  4090. }
  4091. ResultWas::OfType AssertionResult::getResultType() const {
  4092. return m_resultData.resultType;
  4093. }
  4094. bool AssertionResult::hasExpression() const {
  4095. return m_info.capturedExpression[0] != 0;
  4096. }
  4097. bool AssertionResult::hasMessage() const {
  4098. return !m_resultData.message.empty();
  4099. }
  4100. std::string AssertionResult::getExpression() const {
  4101. if( isFalseTest( m_info.resultDisposition ) )
  4102. return "!(" + m_info.capturedExpression + ")";
  4103. else
  4104. return m_info.capturedExpression;
  4105. }
  4106. std::string AssertionResult::getExpressionInMacro() const {
  4107. std::string expr;
  4108. if( m_info.macroName[0] == 0 )
  4109. expr = m_info.capturedExpression;
  4110. else {
  4111. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  4112. expr += m_info.macroName;
  4113. expr += "( ";
  4114. expr += m_info.capturedExpression;
  4115. expr += " )";
  4116. }
  4117. return expr;
  4118. }
  4119. bool AssertionResult::hasExpandedExpression() const {
  4120. return hasExpression() && getExpandedExpression() != getExpression();
  4121. }
  4122. std::string AssertionResult::getExpandedExpression() const {
  4123. std::string expr = m_resultData.reconstructExpression();
  4124. return expr.empty()
  4125. ? getExpression()
  4126. : expr;
  4127. }
  4128. std::string AssertionResult::getMessage() const {
  4129. return m_resultData.message;
  4130. }
  4131. SourceLineInfo AssertionResult::getSourceInfo() const {
  4132. return m_info.lineInfo;
  4133. }
  4134. StringRef AssertionResult::getTestMacroName() const {
  4135. return m_info.macroName;
  4136. }
  4137. } // end namespace Catch
  4138. // end catch_assertionresult.cpp
  4139. // start catch_benchmark.cpp
  4140. namespace Catch {
  4141. auto BenchmarkLooper::getResolution() -> uint64_t {
  4142. return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
  4143. }
  4144. void BenchmarkLooper::reportStart() {
  4145. getResultCapture().benchmarkStarting( { m_name } );
  4146. }
  4147. auto BenchmarkLooper::needsMoreIterations() -> bool {
  4148. auto elapsed = m_timer.getElapsedNanoseconds();
  4149. // Exponentially increasing iterations until we're confident in our timer resolution
  4150. if( elapsed < m_resolution ) {
  4151. m_iterationsToRun *= 10;
  4152. return true;
  4153. }
  4154. getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
  4155. return false;
  4156. }
  4157. } // end namespace Catch
  4158. // end catch_benchmark.cpp
  4159. // start catch_capture_matchers.cpp
  4160. namespace Catch {
  4161. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  4162. // This is the general overload that takes a any string matcher
  4163. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  4164. // the Equals matcher (so the header does not mention matchers)
  4165. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef matcherString ) {
  4166. std::string exceptionMessage = Catch::translateActiveException();
  4167. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  4168. handler.handleExpr( expr );
  4169. }
  4170. } // namespace Catch
  4171. // end catch_capture_matchers.cpp
  4172. // start catch_commandline.cpp
  4173. // start catch_commandline.h
  4174. // start catch_clara.h
  4175. // Use Catch's value for console width (store Clara's off to the side, if present)
  4176. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  4177. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4178. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4179. #endif
  4180. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  4181. #ifdef __clang__
  4182. #pragma clang diagnostic push
  4183. #pragma clang diagnostic ignored "-Wweak-vtables"
  4184. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  4185. #pragma clang diagnostic ignored "-Wshadow"
  4186. #endif
  4187. // start clara.hpp
  4188. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  4189. //
  4190. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4191. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4192. //
  4193. // See https://github.com/philsquared/Clara for more details
  4194. // Clara v1.1.4
  4195. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4196. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  4197. #endif
  4198. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4199. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4200. #endif
  4201. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  4202. #ifdef __has_include
  4203. #if __has_include(<optional>) && __cplusplus >= 201703L
  4204. #include <optional>
  4205. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  4206. #endif
  4207. #endif
  4208. #endif
  4209. // ----------- #included from clara_textflow.hpp -----------
  4210. // TextFlowCpp
  4211. //
  4212. // A single-header library for wrapping and laying out basic text, by Phil Nash
  4213. //
  4214. // This work is licensed under the BSD 2-Clause license.
  4215. // See the accompanying LICENSE file, or the one at https://opensource.org/licenses/BSD-2-Clause
  4216. //
  4217. // This project is hosted at https://github.com/philsquared/textflowcpp
  4218. #include <cassert>
  4219. #include <ostream>
  4220. #include <sstream>
  4221. #include <vector>
  4222. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4223. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  4224. #endif
  4225. namespace Catch { namespace clara { namespace TextFlow {
  4226. inline auto isWhitespace( char c ) -> bool {
  4227. static std::string chars = " \t\n\r";
  4228. return chars.find( c ) != std::string::npos;
  4229. }
  4230. inline auto isBreakableBefore( char c ) -> bool {
  4231. static std::string chars = "[({<|";
  4232. return chars.find( c ) != std::string::npos;
  4233. }
  4234. inline auto isBreakableAfter( char c ) -> bool {
  4235. static std::string chars = "])}>.,:;*+-=&/\\";
  4236. return chars.find( c ) != std::string::npos;
  4237. }
  4238. class Columns;
  4239. class Column {
  4240. std::vector<std::string> m_strings;
  4241. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  4242. size_t m_indent = 0;
  4243. size_t m_initialIndent = std::string::npos;
  4244. public:
  4245. class iterator {
  4246. friend Column;
  4247. Column const& m_column;
  4248. size_t m_stringIndex = 0;
  4249. size_t m_pos = 0;
  4250. size_t m_len = 0;
  4251. size_t m_end = 0;
  4252. bool m_suffix = false;
  4253. iterator( Column const& column, size_t stringIndex )
  4254. : m_column( column ),
  4255. m_stringIndex( stringIndex )
  4256. {}
  4257. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  4258. auto isBoundary( size_t at ) const -> bool {
  4259. assert( at > 0 );
  4260. assert( at <= line().size() );
  4261. return at == line().size() ||
  4262. ( isWhitespace( line()[at] ) && !isWhitespace( line()[at-1] ) ) ||
  4263. isBreakableBefore( line()[at] ) ||
  4264. isBreakableAfter( line()[at-1] );
  4265. }
  4266. void calcLength() {
  4267. assert( m_stringIndex < m_column.m_strings.size() );
  4268. m_suffix = false;
  4269. auto width = m_column.m_width-indent();
  4270. m_end = m_pos;
  4271. while( m_end < line().size() && line()[m_end] != '\n' )
  4272. ++m_end;
  4273. if( m_end < m_pos + width ) {
  4274. m_len = m_end - m_pos;
  4275. }
  4276. else {
  4277. size_t len = width;
  4278. while (len > 0 && !isBoundary(m_pos + len))
  4279. --len;
  4280. while (len > 0 && isWhitespace( line()[m_pos + len - 1] ))
  4281. --len;
  4282. if (len > 0) {
  4283. m_len = len;
  4284. } else {
  4285. m_suffix = true;
  4286. m_len = width - 1;
  4287. }
  4288. }
  4289. }
  4290. auto indent() const -> size_t {
  4291. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  4292. return initial == std::string::npos ? m_column.m_indent : initial;
  4293. }
  4294. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  4295. return std::string( indent(), ' ' ) + (m_suffix ? plain + "-" : plain);
  4296. }
  4297. public:
  4298. explicit iterator( Column const& column ) : m_column( column ) {
  4299. assert( m_column.m_width > m_column.m_indent );
  4300. assert( m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent );
  4301. calcLength();
  4302. if( m_len == 0 )
  4303. m_stringIndex++; // Empty string
  4304. }
  4305. auto operator *() const -> std::string {
  4306. assert( m_stringIndex < m_column.m_strings.size() );
  4307. assert( m_pos <= m_end );
  4308. if( m_pos + m_column.m_width < m_end )
  4309. return addIndentAndSuffix(line().substr(m_pos, m_len));
  4310. else
  4311. return addIndentAndSuffix(line().substr(m_pos, m_end - m_pos));
  4312. }
  4313. auto operator ++() -> iterator& {
  4314. m_pos += m_len;
  4315. if( m_pos < line().size() && line()[m_pos] == '\n' )
  4316. m_pos += 1;
  4317. else
  4318. while( m_pos < line().size() && isWhitespace( line()[m_pos] ) )
  4319. ++m_pos;
  4320. if( m_pos == line().size() ) {
  4321. m_pos = 0;
  4322. ++m_stringIndex;
  4323. }
  4324. if( m_stringIndex < m_column.m_strings.size() )
  4325. calcLength();
  4326. return *this;
  4327. }
  4328. auto operator ++(int) -> iterator {
  4329. iterator prev( *this );
  4330. operator++();
  4331. return prev;
  4332. }
  4333. auto operator ==( iterator const& other ) const -> bool {
  4334. return
  4335. m_pos == other.m_pos &&
  4336. m_stringIndex == other.m_stringIndex &&
  4337. &m_column == &other.m_column;
  4338. }
  4339. auto operator !=( iterator const& other ) const -> bool {
  4340. return !operator==( other );
  4341. }
  4342. };
  4343. using const_iterator = iterator;
  4344. explicit Column( std::string const& text ) { m_strings.push_back( text ); }
  4345. auto width( size_t newWidth ) -> Column& {
  4346. assert( newWidth > 0 );
  4347. m_width = newWidth;
  4348. return *this;
  4349. }
  4350. auto indent( size_t newIndent ) -> Column& {
  4351. m_indent = newIndent;
  4352. return *this;
  4353. }
  4354. auto initialIndent( size_t newIndent ) -> Column& {
  4355. m_initialIndent = newIndent;
  4356. return *this;
  4357. }
  4358. auto width() const -> size_t { return m_width; }
  4359. auto begin() const -> iterator { return iterator( *this ); }
  4360. auto end() const -> iterator { return { *this, m_strings.size() }; }
  4361. inline friend std::ostream& operator << ( std::ostream& os, Column const& col ) {
  4362. bool first = true;
  4363. for( auto line : col ) {
  4364. if( first )
  4365. first = false;
  4366. else
  4367. os << "\n";
  4368. os << line;
  4369. }
  4370. return os;
  4371. }
  4372. auto operator + ( Column const& other ) -> Columns;
  4373. auto toString() const -> std::string {
  4374. std::ostringstream oss;
  4375. oss << *this;
  4376. return oss.str();
  4377. }
  4378. };
  4379. class Spacer : public Column {
  4380. public:
  4381. explicit Spacer( size_t spaceWidth ) : Column( "" ) {
  4382. width( spaceWidth );
  4383. }
  4384. };
  4385. class Columns {
  4386. std::vector<Column> m_columns;
  4387. public:
  4388. class iterator {
  4389. friend Columns;
  4390. struct EndTag {};
  4391. std::vector<Column> const& m_columns;
  4392. std::vector<Column::iterator> m_iterators;
  4393. size_t m_activeIterators;
  4394. iterator( Columns const& columns, EndTag )
  4395. : m_columns( columns.m_columns ),
  4396. m_activeIterators( 0 )
  4397. {
  4398. m_iterators.reserve( m_columns.size() );
  4399. for( auto const& col : m_columns )
  4400. m_iterators.push_back( col.end() );
  4401. }
  4402. public:
  4403. explicit iterator( Columns const& columns )
  4404. : m_columns( columns.m_columns ),
  4405. m_activeIterators( m_columns.size() )
  4406. {
  4407. m_iterators.reserve( m_columns.size() );
  4408. for( auto const& col : m_columns )
  4409. m_iterators.push_back( col.begin() );
  4410. }
  4411. auto operator ==( iterator const& other ) const -> bool {
  4412. return m_iterators == other.m_iterators;
  4413. }
  4414. auto operator !=( iterator const& other ) const -> bool {
  4415. return m_iterators != other.m_iterators;
  4416. }
  4417. auto operator *() const -> std::string {
  4418. std::string row, padding;
  4419. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4420. auto width = m_columns[i].width();
  4421. if( m_iterators[i] != m_columns[i].end() ) {
  4422. std::string col = *m_iterators[i];
  4423. row += padding + col;
  4424. if( col.size() < width )
  4425. padding = std::string( width - col.size(), ' ' );
  4426. else
  4427. padding = "";
  4428. }
  4429. else {
  4430. padding += std::string( width, ' ' );
  4431. }
  4432. }
  4433. return row;
  4434. }
  4435. auto operator ++() -> iterator& {
  4436. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4437. if (m_iterators[i] != m_columns[i].end())
  4438. ++m_iterators[i];
  4439. }
  4440. return *this;
  4441. }
  4442. auto operator ++(int) -> iterator {
  4443. iterator prev( *this );
  4444. operator++();
  4445. return prev;
  4446. }
  4447. };
  4448. using const_iterator = iterator;
  4449. auto begin() const -> iterator { return iterator( *this ); }
  4450. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  4451. auto operator += ( Column const& col ) -> Columns& {
  4452. m_columns.push_back( col );
  4453. return *this;
  4454. }
  4455. auto operator + ( Column const& col ) -> Columns {
  4456. Columns combined = *this;
  4457. combined += col;
  4458. return combined;
  4459. }
  4460. inline friend std::ostream& operator << ( std::ostream& os, Columns const& cols ) {
  4461. bool first = true;
  4462. for( auto line : cols ) {
  4463. if( first )
  4464. first = false;
  4465. else
  4466. os << "\n";
  4467. os << line;
  4468. }
  4469. return os;
  4470. }
  4471. auto toString() const -> std::string {
  4472. std::ostringstream oss;
  4473. oss << *this;
  4474. return oss.str();
  4475. }
  4476. };
  4477. inline auto Column::operator + ( Column const& other ) -> Columns {
  4478. Columns cols;
  4479. cols += *this;
  4480. cols += other;
  4481. return cols;
  4482. }
  4483. }}} // namespace Catch::clara::TextFlow
  4484. // ----------- end of #include from clara_textflow.hpp -----------
  4485. // ........... back in clara.hpp
  4486. #include <memory>
  4487. #include <set>
  4488. #include <algorithm>
  4489. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  4490. #define CATCH_PLATFORM_WINDOWS
  4491. #endif
  4492. namespace Catch { namespace clara {
  4493. namespace detail {
  4494. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  4495. template<typename L>
  4496. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  4497. template<typename ClassT, typename ReturnT, typename... Args>
  4498. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  4499. static const bool isValid = false;
  4500. };
  4501. template<typename ClassT, typename ReturnT, typename ArgT>
  4502. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  4503. static const bool isValid = true;
  4504. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  4505. using ReturnType = ReturnT;
  4506. };
  4507. class TokenStream;
  4508. // Transport for raw args (copied from main args, or supplied via init list for testing)
  4509. class Args {
  4510. friend TokenStream;
  4511. std::string m_exeName;
  4512. std::vector<std::string> m_args;
  4513. public:
  4514. Args( int argc, char const* const* argv )
  4515. : m_exeName(argv[0]),
  4516. m_args(argv + 1, argv + argc) {}
  4517. Args( std::initializer_list<std::string> args )
  4518. : m_exeName( *args.begin() ),
  4519. m_args( args.begin()+1, args.end() )
  4520. {}
  4521. auto exeName() const -> std::string {
  4522. return m_exeName;
  4523. }
  4524. };
  4525. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  4526. // may encode an option + its argument if the : or = form is used
  4527. enum class TokenType {
  4528. Option, Argument
  4529. };
  4530. struct Token {
  4531. TokenType type;
  4532. std::string token;
  4533. };
  4534. inline auto isOptPrefix( char c ) -> bool {
  4535. return c == '-'
  4536. #ifdef CATCH_PLATFORM_WINDOWS
  4537. || c == '/'
  4538. #endif
  4539. ;
  4540. }
  4541. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  4542. class TokenStream {
  4543. using Iterator = std::vector<std::string>::const_iterator;
  4544. Iterator it;
  4545. Iterator itEnd;
  4546. std::vector<Token> m_tokenBuffer;
  4547. void loadBuffer() {
  4548. m_tokenBuffer.resize( 0 );
  4549. // Skip any empty strings
  4550. while( it != itEnd && it->empty() )
  4551. ++it;
  4552. if( it != itEnd ) {
  4553. auto const &next = *it;
  4554. if( isOptPrefix( next[0] ) ) {
  4555. auto delimiterPos = next.find_first_of( " :=" );
  4556. if( delimiterPos != std::string::npos ) {
  4557. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  4558. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  4559. } else {
  4560. if( next[1] != '-' && next.size() > 2 ) {
  4561. std::string opt = "- ";
  4562. for( size_t i = 1; i < next.size(); ++i ) {
  4563. opt[1] = next[i];
  4564. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  4565. }
  4566. } else {
  4567. m_tokenBuffer.push_back( { TokenType::Option, next } );
  4568. }
  4569. }
  4570. } else {
  4571. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  4572. }
  4573. }
  4574. }
  4575. public:
  4576. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  4577. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  4578. loadBuffer();
  4579. }
  4580. explicit operator bool() const {
  4581. return !m_tokenBuffer.empty() || it != itEnd;
  4582. }
  4583. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  4584. auto operator*() const -> Token {
  4585. assert( !m_tokenBuffer.empty() );
  4586. return m_tokenBuffer.front();
  4587. }
  4588. auto operator->() const -> Token const * {
  4589. assert( !m_tokenBuffer.empty() );
  4590. return &m_tokenBuffer.front();
  4591. }
  4592. auto operator++() -> TokenStream & {
  4593. if( m_tokenBuffer.size() >= 2 ) {
  4594. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  4595. } else {
  4596. if( it != itEnd )
  4597. ++it;
  4598. loadBuffer();
  4599. }
  4600. return *this;
  4601. }
  4602. };
  4603. class ResultBase {
  4604. public:
  4605. enum Type {
  4606. Ok, LogicError, RuntimeError
  4607. };
  4608. protected:
  4609. ResultBase( Type type ) : m_type( type ) {}
  4610. virtual ~ResultBase() = default;
  4611. virtual void enforceOk() const = 0;
  4612. Type m_type;
  4613. };
  4614. template<typename T>
  4615. class ResultValueBase : public ResultBase {
  4616. public:
  4617. auto value() const -> T const & {
  4618. enforceOk();
  4619. return m_value;
  4620. }
  4621. protected:
  4622. ResultValueBase( Type type ) : ResultBase( type ) {}
  4623. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  4624. if( m_type == ResultBase::Ok )
  4625. new( &m_value ) T( other.m_value );
  4626. }
  4627. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  4628. new( &m_value ) T( value );
  4629. }
  4630. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  4631. if( m_type == ResultBase::Ok )
  4632. m_value.~T();
  4633. ResultBase::operator=(other);
  4634. if( m_type == ResultBase::Ok )
  4635. new( &m_value ) T( other.m_value );
  4636. return *this;
  4637. }
  4638. ~ResultValueBase() override {
  4639. if( m_type == Ok )
  4640. m_value.~T();
  4641. }
  4642. union {
  4643. T m_value;
  4644. };
  4645. };
  4646. template<>
  4647. class ResultValueBase<void> : public ResultBase {
  4648. protected:
  4649. using ResultBase::ResultBase;
  4650. };
  4651. template<typename T = void>
  4652. class BasicResult : public ResultValueBase<T> {
  4653. public:
  4654. template<typename U>
  4655. explicit BasicResult( BasicResult<U> const &other )
  4656. : ResultValueBase<T>( other.type() ),
  4657. m_errorMessage( other.errorMessage() )
  4658. {
  4659. assert( type() != ResultBase::Ok );
  4660. }
  4661. template<typename U>
  4662. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  4663. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  4664. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  4665. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  4666. explicit operator bool() const { return m_type == ResultBase::Ok; }
  4667. auto type() const -> ResultBase::Type { return m_type; }
  4668. auto errorMessage() const -> std::string { return m_errorMessage; }
  4669. protected:
  4670. void enforceOk() const override {
  4671. // Errors shouldn't reach this point, but if they do
  4672. // the actual error message will be in m_errorMessage
  4673. assert( m_type != ResultBase::LogicError );
  4674. assert( m_type != ResultBase::RuntimeError );
  4675. if( m_type != ResultBase::Ok )
  4676. std::abort();
  4677. }
  4678. std::string m_errorMessage; // Only populated if resultType is an error
  4679. BasicResult( ResultBase::Type type, std::string const &message )
  4680. : ResultValueBase<T>(type),
  4681. m_errorMessage(message)
  4682. {
  4683. assert( m_type != ResultBase::Ok );
  4684. }
  4685. using ResultValueBase<T>::ResultValueBase;
  4686. using ResultBase::m_type;
  4687. };
  4688. enum class ParseResultType {
  4689. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  4690. };
  4691. class ParseState {
  4692. public:
  4693. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  4694. : m_type(type),
  4695. m_remainingTokens( remainingTokens )
  4696. {}
  4697. auto type() const -> ParseResultType { return m_type; }
  4698. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  4699. private:
  4700. ParseResultType m_type;
  4701. TokenStream m_remainingTokens;
  4702. };
  4703. using Result = BasicResult<void>;
  4704. using ParserResult = BasicResult<ParseResultType>;
  4705. using InternalParseResult = BasicResult<ParseState>;
  4706. struct HelpColumns {
  4707. std::string left;
  4708. std::string right;
  4709. };
  4710. template<typename T>
  4711. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  4712. std::stringstream ss;
  4713. ss << source;
  4714. ss >> target;
  4715. if( ss.fail() )
  4716. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  4717. else
  4718. return ParserResult::ok( ParseResultType::Matched );
  4719. }
  4720. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  4721. target = source;
  4722. return ParserResult::ok( ParseResultType::Matched );
  4723. }
  4724. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  4725. std::string srcLC = source;
  4726. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( ::tolower(c) ); } );
  4727. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  4728. target = true;
  4729. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  4730. target = false;
  4731. else
  4732. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  4733. return ParserResult::ok( ParseResultType::Matched );
  4734. }
  4735. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  4736. template<typename T>
  4737. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  4738. T temp;
  4739. auto result = convertInto( source, temp );
  4740. if( result )
  4741. target = std::move(temp);
  4742. return result;
  4743. }
  4744. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  4745. struct NonCopyable {
  4746. NonCopyable() = default;
  4747. NonCopyable( NonCopyable const & ) = delete;
  4748. NonCopyable( NonCopyable && ) = delete;
  4749. NonCopyable &operator=( NonCopyable const & ) = delete;
  4750. NonCopyable &operator=( NonCopyable && ) = delete;
  4751. };
  4752. struct BoundRef : NonCopyable {
  4753. virtual ~BoundRef() = default;
  4754. virtual auto isContainer() const -> bool { return false; }
  4755. virtual auto isFlag() const -> bool { return false; }
  4756. };
  4757. struct BoundValueRefBase : BoundRef {
  4758. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  4759. };
  4760. struct BoundFlagRefBase : BoundRef {
  4761. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  4762. virtual auto isFlag() const -> bool { return true; }
  4763. };
  4764. template<typename T>
  4765. struct BoundValueRef : BoundValueRefBase {
  4766. T &m_ref;
  4767. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  4768. auto setValue( std::string const &arg ) -> ParserResult override {
  4769. return convertInto( arg, m_ref );
  4770. }
  4771. };
  4772. template<typename T>
  4773. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  4774. std::vector<T> &m_ref;
  4775. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  4776. auto isContainer() const -> bool override { return true; }
  4777. auto setValue( std::string const &arg ) -> ParserResult override {
  4778. T temp;
  4779. auto result = convertInto( arg, temp );
  4780. if( result )
  4781. m_ref.push_back( temp );
  4782. return result;
  4783. }
  4784. };
  4785. struct BoundFlagRef : BoundFlagRefBase {
  4786. bool &m_ref;
  4787. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  4788. auto setFlag( bool flag ) -> ParserResult override {
  4789. m_ref = flag;
  4790. return ParserResult::ok( ParseResultType::Matched );
  4791. }
  4792. };
  4793. template<typename ReturnType>
  4794. struct LambdaInvoker {
  4795. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  4796. template<typename L, typename ArgType>
  4797. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4798. return lambda( arg );
  4799. }
  4800. };
  4801. template<>
  4802. struct LambdaInvoker<void> {
  4803. template<typename L, typename ArgType>
  4804. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  4805. lambda( arg );
  4806. return ParserResult::ok( ParseResultType::Matched );
  4807. }
  4808. };
  4809. template<typename ArgType, typename L>
  4810. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  4811. ArgType temp{};
  4812. auto result = convertInto( arg, temp );
  4813. return !result
  4814. ? result
  4815. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  4816. }
  4817. template<typename L>
  4818. struct BoundLambda : BoundValueRefBase {
  4819. L m_lambda;
  4820. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4821. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  4822. auto setValue( std::string const &arg ) -> ParserResult override {
  4823. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  4824. }
  4825. };
  4826. template<typename L>
  4827. struct BoundFlagLambda : BoundFlagRefBase {
  4828. L m_lambda;
  4829. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  4830. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  4831. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  4832. auto setFlag( bool flag ) -> ParserResult override {
  4833. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  4834. }
  4835. };
  4836. enum class Optionality { Optional, Required };
  4837. struct Parser;
  4838. class ParserBase {
  4839. public:
  4840. virtual ~ParserBase() = default;
  4841. virtual auto validate() const -> Result { return Result::ok(); }
  4842. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  4843. virtual auto cardinality() const -> size_t { return 1; }
  4844. auto parse( Args const &args ) const -> InternalParseResult {
  4845. return parse( args.exeName(), TokenStream( args ) );
  4846. }
  4847. };
  4848. template<typename DerivedT>
  4849. class ComposableParserImpl : public ParserBase {
  4850. public:
  4851. template<typename T>
  4852. auto operator|( T const &other ) const -> Parser;
  4853. template<typename T>
  4854. auto operator+( T const &other ) const -> Parser;
  4855. };
  4856. // Common code and state for Args and Opts
  4857. template<typename DerivedT>
  4858. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  4859. protected:
  4860. Optionality m_optionality = Optionality::Optional;
  4861. std::shared_ptr<BoundRef> m_ref;
  4862. std::string m_hint;
  4863. std::string m_description;
  4864. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  4865. public:
  4866. template<typename T>
  4867. ParserRefImpl( T &ref, std::string const &hint )
  4868. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  4869. m_hint( hint )
  4870. {}
  4871. template<typename LambdaT>
  4872. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  4873. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  4874. m_hint(hint)
  4875. {}
  4876. auto operator()( std::string const &description ) -> DerivedT & {
  4877. m_description = description;
  4878. return static_cast<DerivedT &>( *this );
  4879. }
  4880. auto optional() -> DerivedT & {
  4881. m_optionality = Optionality::Optional;
  4882. return static_cast<DerivedT &>( *this );
  4883. };
  4884. auto required() -> DerivedT & {
  4885. m_optionality = Optionality::Required;
  4886. return static_cast<DerivedT &>( *this );
  4887. };
  4888. auto isOptional() const -> bool {
  4889. return m_optionality == Optionality::Optional;
  4890. }
  4891. auto cardinality() const -> size_t override {
  4892. if( m_ref->isContainer() )
  4893. return 0;
  4894. else
  4895. return 1;
  4896. }
  4897. auto hint() const -> std::string { return m_hint; }
  4898. };
  4899. class ExeName : public ComposableParserImpl<ExeName> {
  4900. std::shared_ptr<std::string> m_name;
  4901. std::shared_ptr<BoundValueRefBase> m_ref;
  4902. template<typename LambdaT>
  4903. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  4904. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  4905. }
  4906. public:
  4907. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  4908. explicit ExeName( std::string &ref ) : ExeName() {
  4909. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  4910. }
  4911. template<typename LambdaT>
  4912. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  4913. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  4914. }
  4915. // The exe name is not parsed out of the normal tokens, but is handled specially
  4916. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4917. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  4918. }
  4919. auto name() const -> std::string { return *m_name; }
  4920. auto set( std::string const& newName ) -> ParserResult {
  4921. auto lastSlash = newName.find_last_of( "\\/" );
  4922. auto filename = ( lastSlash == std::string::npos )
  4923. ? newName
  4924. : newName.substr( lastSlash+1 );
  4925. *m_name = filename;
  4926. if( m_ref )
  4927. return m_ref->setValue( filename );
  4928. else
  4929. return ParserResult::ok( ParseResultType::Matched );
  4930. }
  4931. };
  4932. class Arg : public ParserRefImpl<Arg> {
  4933. public:
  4934. using ParserRefImpl::ParserRefImpl;
  4935. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  4936. auto validationResult = validate();
  4937. if( !validationResult )
  4938. return InternalParseResult( validationResult );
  4939. auto remainingTokens = tokens;
  4940. auto const &token = *remainingTokens;
  4941. if( token.type != TokenType::Argument )
  4942. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  4943. assert( !m_ref->isFlag() );
  4944. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  4945. auto result = valueRef->setValue( remainingTokens->token );
  4946. if( !result )
  4947. return InternalParseResult( result );
  4948. else
  4949. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  4950. }
  4951. };
  4952. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  4953. #ifdef CATCH_PLATFORM_WINDOWS
  4954. if( optName[0] == '/' )
  4955. return "-" + optName.substr( 1 );
  4956. else
  4957. #endif
  4958. return optName;
  4959. }
  4960. class Opt : public ParserRefImpl<Opt> {
  4961. protected:
  4962. std::vector<std::string> m_optNames;
  4963. public:
  4964. template<typename LambdaT>
  4965. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  4966. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  4967. template<typename LambdaT>
  4968. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4969. template<typename T>
  4970. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  4971. auto operator[]( std::string const &optName ) -> Opt & {
  4972. m_optNames.push_back( optName );
  4973. return *this;
  4974. }
  4975. auto getHelpColumns() const -> std::vector<HelpColumns> {
  4976. std::ostringstream oss;
  4977. bool first = true;
  4978. for( auto const &opt : m_optNames ) {
  4979. if (first)
  4980. first = false;
  4981. else
  4982. oss << ", ";
  4983. oss << opt;
  4984. }
  4985. if( !m_hint.empty() )
  4986. oss << " <" << m_hint << ">";
  4987. return { { oss.str(), m_description } };
  4988. }
  4989. auto isMatch( std::string const &optToken ) const -> bool {
  4990. auto normalisedToken = normaliseOpt( optToken );
  4991. for( auto const &name : m_optNames ) {
  4992. if( normaliseOpt( name ) == normalisedToken )
  4993. return true;
  4994. }
  4995. return false;
  4996. }
  4997. using ParserBase::parse;
  4998. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  4999. auto validationResult = validate();
  5000. if( !validationResult )
  5001. return InternalParseResult( validationResult );
  5002. auto remainingTokens = tokens;
  5003. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  5004. auto const &token = *remainingTokens;
  5005. if( isMatch(token.token ) ) {
  5006. if( m_ref->isFlag() ) {
  5007. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  5008. auto result = flagRef->setFlag( true );
  5009. if( !result )
  5010. return InternalParseResult( result );
  5011. if( result.value() == ParseResultType::ShortCircuitAll )
  5012. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  5013. } else {
  5014. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  5015. ++remainingTokens;
  5016. if( !remainingTokens )
  5017. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  5018. auto const &argToken = *remainingTokens;
  5019. if( argToken.type != TokenType::Argument )
  5020. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  5021. auto result = valueRef->setValue( argToken.token );
  5022. if( !result )
  5023. return InternalParseResult( result );
  5024. if( result.value() == ParseResultType::ShortCircuitAll )
  5025. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  5026. }
  5027. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  5028. }
  5029. }
  5030. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  5031. }
  5032. auto validate() const -> Result override {
  5033. if( m_optNames.empty() )
  5034. return Result::logicError( "No options supplied to Opt" );
  5035. for( auto const &name : m_optNames ) {
  5036. if( name.empty() )
  5037. return Result::logicError( "Option name cannot be empty" );
  5038. #ifdef CATCH_PLATFORM_WINDOWS
  5039. if( name[0] != '-' && name[0] != '/' )
  5040. return Result::logicError( "Option name must begin with '-' or '/'" );
  5041. #else
  5042. if( name[0] != '-' )
  5043. return Result::logicError( "Option name must begin with '-'" );
  5044. #endif
  5045. }
  5046. return ParserRefImpl::validate();
  5047. }
  5048. };
  5049. struct Help : Opt {
  5050. Help( bool &showHelpFlag )
  5051. : Opt([&]( bool flag ) {
  5052. showHelpFlag = flag;
  5053. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  5054. })
  5055. {
  5056. static_cast<Opt &>( *this )
  5057. ("display usage information")
  5058. ["-?"]["-h"]["--help"]
  5059. .optional();
  5060. }
  5061. };
  5062. struct Parser : ParserBase {
  5063. mutable ExeName m_exeName;
  5064. std::vector<Opt> m_options;
  5065. std::vector<Arg> m_args;
  5066. auto operator|=( ExeName const &exeName ) -> Parser & {
  5067. m_exeName = exeName;
  5068. return *this;
  5069. }
  5070. auto operator|=( Arg const &arg ) -> Parser & {
  5071. m_args.push_back(arg);
  5072. return *this;
  5073. }
  5074. auto operator|=( Opt const &opt ) -> Parser & {
  5075. m_options.push_back(opt);
  5076. return *this;
  5077. }
  5078. auto operator|=( Parser const &other ) -> Parser & {
  5079. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  5080. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  5081. return *this;
  5082. }
  5083. template<typename T>
  5084. auto operator|( T const &other ) const -> Parser {
  5085. return Parser( *this ) |= other;
  5086. }
  5087. // Forward deprecated interface with '+' instead of '|'
  5088. template<typename T>
  5089. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  5090. template<typename T>
  5091. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  5092. auto getHelpColumns() const -> std::vector<HelpColumns> {
  5093. std::vector<HelpColumns> cols;
  5094. for (auto const &o : m_options) {
  5095. auto childCols = o.getHelpColumns();
  5096. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  5097. }
  5098. return cols;
  5099. }
  5100. void writeToStream( std::ostream &os ) const {
  5101. if (!m_exeName.name().empty()) {
  5102. os << "usage:\n" << " " << m_exeName.name() << " ";
  5103. bool required = true, first = true;
  5104. for( auto const &arg : m_args ) {
  5105. if (first)
  5106. first = false;
  5107. else
  5108. os << " ";
  5109. if( arg.isOptional() && required ) {
  5110. os << "[";
  5111. required = false;
  5112. }
  5113. os << "<" << arg.hint() << ">";
  5114. if( arg.cardinality() == 0 )
  5115. os << " ... ";
  5116. }
  5117. if( !required )
  5118. os << "]";
  5119. if( !m_options.empty() )
  5120. os << " options";
  5121. os << "\n\nwhere options are:" << std::endl;
  5122. }
  5123. auto rows = getHelpColumns();
  5124. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  5125. size_t optWidth = 0;
  5126. for( auto const &cols : rows )
  5127. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  5128. optWidth = (std::min)(optWidth, consoleWidth/2);
  5129. for( auto const &cols : rows ) {
  5130. auto row =
  5131. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  5132. TextFlow::Spacer(4) +
  5133. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  5134. os << row << std::endl;
  5135. }
  5136. }
  5137. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  5138. parser.writeToStream( os );
  5139. return os;
  5140. }
  5141. auto validate() const -> Result override {
  5142. for( auto const &opt : m_options ) {
  5143. auto result = opt.validate();
  5144. if( !result )
  5145. return result;
  5146. }
  5147. for( auto const &arg : m_args ) {
  5148. auto result = arg.validate();
  5149. if( !result )
  5150. return result;
  5151. }
  5152. return Result::ok();
  5153. }
  5154. using ParserBase::parse;
  5155. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  5156. struct ParserInfo {
  5157. ParserBase const* parser = nullptr;
  5158. size_t count = 0;
  5159. };
  5160. const size_t totalParsers = m_options.size() + m_args.size();
  5161. assert( totalParsers < 512 );
  5162. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  5163. ParserInfo parseInfos[512];
  5164. {
  5165. size_t i = 0;
  5166. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  5167. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  5168. }
  5169. m_exeName.set( exeName );
  5170. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  5171. while( result.value().remainingTokens() ) {
  5172. bool tokenParsed = false;
  5173. for( size_t i = 0; i < totalParsers; ++i ) {
  5174. auto& parseInfo = parseInfos[i];
  5175. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  5176. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  5177. if (!result)
  5178. return result;
  5179. if (result.value().type() != ParseResultType::NoMatch) {
  5180. tokenParsed = true;
  5181. ++parseInfo.count;
  5182. break;
  5183. }
  5184. }
  5185. }
  5186. if( result.value().type() == ParseResultType::ShortCircuitAll )
  5187. return result;
  5188. if( !tokenParsed )
  5189. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  5190. }
  5191. // !TBD Check missing required options
  5192. return result;
  5193. }
  5194. };
  5195. template<typename DerivedT>
  5196. template<typename T>
  5197. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  5198. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  5199. }
  5200. } // namespace detail
  5201. // A Combined parser
  5202. using detail::Parser;
  5203. // A parser for options
  5204. using detail::Opt;
  5205. // A parser for arguments
  5206. using detail::Arg;
  5207. // Wrapper for argc, argv from main()
  5208. using detail::Args;
  5209. // Specifies the name of the executable
  5210. using detail::ExeName;
  5211. // Convenience wrapper for option parser that specifies the help option
  5212. using detail::Help;
  5213. // enum of result types from a parse
  5214. using detail::ParseResultType;
  5215. // Result type for parser operation
  5216. using detail::ParserResult;
  5217. }} // namespace Catch::clara
  5218. // end clara.hpp
  5219. #ifdef __clang__
  5220. #pragma clang diagnostic pop
  5221. #endif
  5222. // Restore Clara's value for console width, if present
  5223. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5224. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5225. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5226. #endif
  5227. // end catch_clara.h
  5228. namespace Catch {
  5229. clara::Parser makeCommandLineParser( ConfigData& config );
  5230. } // end namespace Catch
  5231. // end catch_commandline.h
  5232. #include <fstream>
  5233. #include <ctime>
  5234. namespace Catch {
  5235. clara::Parser makeCommandLineParser( ConfigData& config ) {
  5236. using namespace clara;
  5237. auto const setWarning = [&]( std::string const& warning ) {
  5238. auto warningSet = [&]() {
  5239. if( warning == "NoAssertions" )
  5240. return WarnAbout::NoAssertions;
  5241. if ( warning == "NoTests" )
  5242. return WarnAbout::NoTests;
  5243. return WarnAbout::Nothing;
  5244. }();
  5245. if (warningSet == WarnAbout::Nothing)
  5246. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  5247. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  5248. return ParserResult::ok( ParseResultType::Matched );
  5249. };
  5250. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  5251. std::ifstream f( filename.c_str() );
  5252. if( !f.is_open() )
  5253. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  5254. std::string line;
  5255. while( std::getline( f, line ) ) {
  5256. line = trim(line);
  5257. if( !line.empty() && !startsWith( line, '#' ) ) {
  5258. if( !startsWith( line, '"' ) )
  5259. line = '"' + line + '"';
  5260. config.testsOrTags.push_back( line + ',' );
  5261. }
  5262. }
  5263. return ParserResult::ok( ParseResultType::Matched );
  5264. };
  5265. auto const setTestOrder = [&]( std::string const& order ) {
  5266. if( startsWith( "declared", order ) )
  5267. config.runOrder = RunTests::InDeclarationOrder;
  5268. else if( startsWith( "lexical", order ) )
  5269. config.runOrder = RunTests::InLexicographicalOrder;
  5270. else if( startsWith( "random", order ) )
  5271. config.runOrder = RunTests::InRandomOrder;
  5272. else
  5273. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  5274. return ParserResult::ok( ParseResultType::Matched );
  5275. };
  5276. auto const setRngSeed = [&]( std::string const& seed ) {
  5277. if( seed != "time" )
  5278. return clara::detail::convertInto( seed, config.rngSeed );
  5279. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  5280. return ParserResult::ok( ParseResultType::Matched );
  5281. };
  5282. auto const setColourUsage = [&]( std::string const& useColour ) {
  5283. auto mode = toLower( useColour );
  5284. if( mode == "yes" )
  5285. config.useColour = UseColour::Yes;
  5286. else if( mode == "no" )
  5287. config.useColour = UseColour::No;
  5288. else if( mode == "auto" )
  5289. config.useColour = UseColour::Auto;
  5290. else
  5291. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  5292. return ParserResult::ok( ParseResultType::Matched );
  5293. };
  5294. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  5295. auto keypressLc = toLower( keypress );
  5296. if( keypressLc == "start" )
  5297. config.waitForKeypress = WaitForKeypress::BeforeStart;
  5298. else if( keypressLc == "exit" )
  5299. config.waitForKeypress = WaitForKeypress::BeforeExit;
  5300. else if( keypressLc == "both" )
  5301. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  5302. else
  5303. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  5304. return ParserResult::ok( ParseResultType::Matched );
  5305. };
  5306. auto const setVerbosity = [&]( std::string const& verbosity ) {
  5307. auto lcVerbosity = toLower( verbosity );
  5308. if( lcVerbosity == "quiet" )
  5309. config.verbosity = Verbosity::Quiet;
  5310. else if( lcVerbosity == "normal" )
  5311. config.verbosity = Verbosity::Normal;
  5312. else if( lcVerbosity == "high" )
  5313. config.verbosity = Verbosity::High;
  5314. else
  5315. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  5316. return ParserResult::ok( ParseResultType::Matched );
  5317. };
  5318. auto cli
  5319. = ExeName( config.processName )
  5320. | Help( config.showHelp )
  5321. | Opt( config.listTests )
  5322. ["-l"]["--list-tests"]
  5323. ( "list all/matching test cases" )
  5324. | Opt( config.listTags )
  5325. ["-t"]["--list-tags"]
  5326. ( "list all/matching tags" )
  5327. | Opt( config.showSuccessfulTests )
  5328. ["-s"]["--success"]
  5329. ( "include successful tests in output" )
  5330. | Opt( config.shouldDebugBreak )
  5331. ["-b"]["--break"]
  5332. ( "break into debugger on failure" )
  5333. | Opt( config.noThrow )
  5334. ["-e"]["--nothrow"]
  5335. ( "skip exception tests" )
  5336. | Opt( config.showInvisibles )
  5337. ["-i"]["--invisibles"]
  5338. ( "show invisibles (tabs, newlines)" )
  5339. | Opt( config.outputFilename, "filename" )
  5340. ["-o"]["--out"]
  5341. ( "output filename" )
  5342. | Opt( config.reporterName, "name" )
  5343. ["-r"]["--reporter"]
  5344. ( "reporter to use (defaults to console)" )
  5345. | Opt( config.name, "name" )
  5346. ["-n"]["--name"]
  5347. ( "suite name" )
  5348. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  5349. ["-a"]["--abort"]
  5350. ( "abort at first failure" )
  5351. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  5352. ["-x"]["--abortx"]
  5353. ( "abort after x failures" )
  5354. | Opt( setWarning, "warning name" )
  5355. ["-w"]["--warn"]
  5356. ( "enable warnings" )
  5357. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  5358. ["-d"]["--durations"]
  5359. ( "show test durations" )
  5360. | Opt( loadTestNamesFromFile, "filename" )
  5361. ["-f"]["--input-file"]
  5362. ( "load test names to run from a file" )
  5363. | Opt( config.filenamesAsTags )
  5364. ["-#"]["--filenames-as-tags"]
  5365. ( "adds a tag for the filename" )
  5366. | Opt( config.sectionsToRun, "section name" )
  5367. ["-c"]["--section"]
  5368. ( "specify section to run" )
  5369. | Opt( setVerbosity, "quiet|normal|high" )
  5370. ["-v"]["--verbosity"]
  5371. ( "set output verbosity" )
  5372. | Opt( config.listTestNamesOnly )
  5373. ["--list-test-names-only"]
  5374. ( "list all/matching test cases names only" )
  5375. | Opt( config.listReporters )
  5376. ["--list-reporters"]
  5377. ( "list all reporters" )
  5378. | Opt( setTestOrder, "decl|lex|rand" )
  5379. ["--order"]
  5380. ( "test case order (defaults to decl)" )
  5381. | Opt( setRngSeed, "'time'|number" )
  5382. ["--rng-seed"]
  5383. ( "set a specific seed for random numbers" )
  5384. | Opt( setColourUsage, "yes|no" )
  5385. ["--use-colour"]
  5386. ( "should output be colourised" )
  5387. | Opt( config.libIdentify )
  5388. ["--libidentify"]
  5389. ( "report name and version according to libidentify standard" )
  5390. | Opt( setWaitForKeypress, "start|exit|both" )
  5391. ["--wait-for-keypress"]
  5392. ( "waits for a keypress before exiting" )
  5393. | Opt( config.benchmarkResolutionMultiple, "multiplier" )
  5394. ["--benchmark-resolution-multiple"]
  5395. ( "multiple of clock resolution to run benchmarks" )
  5396. | Arg( config.testsOrTags, "test name|pattern|tags" )
  5397. ( "which test or tests to use" );
  5398. return cli;
  5399. }
  5400. } // end namespace Catch
  5401. // end catch_commandline.cpp
  5402. // start catch_common.cpp
  5403. #include <cstring>
  5404. #include <ostream>
  5405. namespace Catch {
  5406. bool SourceLineInfo::empty() const noexcept {
  5407. return file[0] == '\0';
  5408. }
  5409. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  5410. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  5411. }
  5412. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  5413. return line < other.line || ( line == other.line && (std::strcmp(file, other.file) < 0));
  5414. }
  5415. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  5416. #ifndef __GNUG__
  5417. os << info.file << '(' << info.line << ')';
  5418. #else
  5419. os << info.file << ':' << info.line;
  5420. #endif
  5421. return os;
  5422. }
  5423. std::string StreamEndStop::operator+() const {
  5424. return std::string();
  5425. }
  5426. NonCopyable::NonCopyable() = default;
  5427. NonCopyable::~NonCopyable() = default;
  5428. }
  5429. // end catch_common.cpp
  5430. // start catch_config.cpp
  5431. // start catch_enforce.h
  5432. #include <stdexcept>
  5433. #define CATCH_PREPARE_EXCEPTION( type, msg ) \
  5434. type( ( Catch::ReusableStringStream() << msg ).str() )
  5435. #define CATCH_INTERNAL_ERROR( msg ) \
  5436. throw CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg);
  5437. #define CATCH_ERROR( msg ) \
  5438. throw CATCH_PREPARE_EXCEPTION( std::domain_error, msg )
  5439. #define CATCH_ENFORCE( condition, msg ) \
  5440. do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
  5441. // end catch_enforce.h
  5442. namespace Catch {
  5443. Config::Config( ConfigData const& data )
  5444. : m_data( data ),
  5445. m_stream( openStream() )
  5446. {
  5447. TestSpecParser parser(ITagAliasRegistry::get());
  5448. if (data.testsOrTags.empty()) {
  5449. parser.parse("~[.]"); // All not hidden tests
  5450. }
  5451. else {
  5452. m_hasTestFilters = true;
  5453. for( auto const& testOrTags : data.testsOrTags )
  5454. parser.parse( testOrTags );
  5455. }
  5456. m_testSpec = parser.testSpec();
  5457. }
  5458. std::string const& Config::getFilename() const {
  5459. return m_data.outputFilename ;
  5460. }
  5461. bool Config::listTests() const { return m_data.listTests; }
  5462. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  5463. bool Config::listTags() const { return m_data.listTags; }
  5464. bool Config::listReporters() const { return m_data.listReporters; }
  5465. std::string Config::getProcessName() const { return m_data.processName; }
  5466. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  5467. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  5468. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  5469. TestSpec const& Config::testSpec() const { return m_testSpec; }
  5470. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  5471. bool Config::showHelp() const { return m_data.showHelp; }
  5472. // IConfig interface
  5473. bool Config::allowThrows() const { return !m_data.noThrow; }
  5474. std::ostream& Config::stream() const { return m_stream->stream(); }
  5475. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  5476. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  5477. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  5478. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  5479. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  5480. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  5481. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  5482. int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
  5483. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  5484. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  5485. int Config::abortAfter() const { return m_data.abortAfter; }
  5486. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  5487. Verbosity Config::verbosity() const { return m_data.verbosity; }
  5488. IStream const* Config::openStream() {
  5489. return Catch::makeStream(m_data.outputFilename);
  5490. }
  5491. } // end namespace Catch
  5492. // end catch_config.cpp
  5493. // start catch_console_colour.cpp
  5494. #if defined(__clang__)
  5495. # pragma clang diagnostic push
  5496. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  5497. #endif
  5498. // start catch_errno_guard.h
  5499. namespace Catch {
  5500. class ErrnoGuard {
  5501. public:
  5502. ErrnoGuard();
  5503. ~ErrnoGuard();
  5504. private:
  5505. int m_oldErrno;
  5506. };
  5507. }
  5508. // end catch_errno_guard.h
  5509. #include <sstream>
  5510. namespace Catch {
  5511. namespace {
  5512. struct IColourImpl {
  5513. virtual ~IColourImpl() = default;
  5514. virtual void use( Colour::Code _colourCode ) = 0;
  5515. };
  5516. struct NoColourImpl : IColourImpl {
  5517. void use( Colour::Code ) {}
  5518. static IColourImpl* instance() {
  5519. static NoColourImpl s_instance;
  5520. return &s_instance;
  5521. }
  5522. };
  5523. } // anon namespace
  5524. } // namespace Catch
  5525. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  5526. # ifdef CATCH_PLATFORM_WINDOWS
  5527. # define CATCH_CONFIG_COLOUR_WINDOWS
  5528. # else
  5529. # define CATCH_CONFIG_COLOUR_ANSI
  5530. # endif
  5531. #endif
  5532. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  5533. namespace Catch {
  5534. namespace {
  5535. class Win32ColourImpl : public IColourImpl {
  5536. public:
  5537. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  5538. {
  5539. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  5540. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  5541. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  5542. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  5543. }
  5544. virtual void use( Colour::Code _colourCode ) override {
  5545. switch( _colourCode ) {
  5546. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  5547. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5548. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  5549. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  5550. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  5551. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  5552. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  5553. case Colour::Grey: return setTextAttribute( 0 );
  5554. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  5555. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  5556. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  5557. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5558. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  5559. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5560. default:
  5561. CATCH_ERROR( "Unknown colour requested" );
  5562. }
  5563. }
  5564. private:
  5565. void setTextAttribute( WORD _textAttribute ) {
  5566. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  5567. }
  5568. HANDLE stdoutHandle;
  5569. WORD originalForegroundAttributes;
  5570. WORD originalBackgroundAttributes;
  5571. };
  5572. IColourImpl* platformColourInstance() {
  5573. static Win32ColourImpl s_instance;
  5574. IConfigPtr config = getCurrentContext().getConfig();
  5575. UseColour::YesOrNo colourMode = config
  5576. ? config->useColour()
  5577. : UseColour::Auto;
  5578. if( colourMode == UseColour::Auto )
  5579. colourMode = UseColour::Yes;
  5580. return colourMode == UseColour::Yes
  5581. ? &s_instance
  5582. : NoColourImpl::instance();
  5583. }
  5584. } // end anon namespace
  5585. } // end namespace Catch
  5586. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  5587. #include <unistd.h>
  5588. namespace Catch {
  5589. namespace {
  5590. // use POSIX/ ANSI console terminal codes
  5591. // Thanks to Adam Strzelecki for original contribution
  5592. // (http://github.com/nanoant)
  5593. // https://github.com/philsquared/Catch/pull/131
  5594. class PosixColourImpl : public IColourImpl {
  5595. public:
  5596. virtual void use( Colour::Code _colourCode ) override {
  5597. switch( _colourCode ) {
  5598. case Colour::None:
  5599. case Colour::White: return setColour( "[0m" );
  5600. case Colour::Red: return setColour( "[0;31m" );
  5601. case Colour::Green: return setColour( "[0;32m" );
  5602. case Colour::Blue: return setColour( "[0;34m" );
  5603. case Colour::Cyan: return setColour( "[0;36m" );
  5604. case Colour::Yellow: return setColour( "[0;33m" );
  5605. case Colour::Grey: return setColour( "[1;30m" );
  5606. case Colour::LightGrey: return setColour( "[0;37m" );
  5607. case Colour::BrightRed: return setColour( "[1;31m" );
  5608. case Colour::BrightGreen: return setColour( "[1;32m" );
  5609. case Colour::BrightWhite: return setColour( "[1;37m" );
  5610. case Colour::BrightYellow: return setColour( "[1;33m" );
  5611. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5612. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  5613. }
  5614. }
  5615. static IColourImpl* instance() {
  5616. static PosixColourImpl s_instance;
  5617. return &s_instance;
  5618. }
  5619. private:
  5620. void setColour( const char* _escapeCode ) {
  5621. Catch::cout() << '\033' << _escapeCode;
  5622. }
  5623. };
  5624. bool useColourOnPlatform() {
  5625. return
  5626. #ifdef CATCH_PLATFORM_MAC
  5627. !isDebuggerActive() &&
  5628. #endif
  5629. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  5630. isatty(STDOUT_FILENO)
  5631. #else
  5632. false
  5633. #endif
  5634. ;
  5635. }
  5636. IColourImpl* platformColourInstance() {
  5637. ErrnoGuard guard;
  5638. IConfigPtr config = getCurrentContext().getConfig();
  5639. UseColour::YesOrNo colourMode = config
  5640. ? config->useColour()
  5641. : UseColour::Auto;
  5642. if( colourMode == UseColour::Auto )
  5643. colourMode = useColourOnPlatform()
  5644. ? UseColour::Yes
  5645. : UseColour::No;
  5646. return colourMode == UseColour::Yes
  5647. ? PosixColourImpl::instance()
  5648. : NoColourImpl::instance();
  5649. }
  5650. } // end anon namespace
  5651. } // end namespace Catch
  5652. #else // not Windows or ANSI ///////////////////////////////////////////////
  5653. namespace Catch {
  5654. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  5655. } // end namespace Catch
  5656. #endif // Windows/ ANSI/ None
  5657. namespace Catch {
  5658. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  5659. Colour::Colour( Colour&& rhs ) noexcept {
  5660. m_moved = rhs.m_moved;
  5661. rhs.m_moved = true;
  5662. }
  5663. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  5664. m_moved = rhs.m_moved;
  5665. rhs.m_moved = true;
  5666. return *this;
  5667. }
  5668. Colour::~Colour(){ if( !m_moved ) use( None ); }
  5669. void Colour::use( Code _colourCode ) {
  5670. static IColourImpl* impl = platformColourInstance();
  5671. impl->use( _colourCode );
  5672. }
  5673. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  5674. return os;
  5675. }
  5676. } // end namespace Catch
  5677. #if defined(__clang__)
  5678. # pragma clang diagnostic pop
  5679. #endif
  5680. // end catch_console_colour.cpp
  5681. // start catch_context.cpp
  5682. namespace Catch {
  5683. class Context : public IMutableContext, NonCopyable {
  5684. public: // IContext
  5685. virtual IResultCapture* getResultCapture() override {
  5686. return m_resultCapture;
  5687. }
  5688. virtual IRunner* getRunner() override {
  5689. return m_runner;
  5690. }
  5691. virtual IConfigPtr const& getConfig() const override {
  5692. return m_config;
  5693. }
  5694. virtual ~Context() override;
  5695. public: // IMutableContext
  5696. virtual void setResultCapture( IResultCapture* resultCapture ) override {
  5697. m_resultCapture = resultCapture;
  5698. }
  5699. virtual void setRunner( IRunner* runner ) override {
  5700. m_runner = runner;
  5701. }
  5702. virtual void setConfig( IConfigPtr const& config ) override {
  5703. m_config = config;
  5704. }
  5705. friend IMutableContext& getCurrentMutableContext();
  5706. private:
  5707. IConfigPtr m_config;
  5708. IRunner* m_runner = nullptr;
  5709. IResultCapture* m_resultCapture = nullptr;
  5710. };
  5711. IMutableContext *IMutableContext::currentContext = nullptr;
  5712. void IMutableContext::createContext()
  5713. {
  5714. currentContext = new Context();
  5715. }
  5716. void cleanUpContext() {
  5717. delete IMutableContext::currentContext;
  5718. IMutableContext::currentContext = nullptr;
  5719. }
  5720. IContext::~IContext() = default;
  5721. IMutableContext::~IMutableContext() = default;
  5722. Context::~Context() = default;
  5723. }
  5724. // end catch_context.cpp
  5725. // start catch_debug_console.cpp
  5726. // start catch_debug_console.h
  5727. #include <string>
  5728. namespace Catch {
  5729. void writeToDebugConsole( std::string const& text );
  5730. }
  5731. // end catch_debug_console.h
  5732. #ifdef CATCH_PLATFORM_WINDOWS
  5733. namespace Catch {
  5734. void writeToDebugConsole( std::string const& text ) {
  5735. ::OutputDebugStringA( text.c_str() );
  5736. }
  5737. }
  5738. #else
  5739. namespace Catch {
  5740. void writeToDebugConsole( std::string const& text ) {
  5741. // !TBD: Need a version for Mac/ XCode and other IDEs
  5742. Catch::cout() << text;
  5743. }
  5744. }
  5745. #endif // Platform
  5746. // end catch_debug_console.cpp
  5747. // start catch_debugger.cpp
  5748. #ifdef CATCH_PLATFORM_MAC
  5749. # include <assert.h>
  5750. # include <stdbool.h>
  5751. # include <sys/types.h>
  5752. # include <unistd.h>
  5753. # include <sys/sysctl.h>
  5754. # include <cstddef>
  5755. # include <ostream>
  5756. namespace Catch {
  5757. // The following function is taken directly from the following technical note:
  5758. // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  5759. // Returns true if the current process is being debugged (either
  5760. // running under the debugger or has a debugger attached post facto).
  5761. bool isDebuggerActive(){
  5762. int mib[4];
  5763. struct kinfo_proc info;
  5764. std::size_t size;
  5765. // Initialize the flags so that, if sysctl fails for some bizarre
  5766. // reason, we get a predictable result.
  5767. info.kp_proc.p_flag = 0;
  5768. // Initialize mib, which tells sysctl the info we want, in this case
  5769. // we're looking for information about a specific process ID.
  5770. mib[0] = CTL_KERN;
  5771. mib[1] = KERN_PROC;
  5772. mib[2] = KERN_PROC_PID;
  5773. mib[3] = getpid();
  5774. // Call sysctl.
  5775. size = sizeof(info);
  5776. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  5777. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  5778. return false;
  5779. }
  5780. // We're being debugged if the P_TRACED flag is set.
  5781. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  5782. }
  5783. } // namespace Catch
  5784. #elif defined(CATCH_PLATFORM_LINUX)
  5785. #include <fstream>
  5786. #include <string>
  5787. namespace Catch{
  5788. // The standard POSIX way of detecting a debugger is to attempt to
  5789. // ptrace() the process, but this needs to be done from a child and not
  5790. // this process itself to still allow attaching to this process later
  5791. // if wanted, so is rather heavy. Under Linux we have the PID of the
  5792. // "debugger" (which doesn't need to be gdb, of course, it could also
  5793. // be strace, for example) in /proc/$PID/status, so just get it from
  5794. // there instead.
  5795. bool isDebuggerActive(){
  5796. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  5797. // This way our users can properly assert over errno values
  5798. ErrnoGuard guard;
  5799. std::ifstream in("/proc/self/status");
  5800. for( std::string line; std::getline(in, line); ) {
  5801. static const int PREFIX_LEN = 11;
  5802. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  5803. // We're traced if the PID is not 0 and no other PID starts
  5804. // with 0 digit, so it's enough to check for just a single
  5805. // character.
  5806. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  5807. }
  5808. }
  5809. return false;
  5810. }
  5811. } // namespace Catch
  5812. #elif defined(_MSC_VER)
  5813. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5814. namespace Catch {
  5815. bool isDebuggerActive() {
  5816. return IsDebuggerPresent() != 0;
  5817. }
  5818. }
  5819. #elif defined(__MINGW32__)
  5820. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  5821. namespace Catch {
  5822. bool isDebuggerActive() {
  5823. return IsDebuggerPresent() != 0;
  5824. }
  5825. }
  5826. #else
  5827. namespace Catch {
  5828. bool isDebuggerActive() { return false; }
  5829. }
  5830. #endif // Platform
  5831. // end catch_debugger.cpp
  5832. // start catch_decomposer.cpp
  5833. namespace Catch {
  5834. ITransientExpression::~ITransientExpression() = default;
  5835. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  5836. if( lhs.size() + rhs.size() < 40 &&
  5837. lhs.find('\n') == std::string::npos &&
  5838. rhs.find('\n') == std::string::npos )
  5839. os << lhs << " " << op << " " << rhs;
  5840. else
  5841. os << lhs << "\n" << op << "\n" << rhs;
  5842. }
  5843. }
  5844. // end catch_decomposer.cpp
  5845. // start catch_errno_guard.cpp
  5846. #include <cerrno>
  5847. namespace Catch {
  5848. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  5849. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  5850. }
  5851. // end catch_errno_guard.cpp
  5852. // start catch_exception_translator_registry.cpp
  5853. // start catch_exception_translator_registry.h
  5854. #include <vector>
  5855. #include <string>
  5856. #include <memory>
  5857. namespace Catch {
  5858. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  5859. public:
  5860. ~ExceptionTranslatorRegistry();
  5861. virtual void registerTranslator( const IExceptionTranslator* translator );
  5862. virtual std::string translateActiveException() const override;
  5863. std::string tryTranslators() const;
  5864. private:
  5865. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  5866. };
  5867. }
  5868. // end catch_exception_translator_registry.h
  5869. #ifdef __OBJC__
  5870. #import "Foundation/Foundation.h"
  5871. #endif
  5872. namespace Catch {
  5873. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  5874. }
  5875. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  5876. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  5877. }
  5878. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  5879. try {
  5880. #ifdef __OBJC__
  5881. // In Objective-C try objective-c exceptions first
  5882. @try {
  5883. return tryTranslators();
  5884. }
  5885. @catch (NSException *exception) {
  5886. return Catch::Detail::stringify( [exception description] );
  5887. }
  5888. #else
  5889. // Compiling a mixed mode project with MSVC means that CLR
  5890. // exceptions will be caught in (...) as well. However, these
  5891. // do not fill-in std::current_exception and thus lead to crash
  5892. // when attempting rethrow.
  5893. // /EHa switch also causes structured exceptions to be caught
  5894. // here, but they fill-in current_exception properly, so
  5895. // at worst the output should be a little weird, instead of
  5896. // causing a crash.
  5897. if (std::current_exception() == nullptr) {
  5898. return "Non C++ exception. Possibly a CLR exception.";
  5899. }
  5900. return tryTranslators();
  5901. #endif
  5902. }
  5903. catch( TestFailureException& ) {
  5904. std::rethrow_exception(std::current_exception());
  5905. }
  5906. catch( std::exception& ex ) {
  5907. return ex.what();
  5908. }
  5909. catch( std::string& msg ) {
  5910. return msg;
  5911. }
  5912. catch( const char* msg ) {
  5913. return msg;
  5914. }
  5915. catch(...) {
  5916. return "Unknown exception";
  5917. }
  5918. }
  5919. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  5920. if( m_translators.empty() )
  5921. std::rethrow_exception(std::current_exception());
  5922. else
  5923. return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() );
  5924. }
  5925. }
  5926. // end catch_exception_translator_registry.cpp
  5927. // start catch_fatal_condition.cpp
  5928. #if defined(__GNUC__)
  5929. # pragma GCC diagnostic push
  5930. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  5931. #endif
  5932. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  5933. namespace {
  5934. // Report the error condition
  5935. void reportFatal( char const * const message ) {
  5936. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  5937. }
  5938. }
  5939. #endif // signals/SEH handling
  5940. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  5941. namespace Catch {
  5942. struct SignalDefs { DWORD id; const char* name; };
  5943. // There is no 1-1 mapping between signals and windows exceptions.
  5944. // Windows can easily distinguish between SO and SigSegV,
  5945. // but SigInt, SigTerm, etc are handled differently.
  5946. static SignalDefs signalDefs[] = {
  5947. { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
  5948. { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
  5949. { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
  5950. { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
  5951. };
  5952. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  5953. for (auto const& def : signalDefs) {
  5954. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  5955. reportFatal(def.name);
  5956. }
  5957. }
  5958. // If its not an exception we care about, pass it along.
  5959. // This stops us from eating debugger breaks etc.
  5960. return EXCEPTION_CONTINUE_SEARCH;
  5961. }
  5962. FatalConditionHandler::FatalConditionHandler() {
  5963. isSet = true;
  5964. // 32k seems enough for Catch to handle stack overflow,
  5965. // but the value was found experimentally, so there is no strong guarantee
  5966. guaranteeSize = 32 * 1024;
  5967. exceptionHandlerHandle = nullptr;
  5968. // Register as first handler in current chain
  5969. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  5970. // Pass in guarantee size to be filled
  5971. SetThreadStackGuarantee(&guaranteeSize);
  5972. }
  5973. void FatalConditionHandler::reset() {
  5974. if (isSet) {
  5975. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  5976. SetThreadStackGuarantee(&guaranteeSize);
  5977. exceptionHandlerHandle = nullptr;
  5978. isSet = false;
  5979. }
  5980. }
  5981. FatalConditionHandler::~FatalConditionHandler() {
  5982. reset();
  5983. }
  5984. bool FatalConditionHandler::isSet = false;
  5985. ULONG FatalConditionHandler::guaranteeSize = 0;
  5986. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  5987. } // namespace Catch
  5988. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  5989. namespace Catch {
  5990. struct SignalDefs {
  5991. int id;
  5992. const char* name;
  5993. };
  5994. // 32kb for the alternate stack seems to be sufficient. However, this value
  5995. // is experimentally determined, so that's not guaranteed.
  5996. constexpr static std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
  5997. static SignalDefs signalDefs[] = {
  5998. { SIGINT, "SIGINT - Terminal interrupt signal" },
  5999. { SIGILL, "SIGILL - Illegal instruction signal" },
  6000. { SIGFPE, "SIGFPE - Floating point error signal" },
  6001. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  6002. { SIGTERM, "SIGTERM - Termination request signal" },
  6003. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  6004. };
  6005. void FatalConditionHandler::handleSignal( int sig ) {
  6006. char const * name = "<unknown signal>";
  6007. for (auto const& def : signalDefs) {
  6008. if (sig == def.id) {
  6009. name = def.name;
  6010. break;
  6011. }
  6012. }
  6013. reset();
  6014. reportFatal(name);
  6015. raise( sig );
  6016. }
  6017. FatalConditionHandler::FatalConditionHandler() {
  6018. isSet = true;
  6019. stack_t sigStack;
  6020. sigStack.ss_sp = altStackMem;
  6021. sigStack.ss_size = sigStackSize;
  6022. sigStack.ss_flags = 0;
  6023. sigaltstack(&sigStack, &oldSigStack);
  6024. struct sigaction sa = { };
  6025. sa.sa_handler = handleSignal;
  6026. sa.sa_flags = SA_ONSTACK;
  6027. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  6028. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  6029. }
  6030. }
  6031. FatalConditionHandler::~FatalConditionHandler() {
  6032. reset();
  6033. }
  6034. void FatalConditionHandler::reset() {
  6035. if( isSet ) {
  6036. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  6037. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  6038. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  6039. }
  6040. // Return the old stack
  6041. sigaltstack(&oldSigStack, nullptr);
  6042. isSet = false;
  6043. }
  6044. }
  6045. bool FatalConditionHandler::isSet = false;
  6046. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  6047. stack_t FatalConditionHandler::oldSigStack = {};
  6048. char FatalConditionHandler::altStackMem[sigStackSize] = {};
  6049. } // namespace Catch
  6050. #else
  6051. namespace Catch {
  6052. void FatalConditionHandler::reset() {}
  6053. }
  6054. #endif // signals/SEH handling
  6055. #if defined(__GNUC__)
  6056. # pragma GCC diagnostic pop
  6057. #endif
  6058. // end catch_fatal_condition.cpp
  6059. // start catch_interfaces_capture.cpp
  6060. namespace Catch {
  6061. IResultCapture::~IResultCapture() = default;
  6062. }
  6063. // end catch_interfaces_capture.cpp
  6064. // start catch_interfaces_config.cpp
  6065. namespace Catch {
  6066. IConfig::~IConfig() = default;
  6067. }
  6068. // end catch_interfaces_config.cpp
  6069. // start catch_interfaces_exception.cpp
  6070. namespace Catch {
  6071. IExceptionTranslator::~IExceptionTranslator() = default;
  6072. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  6073. }
  6074. // end catch_interfaces_exception.cpp
  6075. // start catch_interfaces_registry_hub.cpp
  6076. namespace Catch {
  6077. IRegistryHub::~IRegistryHub() = default;
  6078. IMutableRegistryHub::~IMutableRegistryHub() = default;
  6079. }
  6080. // end catch_interfaces_registry_hub.cpp
  6081. // start catch_interfaces_reporter.cpp
  6082. // start catch_reporter_listening.h
  6083. namespace Catch {
  6084. class ListeningReporter : public IStreamingReporter {
  6085. using Reporters = std::vector<IStreamingReporterPtr>;
  6086. Reporters m_listeners;
  6087. IStreamingReporterPtr m_reporter = nullptr;
  6088. ReporterPreferences m_preferences;
  6089. public:
  6090. ListeningReporter();
  6091. void addListener( IStreamingReporterPtr&& listener );
  6092. void addReporter( IStreamingReporterPtr&& reporter );
  6093. public: // IStreamingReporter
  6094. ReporterPreferences getPreferences() const override;
  6095. void noMatchingTestCases( std::string const& spec ) override;
  6096. static std::set<Verbosity> getSupportedVerbosities();
  6097. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  6098. void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override;
  6099. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  6100. void testGroupStarting( GroupInfo const& groupInfo ) override;
  6101. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  6102. void sectionStarting( SectionInfo const& sectionInfo ) override;
  6103. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  6104. // The return value indicates if the messages buffer should be cleared:
  6105. bool assertionEnded( AssertionStats const& assertionStats ) override;
  6106. void sectionEnded( SectionStats const& sectionStats ) override;
  6107. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  6108. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  6109. void testRunEnded( TestRunStats const& testRunStats ) override;
  6110. void skipTest( TestCaseInfo const& testInfo ) override;
  6111. bool isMulti() const override;
  6112. };
  6113. } // end namespace Catch
  6114. // end catch_reporter_listening.h
  6115. namespace Catch {
  6116. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  6117. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  6118. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  6119. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  6120. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  6121. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  6122. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  6123. GroupInfo::GroupInfo( std::string const& _name,
  6124. std::size_t _groupIndex,
  6125. std::size_t _groupsCount )
  6126. : name( _name ),
  6127. groupIndex( _groupIndex ),
  6128. groupsCounts( _groupsCount )
  6129. {}
  6130. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  6131. std::vector<MessageInfo> const& _infoMessages,
  6132. Totals const& _totals )
  6133. : assertionResult( _assertionResult ),
  6134. infoMessages( _infoMessages ),
  6135. totals( _totals )
  6136. {
  6137. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  6138. if( assertionResult.hasMessage() ) {
  6139. // Copy message into messages list.
  6140. // !TBD This should have been done earlier, somewhere
  6141. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  6142. builder << assertionResult.getMessage();
  6143. builder.m_info.message = builder.m_stream.str();
  6144. infoMessages.push_back( builder.m_info );
  6145. }
  6146. }
  6147. AssertionStats::~AssertionStats() = default;
  6148. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  6149. Counts const& _assertions,
  6150. double _durationInSeconds,
  6151. bool _missingAssertions )
  6152. : sectionInfo( _sectionInfo ),
  6153. assertions( _assertions ),
  6154. durationInSeconds( _durationInSeconds ),
  6155. missingAssertions( _missingAssertions )
  6156. {}
  6157. SectionStats::~SectionStats() = default;
  6158. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  6159. Totals const& _totals,
  6160. std::string const& _stdOut,
  6161. std::string const& _stdErr,
  6162. bool _aborting )
  6163. : testInfo( _testInfo ),
  6164. totals( _totals ),
  6165. stdOut( _stdOut ),
  6166. stdErr( _stdErr ),
  6167. aborting( _aborting )
  6168. {}
  6169. TestCaseStats::~TestCaseStats() = default;
  6170. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  6171. Totals const& _totals,
  6172. bool _aborting )
  6173. : groupInfo( _groupInfo ),
  6174. totals( _totals ),
  6175. aborting( _aborting )
  6176. {}
  6177. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  6178. : groupInfo( _groupInfo ),
  6179. aborting( false )
  6180. {}
  6181. TestGroupStats::~TestGroupStats() = default;
  6182. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  6183. Totals const& _totals,
  6184. bool _aborting )
  6185. : runInfo( _runInfo ),
  6186. totals( _totals ),
  6187. aborting( _aborting )
  6188. {}
  6189. TestRunStats::~TestRunStats() = default;
  6190. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  6191. bool IStreamingReporter::isMulti() const { return false; }
  6192. IReporterFactory::~IReporterFactory() = default;
  6193. IReporterRegistry::~IReporterRegistry() = default;
  6194. } // end namespace Catch
  6195. // end catch_interfaces_reporter.cpp
  6196. // start catch_interfaces_runner.cpp
  6197. namespace Catch {
  6198. IRunner::~IRunner() = default;
  6199. }
  6200. // end catch_interfaces_runner.cpp
  6201. // start catch_interfaces_testcase.cpp
  6202. namespace Catch {
  6203. ITestInvoker::~ITestInvoker() = default;
  6204. ITestCaseRegistry::~ITestCaseRegistry() = default;
  6205. }
  6206. // end catch_interfaces_testcase.cpp
  6207. // start catch_leak_detector.cpp
  6208. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  6209. #include <crtdbg.h>
  6210. namespace Catch {
  6211. LeakDetector::LeakDetector() {
  6212. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  6213. flag |= _CRTDBG_LEAK_CHECK_DF;
  6214. flag |= _CRTDBG_ALLOC_MEM_DF;
  6215. _CrtSetDbgFlag(flag);
  6216. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  6217. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  6218. // Change this to leaking allocation's number to break there
  6219. _CrtSetBreakAlloc(-1);
  6220. }
  6221. }
  6222. #else
  6223. Catch::LeakDetector::LeakDetector() {}
  6224. #endif
  6225. // end catch_leak_detector.cpp
  6226. // start catch_list.cpp
  6227. // start catch_list.h
  6228. #include <set>
  6229. namespace Catch {
  6230. std::size_t listTests( Config const& config );
  6231. std::size_t listTestsNamesOnly( Config const& config );
  6232. struct TagInfo {
  6233. void add( std::string const& spelling );
  6234. std::string all() const;
  6235. std::set<std::string> spellings;
  6236. std::size_t count = 0;
  6237. };
  6238. std::size_t listTags( Config const& config );
  6239. std::size_t listReporters( Config const& /*config*/ );
  6240. Option<std::size_t> list( Config const& config );
  6241. } // end namespace Catch
  6242. // end catch_list.h
  6243. // start catch_text.h
  6244. namespace Catch {
  6245. using namespace clara::TextFlow;
  6246. }
  6247. // end catch_text.h
  6248. #include <limits>
  6249. #include <algorithm>
  6250. #include <iomanip>
  6251. namespace Catch {
  6252. std::size_t listTests( Config const& config ) {
  6253. TestSpec testSpec = config.testSpec();
  6254. if( config.hasTestFilters() )
  6255. Catch::cout() << "Matching test cases:\n";
  6256. else {
  6257. Catch::cout() << "All available test cases:\n";
  6258. }
  6259. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6260. for( auto const& testCaseInfo : matchedTestCases ) {
  6261. Colour::Code colour = testCaseInfo.isHidden()
  6262. ? Colour::SecondaryText
  6263. : Colour::None;
  6264. Colour colourGuard( colour );
  6265. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  6266. if( config.verbosity() >= Verbosity::High ) {
  6267. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  6268. std::string description = testCaseInfo.description;
  6269. if( description.empty() )
  6270. description = "(NO DESCRIPTION)";
  6271. Catch::cout() << Column( description ).indent(4) << std::endl;
  6272. }
  6273. if( !testCaseInfo.tags.empty() )
  6274. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  6275. }
  6276. if( !config.hasTestFilters() )
  6277. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  6278. else
  6279. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  6280. return matchedTestCases.size();
  6281. }
  6282. std::size_t listTestsNamesOnly( Config const& config ) {
  6283. TestSpec testSpec = config.testSpec();
  6284. std::size_t matchedTests = 0;
  6285. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6286. for( auto const& testCaseInfo : matchedTestCases ) {
  6287. matchedTests++;
  6288. if( startsWith( testCaseInfo.name, '#' ) )
  6289. Catch::cout() << '"' << testCaseInfo.name << '"';
  6290. else
  6291. Catch::cout() << testCaseInfo.name;
  6292. if ( config.verbosity() >= Verbosity::High )
  6293. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  6294. Catch::cout() << std::endl;
  6295. }
  6296. return matchedTests;
  6297. }
  6298. void TagInfo::add( std::string const& spelling ) {
  6299. ++count;
  6300. spellings.insert( spelling );
  6301. }
  6302. std::string TagInfo::all() const {
  6303. std::string out;
  6304. for( auto const& spelling : spellings )
  6305. out += "[" + spelling + "]";
  6306. return out;
  6307. }
  6308. std::size_t listTags( Config const& config ) {
  6309. TestSpec testSpec = config.testSpec();
  6310. if( config.hasTestFilters() )
  6311. Catch::cout() << "Tags for matching test cases:\n";
  6312. else {
  6313. Catch::cout() << "All available tags:\n";
  6314. }
  6315. std::map<std::string, TagInfo> tagCounts;
  6316. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6317. for( auto const& testCase : matchedTestCases ) {
  6318. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  6319. std::string lcaseTagName = toLower( tagName );
  6320. auto countIt = tagCounts.find( lcaseTagName );
  6321. if( countIt == tagCounts.end() )
  6322. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  6323. countIt->second.add( tagName );
  6324. }
  6325. }
  6326. for( auto const& tagCount : tagCounts ) {
  6327. ReusableStringStream rss;
  6328. rss << " " << std::setw(2) << tagCount.second.count << " ";
  6329. auto str = rss.str();
  6330. auto wrapper = Column( tagCount.second.all() )
  6331. .initialIndent( 0 )
  6332. .indent( str.size() )
  6333. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  6334. Catch::cout() << str << wrapper << '\n';
  6335. }
  6336. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  6337. return tagCounts.size();
  6338. }
  6339. std::size_t listReporters( Config const& /*config*/ ) {
  6340. Catch::cout() << "Available reporters:\n";
  6341. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  6342. std::size_t maxNameLen = 0;
  6343. for( auto const& factoryKvp : factories )
  6344. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  6345. for( auto const& factoryKvp : factories ) {
  6346. Catch::cout()
  6347. << Column( factoryKvp.first + ":" )
  6348. .indent(2)
  6349. .width( 5+maxNameLen )
  6350. + Column( factoryKvp.second->getDescription() )
  6351. .initialIndent(0)
  6352. .indent(2)
  6353. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  6354. << "\n";
  6355. }
  6356. Catch::cout() << std::endl;
  6357. return factories.size();
  6358. }
  6359. Option<std::size_t> list( Config const& config ) {
  6360. Option<std::size_t> listedCount;
  6361. if( config.listTests() )
  6362. listedCount = listedCount.valueOr(0) + listTests( config );
  6363. if( config.listTestNamesOnly() )
  6364. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
  6365. if( config.listTags() )
  6366. listedCount = listedCount.valueOr(0) + listTags( config );
  6367. if( config.listReporters() )
  6368. listedCount = listedCount.valueOr(0) + listReporters( config );
  6369. return listedCount;
  6370. }
  6371. } // end namespace Catch
  6372. // end catch_list.cpp
  6373. // start catch_matchers.cpp
  6374. namespace Catch {
  6375. namespace Matchers {
  6376. namespace Impl {
  6377. std::string MatcherUntypedBase::toString() const {
  6378. if( m_cachedToString.empty() )
  6379. m_cachedToString = describe();
  6380. return m_cachedToString;
  6381. }
  6382. MatcherUntypedBase::~MatcherUntypedBase() = default;
  6383. } // namespace Impl
  6384. } // namespace Matchers
  6385. using namespace Matchers;
  6386. using Matchers::Impl::MatcherBase;
  6387. } // namespace Catch
  6388. // end catch_matchers.cpp
  6389. // start catch_matchers_floating.cpp
  6390. // start catch_to_string.hpp
  6391. #include <string>
  6392. namespace Catch {
  6393. template <typename T>
  6394. std::string to_string(T const& t) {
  6395. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  6396. return std::to_string(t);
  6397. #else
  6398. ReusableStringStream rss;
  6399. rss << t;
  6400. return rss.str();
  6401. #endif
  6402. }
  6403. } // end namespace Catch
  6404. // end catch_to_string.hpp
  6405. #include <cstdlib>
  6406. #include <cstdint>
  6407. #include <cstring>
  6408. #include <stdexcept>
  6409. namespace Catch {
  6410. namespace Matchers {
  6411. namespace Floating {
  6412. enum class FloatingPointKind : uint8_t {
  6413. Float,
  6414. Double
  6415. };
  6416. }
  6417. }
  6418. }
  6419. namespace {
  6420. template <typename T>
  6421. struct Converter;
  6422. template <>
  6423. struct Converter<float> {
  6424. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  6425. Converter(float f) {
  6426. std::memcpy(&i, &f, sizeof(f));
  6427. }
  6428. int32_t i;
  6429. };
  6430. template <>
  6431. struct Converter<double> {
  6432. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  6433. Converter(double d) {
  6434. std::memcpy(&i, &d, sizeof(d));
  6435. }
  6436. int64_t i;
  6437. };
  6438. template <typename T>
  6439. auto convert(T t) -> Converter<T> {
  6440. return Converter<T>(t);
  6441. }
  6442. template <typename FP>
  6443. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  6444. // Comparison with NaN should always be false.
  6445. // This way we can rule it out before getting into the ugly details
  6446. if (std::isnan(lhs) || std::isnan(rhs)) {
  6447. return false;
  6448. }
  6449. auto lc = convert(lhs);
  6450. auto rc = convert(rhs);
  6451. if ((lc.i < 0) != (rc.i < 0)) {
  6452. // Potentially we can have +0 and -0
  6453. return lhs == rhs;
  6454. }
  6455. auto ulpDiff = std::abs(lc.i - rc.i);
  6456. return ulpDiff <= maxUlpDiff;
  6457. }
  6458. }
  6459. namespace Catch {
  6460. namespace Matchers {
  6461. namespace Floating {
  6462. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  6463. :m_target{ target }, m_margin{ margin } {
  6464. if (m_margin < 0) {
  6465. throw std::domain_error("Allowed margin difference has to be >= 0");
  6466. }
  6467. }
  6468. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6469. // But without the subtraction to allow for INFINITY in comparison
  6470. bool WithinAbsMatcher::match(double const& matchee) const {
  6471. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  6472. }
  6473. std::string WithinAbsMatcher::describe() const {
  6474. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  6475. }
  6476. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  6477. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  6478. if (m_ulps < 0) {
  6479. throw std::domain_error("Allowed ulp difference has to be >= 0");
  6480. }
  6481. }
  6482. bool WithinUlpsMatcher::match(double const& matchee) const {
  6483. switch (m_type) {
  6484. case FloatingPointKind::Float:
  6485. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  6486. case FloatingPointKind::Double:
  6487. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  6488. default:
  6489. throw std::domain_error("Unknown FloatingPointKind value");
  6490. }
  6491. }
  6492. std::string WithinUlpsMatcher::describe() const {
  6493. return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  6494. }
  6495. }// namespace Floating
  6496. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  6497. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  6498. }
  6499. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  6500. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  6501. }
  6502. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  6503. return Floating::WithinAbsMatcher(target, margin);
  6504. }
  6505. } // namespace Matchers
  6506. } // namespace Catch
  6507. // end catch_matchers_floating.cpp
  6508. // start catch_matchers_generic.cpp
  6509. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  6510. if (desc.empty()) {
  6511. return "matches undescribed predicate";
  6512. } else {
  6513. return "matches predicate: \"" + desc + '"';
  6514. }
  6515. }
  6516. // end catch_matchers_generic.cpp
  6517. // start catch_matchers_string.cpp
  6518. #include <regex>
  6519. namespace Catch {
  6520. namespace Matchers {
  6521. namespace StdString {
  6522. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  6523. : m_caseSensitivity( caseSensitivity ),
  6524. m_str( adjustString( str ) )
  6525. {}
  6526. std::string CasedString::adjustString( std::string const& str ) const {
  6527. return m_caseSensitivity == CaseSensitive::No
  6528. ? toLower( str )
  6529. : str;
  6530. }
  6531. std::string CasedString::caseSensitivitySuffix() const {
  6532. return m_caseSensitivity == CaseSensitive::No
  6533. ? " (case insensitive)"
  6534. : std::string();
  6535. }
  6536. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  6537. : m_comparator( comparator ),
  6538. m_operation( operation ) {
  6539. }
  6540. std::string StringMatcherBase::describe() const {
  6541. std::string description;
  6542. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  6543. m_comparator.caseSensitivitySuffix().size());
  6544. description += m_operation;
  6545. description += ": \"";
  6546. description += m_comparator.m_str;
  6547. description += "\"";
  6548. description += m_comparator.caseSensitivitySuffix();
  6549. return description;
  6550. }
  6551. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  6552. bool EqualsMatcher::match( std::string const& source ) const {
  6553. return m_comparator.adjustString( source ) == m_comparator.m_str;
  6554. }
  6555. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  6556. bool ContainsMatcher::match( std::string const& source ) const {
  6557. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  6558. }
  6559. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  6560. bool StartsWithMatcher::match( std::string const& source ) const {
  6561. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6562. }
  6563. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  6564. bool EndsWithMatcher::match( std::string const& source ) const {
  6565. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6566. }
  6567. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  6568. bool RegexMatcher::match(std::string const& matchee) const {
  6569. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  6570. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  6571. flags |= std::regex::icase;
  6572. }
  6573. auto reg = std::regex(m_regex, flags);
  6574. return std::regex_match(matchee, reg);
  6575. }
  6576. std::string RegexMatcher::describe() const {
  6577. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  6578. }
  6579. } // namespace StdString
  6580. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6581. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  6582. }
  6583. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6584. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  6585. }
  6586. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6587. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  6588. }
  6589. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6590. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  6591. }
  6592. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  6593. return StdString::RegexMatcher(regex, caseSensitivity);
  6594. }
  6595. } // namespace Matchers
  6596. } // namespace Catch
  6597. // end catch_matchers_string.cpp
  6598. // start catch_message.cpp
  6599. // start catch_uncaught_exceptions.h
  6600. namespace Catch {
  6601. bool uncaught_exceptions();
  6602. } // end namespace Catch
  6603. // end catch_uncaught_exceptions.h
  6604. namespace Catch {
  6605. MessageInfo::MessageInfo( std::string const& _macroName,
  6606. SourceLineInfo const& _lineInfo,
  6607. ResultWas::OfType _type )
  6608. : macroName( _macroName ),
  6609. lineInfo( _lineInfo ),
  6610. type( _type ),
  6611. sequence( ++globalCount )
  6612. {}
  6613. bool MessageInfo::operator==( MessageInfo const& other ) const {
  6614. return sequence == other.sequence;
  6615. }
  6616. bool MessageInfo::operator<( MessageInfo const& other ) const {
  6617. return sequence < other.sequence;
  6618. }
  6619. // This may need protecting if threading support is added
  6620. unsigned int MessageInfo::globalCount = 0;
  6621. ////////////////////////////////////////////////////////////////////////////
  6622. Catch::MessageBuilder::MessageBuilder( std::string const& macroName,
  6623. SourceLineInfo const& lineInfo,
  6624. ResultWas::OfType type )
  6625. :m_info(macroName, lineInfo, type) {}
  6626. ////////////////////////////////////////////////////////////////////////////
  6627. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  6628. : m_info( builder.m_info )
  6629. {
  6630. m_info.message = builder.m_stream.str();
  6631. getResultCapture().pushScopedMessage( m_info );
  6632. }
  6633. ScopedMessage::~ScopedMessage() {
  6634. if ( !uncaught_exceptions() ){
  6635. getResultCapture().popScopedMessage(m_info);
  6636. }
  6637. }
  6638. } // end namespace Catch
  6639. // end catch_message.cpp
  6640. // start catch_output_redirect.cpp
  6641. // start catch_output_redirect.h
  6642. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  6643. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  6644. #include <cstdio>
  6645. #include <iosfwd>
  6646. #include <string>
  6647. namespace Catch {
  6648. class RedirectedStream {
  6649. std::ostream& m_originalStream;
  6650. std::ostream& m_redirectionStream;
  6651. std::streambuf* m_prevBuf;
  6652. public:
  6653. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  6654. ~RedirectedStream();
  6655. };
  6656. class RedirectedStdOut {
  6657. ReusableStringStream m_rss;
  6658. RedirectedStream m_cout;
  6659. public:
  6660. RedirectedStdOut();
  6661. auto str() const -> std::string;
  6662. };
  6663. // StdErr has two constituent streams in C++, std::cerr and std::clog
  6664. // This means that we need to redirect 2 streams into 1 to keep proper
  6665. // order of writes
  6666. class RedirectedStdErr {
  6667. ReusableStringStream m_rss;
  6668. RedirectedStream m_cerr;
  6669. RedirectedStream m_clog;
  6670. public:
  6671. RedirectedStdErr();
  6672. auto str() const -> std::string;
  6673. };
  6674. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  6675. // Windows's implementation of std::tmpfile is terrible (it tries
  6676. // to create a file inside system folder, thus requiring elevated
  6677. // privileges for the binary), so we have to use tmpnam(_s) and
  6678. // create the file ourselves there.
  6679. class TempFile {
  6680. public:
  6681. TempFile(TempFile const&) = delete;
  6682. TempFile& operator=(TempFile const&) = delete;
  6683. TempFile(TempFile&&) = delete;
  6684. TempFile& operator=(TempFile&&) = delete;
  6685. TempFile();
  6686. ~TempFile();
  6687. std::FILE* getFile();
  6688. std::string getContents();
  6689. private:
  6690. std::FILE* m_file = nullptr;
  6691. #if defined(_MSC_VER)
  6692. char m_buffer[L_tmpnam] = { 0 };
  6693. #endif
  6694. };
  6695. class OutputRedirect {
  6696. public:
  6697. OutputRedirect(OutputRedirect const&) = delete;
  6698. OutputRedirect& operator=(OutputRedirect const&) = delete;
  6699. OutputRedirect(OutputRedirect&&) = delete;
  6700. OutputRedirect& operator=(OutputRedirect&&) = delete;
  6701. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  6702. ~OutputRedirect();
  6703. private:
  6704. int m_originalStdout = -1;
  6705. int m_originalStderr = -1;
  6706. TempFile m_stdoutFile;
  6707. TempFile m_stderrFile;
  6708. std::string& m_stdoutDest;
  6709. std::string& m_stderrDest;
  6710. };
  6711. #endif
  6712. } // end namespace Catch
  6713. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  6714. // end catch_output_redirect.h
  6715. #include <cstdio>
  6716. #include <cstring>
  6717. #include <fstream>
  6718. #include <sstream>
  6719. #include <stdexcept>
  6720. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  6721. #if defined(_MSC_VER)
  6722. #include <io.h> //_dup and _dup2
  6723. #define dup _dup
  6724. #define dup2 _dup2
  6725. #define fileno _fileno
  6726. #else
  6727. #include <unistd.h> // dup and dup2
  6728. #endif
  6729. #endif
  6730. namespace Catch {
  6731. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  6732. : m_originalStream( originalStream ),
  6733. m_redirectionStream( redirectionStream ),
  6734. m_prevBuf( m_originalStream.rdbuf() )
  6735. {
  6736. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  6737. }
  6738. RedirectedStream::~RedirectedStream() {
  6739. m_originalStream.rdbuf( m_prevBuf );
  6740. }
  6741. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  6742. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  6743. RedirectedStdErr::RedirectedStdErr()
  6744. : m_cerr( Catch::cerr(), m_rss.get() ),
  6745. m_clog( Catch::clog(), m_rss.get() )
  6746. {}
  6747. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  6748. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  6749. #if defined(_MSC_VER)
  6750. TempFile::TempFile() {
  6751. if (tmpnam_s(m_buffer)) {
  6752. throw std::runtime_error("Could not get a temp filename");
  6753. }
  6754. if (fopen_s(&m_file, m_buffer, "w")) {
  6755. char buffer[100];
  6756. if (strerror_s(buffer, errno)) {
  6757. throw std::runtime_error("Could not translate errno to string");
  6758. }
  6759. throw std::runtime_error("Could not open the temp file: " + std::string(m_buffer) + buffer);
  6760. }
  6761. }
  6762. #else
  6763. TempFile::TempFile() {
  6764. m_file = std::tmpfile();
  6765. if (!m_file) {
  6766. throw std::runtime_error("Could not create a temp file.");
  6767. }
  6768. }
  6769. #endif
  6770. TempFile::~TempFile() {
  6771. // TBD: What to do about errors here?
  6772. std::fclose(m_file);
  6773. // We manually create the file on Windows only, on Linux
  6774. // it will be autodeleted
  6775. #if defined(_MSC_VER)
  6776. std::remove(m_buffer);
  6777. #endif
  6778. }
  6779. FILE* TempFile::getFile() {
  6780. return m_file;
  6781. }
  6782. std::string TempFile::getContents() {
  6783. std::stringstream sstr;
  6784. char buffer[100] = {};
  6785. std::rewind(m_file);
  6786. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  6787. sstr << buffer;
  6788. }
  6789. return sstr.str();
  6790. }
  6791. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  6792. m_originalStdout(dup(1)),
  6793. m_originalStderr(dup(2)),
  6794. m_stdoutDest(stdout_dest),
  6795. m_stderrDest(stderr_dest) {
  6796. dup2(fileno(m_stdoutFile.getFile()), 1);
  6797. dup2(fileno(m_stderrFile.getFile()), 2);
  6798. }
  6799. OutputRedirect::~OutputRedirect() {
  6800. Catch::cout() << std::flush;
  6801. fflush(stdout);
  6802. // Since we support overriding these streams, we flush cerr
  6803. // even though std::cerr is unbuffered
  6804. Catch::cerr() << std::flush;
  6805. Catch::clog() << std::flush;
  6806. fflush(stderr);
  6807. dup2(m_originalStdout, 1);
  6808. dup2(m_originalStderr, 2);
  6809. m_stdoutDest += m_stdoutFile.getContents();
  6810. m_stderrDest += m_stderrFile.getContents();
  6811. }
  6812. #endif // CATCH_CONFIG_NEW_CAPTURE
  6813. } // namespace Catch
  6814. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  6815. #if defined(_MSC_VER)
  6816. #undef dup
  6817. #undef dup2
  6818. #undef fileno
  6819. #endif
  6820. #endif
  6821. // end catch_output_redirect.cpp
  6822. // start catch_random_number_generator.cpp
  6823. // start catch_random_number_generator.h
  6824. #include <algorithm>
  6825. #include <random>
  6826. namespace Catch {
  6827. struct IConfig;
  6828. std::mt19937& rng();
  6829. void seedRng( IConfig const& config );
  6830. unsigned int rngSeed();
  6831. }
  6832. // end catch_random_number_generator.h
  6833. namespace Catch {
  6834. std::mt19937& rng() {
  6835. static std::mt19937 s_rng;
  6836. return s_rng;
  6837. }
  6838. void seedRng( IConfig const& config ) {
  6839. if( config.rngSeed() != 0 ) {
  6840. std::srand( config.rngSeed() );
  6841. rng().seed( config.rngSeed() );
  6842. }
  6843. }
  6844. unsigned int rngSeed() {
  6845. return getCurrentContext().getConfig()->rngSeed();
  6846. }
  6847. }
  6848. // end catch_random_number_generator.cpp
  6849. // start catch_registry_hub.cpp
  6850. // start catch_test_case_registry_impl.h
  6851. #include <vector>
  6852. #include <set>
  6853. #include <algorithm>
  6854. #include <ios>
  6855. namespace Catch {
  6856. class TestCase;
  6857. struct IConfig;
  6858. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  6859. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  6860. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  6861. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  6862. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  6863. class TestRegistry : public ITestCaseRegistry {
  6864. public:
  6865. virtual ~TestRegistry() = default;
  6866. virtual void registerTest( TestCase const& testCase );
  6867. std::vector<TestCase> const& getAllTests() const override;
  6868. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  6869. private:
  6870. std::vector<TestCase> m_functions;
  6871. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  6872. mutable std::vector<TestCase> m_sortedFunctions;
  6873. std::size_t m_unnamedCount = 0;
  6874. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  6875. };
  6876. ///////////////////////////////////////////////////////////////////////////
  6877. class TestInvokerAsFunction : public ITestInvoker {
  6878. void(*m_testAsFunction)();
  6879. public:
  6880. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  6881. void invoke() const override;
  6882. };
  6883. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  6884. ///////////////////////////////////////////////////////////////////////////
  6885. } // end namespace Catch
  6886. // end catch_test_case_registry_impl.h
  6887. // start catch_reporter_registry.h
  6888. #include <map>
  6889. namespace Catch {
  6890. class ReporterRegistry : public IReporterRegistry {
  6891. public:
  6892. ~ReporterRegistry() override;
  6893. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  6894. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  6895. void registerListener( IReporterFactoryPtr const& factory );
  6896. FactoryMap const& getFactories() const override;
  6897. Listeners const& getListeners() const override;
  6898. private:
  6899. FactoryMap m_factories;
  6900. Listeners m_listeners;
  6901. };
  6902. }
  6903. // end catch_reporter_registry.h
  6904. // start catch_tag_alias_registry.h
  6905. // start catch_tag_alias.h
  6906. #include <string>
  6907. namespace Catch {
  6908. struct TagAlias {
  6909. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  6910. std::string tag;
  6911. SourceLineInfo lineInfo;
  6912. };
  6913. } // end namespace Catch
  6914. // end catch_tag_alias.h
  6915. #include <map>
  6916. namespace Catch {
  6917. class TagAliasRegistry : public ITagAliasRegistry {
  6918. public:
  6919. ~TagAliasRegistry() override;
  6920. TagAlias const* find( std::string const& alias ) const override;
  6921. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  6922. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  6923. private:
  6924. std::map<std::string, TagAlias> m_registry;
  6925. };
  6926. } // end namespace Catch
  6927. // end catch_tag_alias_registry.h
  6928. // start catch_startup_exception_registry.h
  6929. #include <vector>
  6930. #include <exception>
  6931. namespace Catch {
  6932. class StartupExceptionRegistry {
  6933. public:
  6934. void add(std::exception_ptr const& exception) noexcept;
  6935. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  6936. private:
  6937. std::vector<std::exception_ptr> m_exceptions;
  6938. };
  6939. } // end namespace Catch
  6940. // end catch_startup_exception_registry.h
  6941. namespace Catch {
  6942. namespace {
  6943. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  6944. private NonCopyable {
  6945. public: // IRegistryHub
  6946. RegistryHub() = default;
  6947. IReporterRegistry const& getReporterRegistry() const override {
  6948. return m_reporterRegistry;
  6949. }
  6950. ITestCaseRegistry const& getTestCaseRegistry() const override {
  6951. return m_testCaseRegistry;
  6952. }
  6953. IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() override {
  6954. return m_exceptionTranslatorRegistry;
  6955. }
  6956. ITagAliasRegistry const& getTagAliasRegistry() const override {
  6957. return m_tagAliasRegistry;
  6958. }
  6959. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  6960. return m_exceptionRegistry;
  6961. }
  6962. public: // IMutableRegistryHub
  6963. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  6964. m_reporterRegistry.registerReporter( name, factory );
  6965. }
  6966. void registerListener( IReporterFactoryPtr const& factory ) override {
  6967. m_reporterRegistry.registerListener( factory );
  6968. }
  6969. void registerTest( TestCase const& testInfo ) override {
  6970. m_testCaseRegistry.registerTest( testInfo );
  6971. }
  6972. void registerTranslator( const IExceptionTranslator* translator ) override {
  6973. m_exceptionTranslatorRegistry.registerTranslator( translator );
  6974. }
  6975. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  6976. m_tagAliasRegistry.add( alias, tag, lineInfo );
  6977. }
  6978. void registerStartupException() noexcept override {
  6979. m_exceptionRegistry.add(std::current_exception());
  6980. }
  6981. private:
  6982. TestRegistry m_testCaseRegistry;
  6983. ReporterRegistry m_reporterRegistry;
  6984. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  6985. TagAliasRegistry m_tagAliasRegistry;
  6986. StartupExceptionRegistry m_exceptionRegistry;
  6987. };
  6988. // Single, global, instance
  6989. RegistryHub*& getTheRegistryHub() {
  6990. static RegistryHub* theRegistryHub = nullptr;
  6991. if( !theRegistryHub )
  6992. theRegistryHub = new RegistryHub();
  6993. return theRegistryHub;
  6994. }
  6995. }
  6996. IRegistryHub& getRegistryHub() {
  6997. return *getTheRegistryHub();
  6998. }
  6999. IMutableRegistryHub& getMutableRegistryHub() {
  7000. return *getTheRegistryHub();
  7001. }
  7002. void cleanUp() {
  7003. delete getTheRegistryHub();
  7004. getTheRegistryHub() = nullptr;
  7005. cleanUpContext();
  7006. ReusableStringStream::cleanup();
  7007. }
  7008. std::string translateActiveException() {
  7009. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  7010. }
  7011. } // end namespace Catch
  7012. // end catch_registry_hub.cpp
  7013. // start catch_reporter_registry.cpp
  7014. namespace Catch {
  7015. ReporterRegistry::~ReporterRegistry() = default;
  7016. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  7017. auto it = m_factories.find( name );
  7018. if( it == m_factories.end() )
  7019. return nullptr;
  7020. return it->second->create( ReporterConfig( config ) );
  7021. }
  7022. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  7023. m_factories.emplace(name, factory);
  7024. }
  7025. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  7026. m_listeners.push_back( factory );
  7027. }
  7028. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  7029. return m_factories;
  7030. }
  7031. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  7032. return m_listeners;
  7033. }
  7034. }
  7035. // end catch_reporter_registry.cpp
  7036. // start catch_result_type.cpp
  7037. namespace Catch {
  7038. bool isOk( ResultWas::OfType resultType ) {
  7039. return ( resultType & ResultWas::FailureBit ) == 0;
  7040. }
  7041. bool isJustInfo( int flags ) {
  7042. return flags == ResultWas::Info;
  7043. }
  7044. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  7045. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  7046. }
  7047. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  7048. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  7049. } // end namespace Catch
  7050. // end catch_result_type.cpp
  7051. // start catch_run_context.cpp
  7052. #include <cassert>
  7053. #include <algorithm>
  7054. #include <sstream>
  7055. namespace Catch {
  7056. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  7057. : m_runInfo(_config->name()),
  7058. m_context(getCurrentMutableContext()),
  7059. m_config(_config),
  7060. m_reporter(std::move(reporter)),
  7061. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  7062. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  7063. {
  7064. m_context.setRunner(this);
  7065. m_context.setConfig(m_config);
  7066. m_context.setResultCapture(this);
  7067. m_reporter->testRunStarting(m_runInfo);
  7068. }
  7069. RunContext::~RunContext() {
  7070. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  7071. }
  7072. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  7073. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  7074. }
  7075. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  7076. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  7077. }
  7078. Totals RunContext::runTest(TestCase const& testCase) {
  7079. Totals prevTotals = m_totals;
  7080. std::string redirectedCout;
  7081. std::string redirectedCerr;
  7082. auto const& testInfo = testCase.getTestCaseInfo();
  7083. m_reporter->testCaseStarting(testInfo);
  7084. m_activeTestCase = &testCase;
  7085. ITracker& rootTracker = m_trackerContext.startRun();
  7086. assert(rootTracker.isSectionTracker());
  7087. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  7088. do {
  7089. m_trackerContext.startCycle();
  7090. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  7091. runCurrentTest(redirectedCout, redirectedCerr);
  7092. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  7093. Totals deltaTotals = m_totals.delta(prevTotals);
  7094. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  7095. deltaTotals.assertions.failed++;
  7096. deltaTotals.testCases.passed--;
  7097. deltaTotals.testCases.failed++;
  7098. }
  7099. m_totals.testCases += deltaTotals.testCases;
  7100. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  7101. deltaTotals,
  7102. redirectedCout,
  7103. redirectedCerr,
  7104. aborting()));
  7105. m_activeTestCase = nullptr;
  7106. m_testCaseTracker = nullptr;
  7107. return deltaTotals;
  7108. }
  7109. IConfigPtr RunContext::config() const {
  7110. return m_config;
  7111. }
  7112. IStreamingReporter& RunContext::reporter() const {
  7113. return *m_reporter;
  7114. }
  7115. void RunContext::assertionEnded(AssertionResult const & result) {
  7116. if (result.getResultType() == ResultWas::Ok) {
  7117. m_totals.assertions.passed++;
  7118. m_lastAssertionPassed = true;
  7119. } else if (!result.isOk()) {
  7120. m_lastAssertionPassed = false;
  7121. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  7122. m_totals.assertions.failedButOk++;
  7123. else
  7124. m_totals.assertions.failed++;
  7125. }
  7126. else {
  7127. m_lastAssertionPassed = true;
  7128. }
  7129. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  7130. // and should be let to clear themselves out.
  7131. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  7132. // Reset working state
  7133. resetAssertionInfo();
  7134. m_lastResult = result;
  7135. }
  7136. void RunContext::resetAssertionInfo() {
  7137. m_lastAssertionInfo.macroName = StringRef();
  7138. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  7139. }
  7140. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  7141. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  7142. if (!sectionTracker.isOpen())
  7143. return false;
  7144. m_activeSections.push_back(&sectionTracker);
  7145. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  7146. m_reporter->sectionStarting(sectionInfo);
  7147. assertions = m_totals.assertions;
  7148. return true;
  7149. }
  7150. bool RunContext::testForMissingAssertions(Counts& assertions) {
  7151. if (assertions.total() != 0)
  7152. return false;
  7153. if (!m_config->warnAboutMissingAssertions())
  7154. return false;
  7155. if (m_trackerContext.currentTracker().hasChildren())
  7156. return false;
  7157. m_totals.assertions.failed++;
  7158. assertions.failed++;
  7159. return true;
  7160. }
  7161. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  7162. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  7163. bool missingAssertions = testForMissingAssertions(assertions);
  7164. if (!m_activeSections.empty()) {
  7165. m_activeSections.back()->close();
  7166. m_activeSections.pop_back();
  7167. }
  7168. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  7169. m_messages.clear();
  7170. }
  7171. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  7172. if (m_unfinishedSections.empty())
  7173. m_activeSections.back()->fail();
  7174. else
  7175. m_activeSections.back()->close();
  7176. m_activeSections.pop_back();
  7177. m_unfinishedSections.push_back(endInfo);
  7178. }
  7179. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  7180. m_reporter->benchmarkStarting( info );
  7181. }
  7182. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  7183. m_reporter->benchmarkEnded( stats );
  7184. }
  7185. void RunContext::pushScopedMessage(MessageInfo const & message) {
  7186. m_messages.push_back(message);
  7187. }
  7188. void RunContext::popScopedMessage(MessageInfo const & message) {
  7189. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  7190. }
  7191. std::string RunContext::getCurrentTestName() const {
  7192. return m_activeTestCase
  7193. ? m_activeTestCase->getTestCaseInfo().name
  7194. : std::string();
  7195. }
  7196. const AssertionResult * RunContext::getLastResult() const {
  7197. return &(*m_lastResult);
  7198. }
  7199. void RunContext::exceptionEarlyReported() {
  7200. m_shouldReportUnexpected = false;
  7201. }
  7202. void RunContext::handleFatalErrorCondition( StringRef message ) {
  7203. // First notify reporter that bad things happened
  7204. m_reporter->fatalErrorEncountered(message);
  7205. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  7206. // Instead, fake a result data.
  7207. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  7208. tempResult.message = message;
  7209. AssertionResult result(m_lastAssertionInfo, tempResult);
  7210. assertionEnded(result);
  7211. handleUnfinishedSections();
  7212. // Recreate section for test case (as we will lose the one that was in scope)
  7213. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  7214. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  7215. Counts assertions;
  7216. assertions.failed = 1;
  7217. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  7218. m_reporter->sectionEnded(testCaseSectionStats);
  7219. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  7220. Totals deltaTotals;
  7221. deltaTotals.testCases.failed = 1;
  7222. deltaTotals.assertions.failed = 1;
  7223. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  7224. deltaTotals,
  7225. std::string(),
  7226. std::string(),
  7227. false));
  7228. m_totals.testCases.failed++;
  7229. testGroupEnded(std::string(), m_totals, 1, 1);
  7230. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  7231. }
  7232. bool RunContext::lastAssertionPassed() {
  7233. return m_lastAssertionPassed;
  7234. }
  7235. void RunContext::assertionPassed() {
  7236. m_lastAssertionPassed = true;
  7237. ++m_totals.assertions.passed;
  7238. resetAssertionInfo();
  7239. }
  7240. bool RunContext::aborting() const {
  7241. return m_totals.assertions.failed == static_cast<std::size_t>(m_config->abortAfter());
  7242. }
  7243. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  7244. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  7245. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  7246. m_reporter->sectionStarting(testCaseSection);
  7247. Counts prevAssertions = m_totals.assertions;
  7248. double duration = 0;
  7249. m_shouldReportUnexpected = true;
  7250. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  7251. seedRng(*m_config);
  7252. Timer timer;
  7253. try {
  7254. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  7255. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  7256. RedirectedStdOut redirectedStdOut;
  7257. RedirectedStdErr redirectedStdErr;
  7258. timer.start();
  7259. invokeActiveTestCase();
  7260. redirectedCout += redirectedStdOut.str();
  7261. redirectedCerr += redirectedStdErr.str();
  7262. #else
  7263. OutputRedirect r(redirectedCout, redirectedCerr);
  7264. timer.start();
  7265. invokeActiveTestCase();
  7266. #endif
  7267. } else {
  7268. timer.start();
  7269. invokeActiveTestCase();
  7270. }
  7271. duration = timer.getElapsedSeconds();
  7272. } catch (TestFailureException&) {
  7273. // This just means the test was aborted due to failure
  7274. } catch (...) {
  7275. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  7276. // are reported without translation at the point of origin.
  7277. if( m_shouldReportUnexpected ) {
  7278. AssertionReaction dummyReaction;
  7279. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  7280. }
  7281. }
  7282. Counts assertions = m_totals.assertions - prevAssertions;
  7283. bool missingAssertions = testForMissingAssertions(assertions);
  7284. m_testCaseTracker->close();
  7285. handleUnfinishedSections();
  7286. m_messages.clear();
  7287. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  7288. m_reporter->sectionEnded(testCaseSectionStats);
  7289. }
  7290. void RunContext::invokeActiveTestCase() {
  7291. FatalConditionHandler fatalConditionHandler; // Handle signals
  7292. m_activeTestCase->invoke();
  7293. fatalConditionHandler.reset();
  7294. }
  7295. void RunContext::handleUnfinishedSections() {
  7296. // If sections ended prematurely due to an exception we stored their
  7297. // infos here so we can tear them down outside the unwind process.
  7298. for (auto it = m_unfinishedSections.rbegin(),
  7299. itEnd = m_unfinishedSections.rend();
  7300. it != itEnd;
  7301. ++it)
  7302. sectionEnded(*it);
  7303. m_unfinishedSections.clear();
  7304. }
  7305. void RunContext::handleExpr(
  7306. AssertionInfo const& info,
  7307. ITransientExpression const& expr,
  7308. AssertionReaction& reaction
  7309. ) {
  7310. m_reporter->assertionStarting( info );
  7311. bool negated = isFalseTest( info.resultDisposition );
  7312. bool result = expr.getResult() != negated;
  7313. if( result ) {
  7314. if (!m_includeSuccessfulResults) {
  7315. assertionPassed();
  7316. }
  7317. else {
  7318. reportExpr(info, ResultWas::Ok, &expr, negated);
  7319. }
  7320. }
  7321. else {
  7322. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  7323. populateReaction( reaction );
  7324. }
  7325. }
  7326. void RunContext::reportExpr(
  7327. AssertionInfo const &info,
  7328. ResultWas::OfType resultType,
  7329. ITransientExpression const *expr,
  7330. bool negated ) {
  7331. m_lastAssertionInfo = info;
  7332. AssertionResultData data( resultType, LazyExpression( negated ) );
  7333. AssertionResult assertionResult{ info, data };
  7334. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  7335. assertionEnded( assertionResult );
  7336. }
  7337. void RunContext::handleMessage(
  7338. AssertionInfo const& info,
  7339. ResultWas::OfType resultType,
  7340. StringRef const& message,
  7341. AssertionReaction& reaction
  7342. ) {
  7343. m_reporter->assertionStarting( info );
  7344. m_lastAssertionInfo = info;
  7345. AssertionResultData data( resultType, LazyExpression( false ) );
  7346. data.message = message;
  7347. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  7348. assertionEnded( assertionResult );
  7349. if( !assertionResult.isOk() )
  7350. populateReaction( reaction );
  7351. }
  7352. void RunContext::handleUnexpectedExceptionNotThrown(
  7353. AssertionInfo const& info,
  7354. AssertionReaction& reaction
  7355. ) {
  7356. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  7357. }
  7358. void RunContext::handleUnexpectedInflightException(
  7359. AssertionInfo const& info,
  7360. std::string const& message,
  7361. AssertionReaction& reaction
  7362. ) {
  7363. m_lastAssertionInfo = info;
  7364. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  7365. data.message = message;
  7366. AssertionResult assertionResult{ info, data };
  7367. assertionEnded( assertionResult );
  7368. populateReaction( reaction );
  7369. }
  7370. void RunContext::populateReaction( AssertionReaction& reaction ) {
  7371. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  7372. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  7373. }
  7374. void RunContext::handleIncomplete(
  7375. AssertionInfo const& info
  7376. ) {
  7377. m_lastAssertionInfo = info;
  7378. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  7379. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  7380. AssertionResult assertionResult{ info, data };
  7381. assertionEnded( assertionResult );
  7382. }
  7383. void RunContext::handleNonExpr(
  7384. AssertionInfo const &info,
  7385. ResultWas::OfType resultType,
  7386. AssertionReaction &reaction
  7387. ) {
  7388. m_lastAssertionInfo = info;
  7389. AssertionResultData data( resultType, LazyExpression( false ) );
  7390. AssertionResult assertionResult{ info, data };
  7391. assertionEnded( assertionResult );
  7392. if( !assertionResult.isOk() )
  7393. populateReaction( reaction );
  7394. }
  7395. IResultCapture& getResultCapture() {
  7396. if (auto* capture = getCurrentContext().getResultCapture())
  7397. return *capture;
  7398. else
  7399. CATCH_INTERNAL_ERROR("No result capture instance");
  7400. }
  7401. }
  7402. // end catch_run_context.cpp
  7403. // start catch_section.cpp
  7404. namespace Catch {
  7405. Section::Section( SectionInfo const& info )
  7406. : m_info( info ),
  7407. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  7408. {
  7409. m_timer.start();
  7410. }
  7411. Section::~Section() {
  7412. if( m_sectionIncluded ) {
  7413. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  7414. if( uncaught_exceptions() )
  7415. getResultCapture().sectionEndedEarly( endInfo );
  7416. else
  7417. getResultCapture().sectionEnded( endInfo );
  7418. }
  7419. }
  7420. // This indicates whether the section should be executed or not
  7421. Section::operator bool() const {
  7422. return m_sectionIncluded;
  7423. }
  7424. } // end namespace Catch
  7425. // end catch_section.cpp
  7426. // start catch_section_info.cpp
  7427. namespace Catch {
  7428. SectionInfo::SectionInfo
  7429. ( SourceLineInfo const& _lineInfo,
  7430. std::string const& _name )
  7431. : name( _name ),
  7432. lineInfo( _lineInfo )
  7433. {}
  7434. } // end namespace Catch
  7435. // end catch_section_info.cpp
  7436. // start catch_session.cpp
  7437. // start catch_session.h
  7438. #include <memory>
  7439. namespace Catch {
  7440. class Session : NonCopyable {
  7441. public:
  7442. Session();
  7443. ~Session() override;
  7444. void showHelp() const;
  7445. void libIdentify();
  7446. int applyCommandLine( int argc, char const * const * argv );
  7447. void useConfigData( ConfigData const& configData );
  7448. int run( int argc, char* argv[] );
  7449. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  7450. int run( int argc, wchar_t* const argv[] );
  7451. #endif
  7452. int run();
  7453. clara::Parser const& cli() const;
  7454. void cli( clara::Parser const& newParser );
  7455. ConfigData& configData();
  7456. Config& config();
  7457. private:
  7458. int runInternal();
  7459. clara::Parser m_cli;
  7460. ConfigData m_configData;
  7461. std::shared_ptr<Config> m_config;
  7462. bool m_startupExceptions = false;
  7463. };
  7464. } // end namespace Catch
  7465. // end catch_session.h
  7466. // start catch_version.h
  7467. #include <iosfwd>
  7468. namespace Catch {
  7469. // Versioning information
  7470. struct Version {
  7471. Version( Version const& ) = delete;
  7472. Version& operator=( Version const& ) = delete;
  7473. Version( unsigned int _majorVersion,
  7474. unsigned int _minorVersion,
  7475. unsigned int _patchNumber,
  7476. char const * const _branchName,
  7477. unsigned int _buildNumber );
  7478. unsigned int const majorVersion;
  7479. unsigned int const minorVersion;
  7480. unsigned int const patchNumber;
  7481. // buildNumber is only used if branchName is not null
  7482. char const * const branchName;
  7483. unsigned int const buildNumber;
  7484. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  7485. };
  7486. Version const& libraryVersion();
  7487. }
  7488. // end catch_version.h
  7489. #include <cstdlib>
  7490. #include <iomanip>
  7491. namespace Catch {
  7492. namespace {
  7493. const int MaxExitCode = 255;
  7494. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  7495. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  7496. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  7497. return reporter;
  7498. }
  7499. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  7500. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  7501. return createReporter(config->getReporterName(), config);
  7502. }
  7503. auto multi = std::unique_ptr<ListeningReporter>(new ListeningReporter);
  7504. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  7505. for (auto const& listener : listeners) {
  7506. multi->addListener(listener->create(Catch::ReporterConfig(config)));
  7507. }
  7508. multi->addReporter(createReporter(config->getReporterName(), config));
  7509. return std::move(multi);
  7510. }
  7511. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  7512. // FixMe: Add listeners in order first, then add reporters.
  7513. auto reporter = makeReporter(config);
  7514. RunContext context(config, std::move(reporter));
  7515. Totals totals;
  7516. context.testGroupStarting(config->name(), 1, 1);
  7517. TestSpec testSpec = config->testSpec();
  7518. auto const& allTestCases = getAllTestCasesSorted(*config);
  7519. for (auto const& testCase : allTestCases) {
  7520. if (!context.aborting() && matchTest(testCase, testSpec, *config))
  7521. totals += context.runTest(testCase);
  7522. else
  7523. context.reporter().skipTest(testCase);
  7524. }
  7525. if (config->warnAboutNoTests() && totals.testCases.total() == 0) {
  7526. ReusableStringStream testConfig;
  7527. bool first = true;
  7528. for (const auto& input : config->getTestsOrTags()) {
  7529. if (!first) { testConfig << ' '; }
  7530. first = false;
  7531. testConfig << input;
  7532. }
  7533. context.reporter().noMatchingTestCases(testConfig.str());
  7534. totals.error = -1;
  7535. }
  7536. context.testGroupEnded(config->name(), totals, 1, 1);
  7537. return totals;
  7538. }
  7539. void applyFilenamesAsTags(Catch::IConfig const& config) {
  7540. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  7541. for (auto& testCase : tests) {
  7542. auto tags = testCase.tags;
  7543. std::string filename = testCase.lineInfo.file;
  7544. auto lastSlash = filename.find_last_of("\\/");
  7545. if (lastSlash != std::string::npos) {
  7546. filename.erase(0, lastSlash);
  7547. filename[0] = '#';
  7548. }
  7549. auto lastDot = filename.find_last_of('.');
  7550. if (lastDot != std::string::npos) {
  7551. filename.erase(lastDot);
  7552. }
  7553. tags.push_back(std::move(filename));
  7554. setTags(testCase, tags);
  7555. }
  7556. }
  7557. } // anon namespace
  7558. Session::Session() {
  7559. static bool alreadyInstantiated = false;
  7560. if( alreadyInstantiated ) {
  7561. try { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  7562. catch(...) { getMutableRegistryHub().registerStartupException(); }
  7563. }
  7564. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  7565. if ( !exceptions.empty() ) {
  7566. m_startupExceptions = true;
  7567. Colour colourGuard( Colour::Red );
  7568. Catch::cerr() << "Errors occurred during startup!" << '\n';
  7569. // iterate over all exceptions and notify user
  7570. for ( const auto& ex_ptr : exceptions ) {
  7571. try {
  7572. std::rethrow_exception(ex_ptr);
  7573. } catch ( std::exception const& ex ) {
  7574. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  7575. }
  7576. }
  7577. }
  7578. alreadyInstantiated = true;
  7579. m_cli = makeCommandLineParser( m_configData );
  7580. }
  7581. Session::~Session() {
  7582. Catch::cleanUp();
  7583. }
  7584. void Session::showHelp() const {
  7585. Catch::cout()
  7586. << "\nCatch v" << libraryVersion() << "\n"
  7587. << m_cli << std::endl
  7588. << "For more detailed usage please see the project docs\n" << std::endl;
  7589. }
  7590. void Session::libIdentify() {
  7591. Catch::cout()
  7592. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  7593. << std::left << std::setw(16) << "category: " << "testframework\n"
  7594. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  7595. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  7596. }
  7597. int Session::applyCommandLine( int argc, char const * const * argv ) {
  7598. if( m_startupExceptions )
  7599. return 1;
  7600. auto result = m_cli.parse( clara::Args( argc, argv ) );
  7601. if( !result ) {
  7602. Catch::cerr()
  7603. << Colour( Colour::Red )
  7604. << "\nError(s) in input:\n"
  7605. << Column( result.errorMessage() ).indent( 2 )
  7606. << "\n\n";
  7607. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  7608. return MaxExitCode;
  7609. }
  7610. if( m_configData.showHelp )
  7611. showHelp();
  7612. if( m_configData.libIdentify )
  7613. libIdentify();
  7614. m_config.reset();
  7615. return 0;
  7616. }
  7617. void Session::useConfigData( ConfigData const& configData ) {
  7618. m_configData = configData;
  7619. m_config.reset();
  7620. }
  7621. int Session::run( int argc, char* argv[] ) {
  7622. if( m_startupExceptions )
  7623. return 1;
  7624. int returnCode = applyCommandLine( argc, argv );
  7625. if( returnCode == 0 )
  7626. returnCode = run();
  7627. return returnCode;
  7628. }
  7629. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  7630. int Session::run( int argc, wchar_t* const argv[] ) {
  7631. char **utf8Argv = new char *[ argc ];
  7632. for ( int i = 0; i < argc; ++i ) {
  7633. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  7634. utf8Argv[ i ] = new char[ bufSize ];
  7635. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  7636. }
  7637. int returnCode = run( argc, utf8Argv );
  7638. for ( int i = 0; i < argc; ++i )
  7639. delete [] utf8Argv[ i ];
  7640. delete [] utf8Argv;
  7641. return returnCode;
  7642. }
  7643. #endif
  7644. int Session::run() {
  7645. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  7646. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  7647. static_cast<void>(std::getchar());
  7648. }
  7649. int exitCode = runInternal();
  7650. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  7651. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  7652. static_cast<void>(std::getchar());
  7653. }
  7654. return exitCode;
  7655. }
  7656. clara::Parser const& Session::cli() const {
  7657. return m_cli;
  7658. }
  7659. void Session::cli( clara::Parser const& newParser ) {
  7660. m_cli = newParser;
  7661. }
  7662. ConfigData& Session::configData() {
  7663. return m_configData;
  7664. }
  7665. Config& Session::config() {
  7666. if( !m_config )
  7667. m_config = std::make_shared<Config>( m_configData );
  7668. return *m_config;
  7669. }
  7670. int Session::runInternal() {
  7671. if( m_startupExceptions )
  7672. return 1;
  7673. if( m_configData.showHelp || m_configData.libIdentify )
  7674. return 0;
  7675. try
  7676. {
  7677. config(); // Force config to be constructed
  7678. seedRng( *m_config );
  7679. if( m_configData.filenamesAsTags )
  7680. applyFilenamesAsTags( *m_config );
  7681. // Handle list request
  7682. if( Option<std::size_t> listed = list( config() ) )
  7683. return static_cast<int>( *listed );
  7684. auto totals = runTests( m_config );
  7685. // Note that on unices only the lower 8 bits are usually used, clamping
  7686. // the return value to 255 prevents false negative when some multiple
  7687. // of 256 tests has failed
  7688. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  7689. }
  7690. catch( std::exception& ex ) {
  7691. Catch::cerr() << ex.what() << std::endl;
  7692. return MaxExitCode;
  7693. }
  7694. }
  7695. } // end namespace Catch
  7696. // end catch_session.cpp
  7697. // start catch_startup_exception_registry.cpp
  7698. namespace Catch {
  7699. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  7700. try {
  7701. m_exceptions.push_back(exception);
  7702. }
  7703. catch(...) {
  7704. // If we run out of memory during start-up there's really not a lot more we can do about it
  7705. std::terminate();
  7706. }
  7707. }
  7708. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  7709. return m_exceptions;
  7710. }
  7711. } // end namespace Catch
  7712. // end catch_startup_exception_registry.cpp
  7713. // start catch_stream.cpp
  7714. #include <cstdio>
  7715. #include <iostream>
  7716. #include <fstream>
  7717. #include <sstream>
  7718. #include <vector>
  7719. #include <memory>
  7720. #if defined(__clang__)
  7721. # pragma clang diagnostic push
  7722. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7723. #endif
  7724. namespace Catch {
  7725. Catch::IStream::~IStream() = default;
  7726. namespace detail { namespace {
  7727. template<typename WriterF, std::size_t bufferSize=256>
  7728. class StreamBufImpl : public std::streambuf {
  7729. char data[bufferSize];
  7730. WriterF m_writer;
  7731. public:
  7732. StreamBufImpl() {
  7733. setp( data, data + sizeof(data) );
  7734. }
  7735. ~StreamBufImpl() noexcept {
  7736. StreamBufImpl::sync();
  7737. }
  7738. private:
  7739. int overflow( int c ) override {
  7740. sync();
  7741. if( c != EOF ) {
  7742. if( pbase() == epptr() )
  7743. m_writer( std::string( 1, static_cast<char>( c ) ) );
  7744. else
  7745. sputc( static_cast<char>( c ) );
  7746. }
  7747. return 0;
  7748. }
  7749. int sync() override {
  7750. if( pbase() != pptr() ) {
  7751. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  7752. setp( pbase(), epptr() );
  7753. }
  7754. return 0;
  7755. }
  7756. };
  7757. ///////////////////////////////////////////////////////////////////////////
  7758. struct OutputDebugWriter {
  7759. void operator()( std::string const&str ) {
  7760. writeToDebugConsole( str );
  7761. }
  7762. };
  7763. ///////////////////////////////////////////////////////////////////////////
  7764. class FileStream : public IStream {
  7765. mutable std::ofstream m_ofs;
  7766. public:
  7767. FileStream( StringRef filename ) {
  7768. m_ofs.open( filename.c_str() );
  7769. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  7770. }
  7771. ~FileStream() override = default;
  7772. public: // IStream
  7773. std::ostream& stream() const override {
  7774. return m_ofs;
  7775. }
  7776. };
  7777. ///////////////////////////////////////////////////////////////////////////
  7778. class CoutStream : public IStream {
  7779. mutable std::ostream m_os;
  7780. public:
  7781. // Store the streambuf from cout up-front because
  7782. // cout may get redirected when running tests
  7783. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  7784. ~CoutStream() override = default;
  7785. public: // IStream
  7786. std::ostream& stream() const override { return m_os; }
  7787. };
  7788. ///////////////////////////////////////////////////////////////////////////
  7789. class DebugOutStream : public IStream {
  7790. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  7791. mutable std::ostream m_os;
  7792. public:
  7793. DebugOutStream()
  7794. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  7795. m_os( m_streamBuf.get() )
  7796. {}
  7797. ~DebugOutStream() override = default;
  7798. public: // IStream
  7799. std::ostream& stream() const override { return m_os; }
  7800. };
  7801. }} // namespace anon::detail
  7802. ///////////////////////////////////////////////////////////////////////////
  7803. auto makeStream( StringRef const &filename ) -> IStream const* {
  7804. if( filename.empty() )
  7805. return new detail::CoutStream();
  7806. else if( filename[0] == '%' ) {
  7807. if( filename == "%debug" )
  7808. return new detail::DebugOutStream();
  7809. else
  7810. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  7811. }
  7812. else
  7813. return new detail::FileStream( filename );
  7814. }
  7815. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  7816. struct StringStreams {
  7817. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  7818. std::vector<std::size_t> m_unused;
  7819. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  7820. static StringStreams* s_instance;
  7821. auto add() -> std::size_t {
  7822. if( m_unused.empty() ) {
  7823. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  7824. return m_streams.size()-1;
  7825. }
  7826. else {
  7827. auto index = m_unused.back();
  7828. m_unused.pop_back();
  7829. return index;
  7830. }
  7831. }
  7832. void release( std::size_t index ) {
  7833. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  7834. m_unused.push_back(index);
  7835. }
  7836. // !TBD: put in TLS
  7837. static auto instance() -> StringStreams& {
  7838. if( !s_instance )
  7839. s_instance = new StringStreams();
  7840. return *s_instance;
  7841. }
  7842. static void cleanup() {
  7843. delete s_instance;
  7844. s_instance = nullptr;
  7845. }
  7846. };
  7847. StringStreams* StringStreams::s_instance = nullptr;
  7848. void ReusableStringStream::cleanup() {
  7849. StringStreams::cleanup();
  7850. }
  7851. ReusableStringStream::ReusableStringStream()
  7852. : m_index( StringStreams::instance().add() ),
  7853. m_oss( StringStreams::instance().m_streams[m_index].get() )
  7854. {}
  7855. ReusableStringStream::~ReusableStringStream() {
  7856. static_cast<std::ostringstream*>( m_oss )->str("");
  7857. m_oss->clear();
  7858. StringStreams::instance().release( m_index );
  7859. }
  7860. auto ReusableStringStream::str() const -> std::string {
  7861. return static_cast<std::ostringstream*>( m_oss )->str();
  7862. }
  7863. ///////////////////////////////////////////////////////////////////////////
  7864. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  7865. std::ostream& cout() { return std::cout; }
  7866. std::ostream& cerr() { return std::cerr; }
  7867. std::ostream& clog() { return std::clog; }
  7868. #endif
  7869. }
  7870. #if defined(__clang__)
  7871. # pragma clang diagnostic pop
  7872. #endif
  7873. // end catch_stream.cpp
  7874. // start catch_string_manip.cpp
  7875. #include <algorithm>
  7876. #include <ostream>
  7877. #include <cstring>
  7878. #include <cctype>
  7879. namespace Catch {
  7880. namespace {
  7881. char toLowerCh(char c) {
  7882. return static_cast<char>( std::tolower( c ) );
  7883. }
  7884. }
  7885. bool startsWith( std::string const& s, std::string const& prefix ) {
  7886. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  7887. }
  7888. bool startsWith( std::string const& s, char prefix ) {
  7889. return !s.empty() && s[0] == prefix;
  7890. }
  7891. bool endsWith( std::string const& s, std::string const& suffix ) {
  7892. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  7893. }
  7894. bool endsWith( std::string const& s, char suffix ) {
  7895. return !s.empty() && s[s.size()-1] == suffix;
  7896. }
  7897. bool contains( std::string const& s, std::string const& infix ) {
  7898. return s.find( infix ) != std::string::npos;
  7899. }
  7900. void toLowerInPlace( std::string& s ) {
  7901. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  7902. }
  7903. std::string toLower( std::string const& s ) {
  7904. std::string lc = s;
  7905. toLowerInPlace( lc );
  7906. return lc;
  7907. }
  7908. std::string trim( std::string const& str ) {
  7909. static char const* whitespaceChars = "\n\r\t ";
  7910. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  7911. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  7912. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  7913. }
  7914. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  7915. bool replaced = false;
  7916. std::size_t i = str.find( replaceThis );
  7917. while( i != std::string::npos ) {
  7918. replaced = true;
  7919. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  7920. if( i < str.size()-withThis.size() )
  7921. i = str.find( replaceThis, i+withThis.size() );
  7922. else
  7923. i = std::string::npos;
  7924. }
  7925. return replaced;
  7926. }
  7927. pluralise::pluralise( std::size_t count, std::string const& label )
  7928. : m_count( count ),
  7929. m_label( label )
  7930. {}
  7931. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  7932. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  7933. if( pluraliser.m_count != 1 )
  7934. os << 's';
  7935. return os;
  7936. }
  7937. }
  7938. // end catch_string_manip.cpp
  7939. // start catch_stringref.cpp
  7940. #if defined(__clang__)
  7941. # pragma clang diagnostic push
  7942. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  7943. #endif
  7944. #include <ostream>
  7945. #include <cstring>
  7946. #include <cstdint>
  7947. namespace {
  7948. const uint32_t byte_2_lead = 0xC0;
  7949. const uint32_t byte_3_lead = 0xE0;
  7950. const uint32_t byte_4_lead = 0xF0;
  7951. }
  7952. namespace Catch {
  7953. StringRef::StringRef( char const* rawChars ) noexcept
  7954. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  7955. {}
  7956. StringRef::operator std::string() const {
  7957. return std::string( m_start, m_size );
  7958. }
  7959. void StringRef::swap( StringRef& other ) noexcept {
  7960. std::swap( m_start, other.m_start );
  7961. std::swap( m_size, other.m_size );
  7962. std::swap( m_data, other.m_data );
  7963. }
  7964. auto StringRef::c_str() const -> char const* {
  7965. if( isSubstring() )
  7966. const_cast<StringRef*>( this )->takeOwnership();
  7967. return m_start;
  7968. }
  7969. auto StringRef::currentData() const noexcept -> char const* {
  7970. return m_start;
  7971. }
  7972. auto StringRef::isOwned() const noexcept -> bool {
  7973. return m_data != nullptr;
  7974. }
  7975. auto StringRef::isSubstring() const noexcept -> bool {
  7976. return m_start[m_size] != '\0';
  7977. }
  7978. void StringRef::takeOwnership() {
  7979. if( !isOwned() ) {
  7980. m_data = new char[m_size+1];
  7981. memcpy( m_data, m_start, m_size );
  7982. m_data[m_size] = '\0';
  7983. m_start = m_data;
  7984. }
  7985. }
  7986. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  7987. if( start < m_size )
  7988. return StringRef( m_start+start, size );
  7989. else
  7990. return StringRef();
  7991. }
  7992. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  7993. return
  7994. size() == other.size() &&
  7995. (std::strncmp( m_start, other.m_start, size() ) == 0);
  7996. }
  7997. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  7998. return !operator==( other );
  7999. }
  8000. auto StringRef::operator[](size_type index) const noexcept -> char {
  8001. return m_start[index];
  8002. }
  8003. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  8004. size_type noChars = m_size;
  8005. // Make adjustments for uft encodings
  8006. for( size_type i=0; i < m_size; ++i ) {
  8007. char c = m_start[i];
  8008. if( ( c & byte_2_lead ) == byte_2_lead ) {
  8009. noChars--;
  8010. if (( c & byte_3_lead ) == byte_3_lead )
  8011. noChars--;
  8012. if( ( c & byte_4_lead ) == byte_4_lead )
  8013. noChars--;
  8014. }
  8015. }
  8016. return noChars;
  8017. }
  8018. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  8019. std::string str;
  8020. str.reserve( lhs.size() + rhs.size() );
  8021. str += lhs;
  8022. str += rhs;
  8023. return str;
  8024. }
  8025. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  8026. return std::string( lhs ) + std::string( rhs );
  8027. }
  8028. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  8029. return std::string( lhs ) + std::string( rhs );
  8030. }
  8031. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  8032. return os.write(str.currentData(), str.size());
  8033. }
  8034. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  8035. lhs.append(rhs.currentData(), rhs.size());
  8036. return lhs;
  8037. }
  8038. } // namespace Catch
  8039. #if defined(__clang__)
  8040. # pragma clang diagnostic pop
  8041. #endif
  8042. // end catch_stringref.cpp
  8043. // start catch_tag_alias.cpp
  8044. namespace Catch {
  8045. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  8046. }
  8047. // end catch_tag_alias.cpp
  8048. // start catch_tag_alias_autoregistrar.cpp
  8049. namespace Catch {
  8050. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  8051. try {
  8052. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  8053. } catch (...) {
  8054. // Do not throw when constructing global objects, instead register the exception to be processed later
  8055. getMutableRegistryHub().registerStartupException();
  8056. }
  8057. }
  8058. }
  8059. // end catch_tag_alias_autoregistrar.cpp
  8060. // start catch_tag_alias_registry.cpp
  8061. #include <sstream>
  8062. namespace Catch {
  8063. TagAliasRegistry::~TagAliasRegistry() {}
  8064. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  8065. auto it = m_registry.find( alias );
  8066. if( it != m_registry.end() )
  8067. return &(it->second);
  8068. else
  8069. return nullptr;
  8070. }
  8071. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  8072. std::string expandedTestSpec = unexpandedTestSpec;
  8073. for( auto const& registryKvp : m_registry ) {
  8074. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  8075. if( pos != std::string::npos ) {
  8076. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  8077. registryKvp.second.tag +
  8078. expandedTestSpec.substr( pos + registryKvp.first.size() );
  8079. }
  8080. }
  8081. return expandedTestSpec;
  8082. }
  8083. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  8084. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  8085. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  8086. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  8087. "error: tag alias, '" << alias << "' already registered.\n"
  8088. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  8089. << "\tRedefined at: " << lineInfo );
  8090. }
  8091. ITagAliasRegistry::~ITagAliasRegistry() {}
  8092. ITagAliasRegistry const& ITagAliasRegistry::get() {
  8093. return getRegistryHub().getTagAliasRegistry();
  8094. }
  8095. } // end namespace Catch
  8096. // end catch_tag_alias_registry.cpp
  8097. // start catch_test_case_info.cpp
  8098. #include <cctype>
  8099. #include <exception>
  8100. #include <algorithm>
  8101. #include <sstream>
  8102. namespace Catch {
  8103. namespace {
  8104. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  8105. if( startsWith( tag, '.' ) ||
  8106. tag == "!hide" )
  8107. return TestCaseInfo::IsHidden;
  8108. else if( tag == "!throws" )
  8109. return TestCaseInfo::Throws;
  8110. else if( tag == "!shouldfail" )
  8111. return TestCaseInfo::ShouldFail;
  8112. else if( tag == "!mayfail" )
  8113. return TestCaseInfo::MayFail;
  8114. else if( tag == "!nonportable" )
  8115. return TestCaseInfo::NonPortable;
  8116. else if( tag == "!benchmark" )
  8117. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  8118. else
  8119. return TestCaseInfo::None;
  8120. }
  8121. bool isReservedTag( std::string const& tag ) {
  8122. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  8123. }
  8124. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  8125. CATCH_ENFORCE( !isReservedTag(tag),
  8126. "Tag name: [" << tag << "] is not allowed.\n"
  8127. << "Tag names starting with non alpha-numeric characters are reserved\n"
  8128. << _lineInfo );
  8129. }
  8130. }
  8131. TestCase makeTestCase( ITestInvoker* _testCase,
  8132. std::string const& _className,
  8133. NameAndTags const& nameAndTags,
  8134. SourceLineInfo const& _lineInfo )
  8135. {
  8136. bool isHidden = false;
  8137. // Parse out tags
  8138. std::vector<std::string> tags;
  8139. std::string desc, tag;
  8140. bool inTag = false;
  8141. std::string _descOrTags = nameAndTags.tags;
  8142. for (char c : _descOrTags) {
  8143. if( !inTag ) {
  8144. if( c == '[' )
  8145. inTag = true;
  8146. else
  8147. desc += c;
  8148. }
  8149. else {
  8150. if( c == ']' ) {
  8151. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  8152. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  8153. isHidden = true;
  8154. else if( prop == TestCaseInfo::None )
  8155. enforceNotReservedTag( tag, _lineInfo );
  8156. tags.push_back( tag );
  8157. tag.clear();
  8158. inTag = false;
  8159. }
  8160. else
  8161. tag += c;
  8162. }
  8163. }
  8164. if( isHidden ) {
  8165. tags.push_back( "." );
  8166. }
  8167. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  8168. return TestCase( _testCase, std::move(info) );
  8169. }
  8170. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  8171. std::sort(begin(tags), end(tags));
  8172. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  8173. testCaseInfo.lcaseTags.clear();
  8174. for( auto const& tag : tags ) {
  8175. std::string lcaseTag = toLower( tag );
  8176. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  8177. testCaseInfo.lcaseTags.push_back( lcaseTag );
  8178. }
  8179. testCaseInfo.tags = std::move(tags);
  8180. }
  8181. TestCaseInfo::TestCaseInfo( std::string const& _name,
  8182. std::string const& _className,
  8183. std::string const& _description,
  8184. std::vector<std::string> const& _tags,
  8185. SourceLineInfo const& _lineInfo )
  8186. : name( _name ),
  8187. className( _className ),
  8188. description( _description ),
  8189. lineInfo( _lineInfo ),
  8190. properties( None )
  8191. {
  8192. setTags( *this, _tags );
  8193. }
  8194. bool TestCaseInfo::isHidden() const {
  8195. return ( properties & IsHidden ) != 0;
  8196. }
  8197. bool TestCaseInfo::throws() const {
  8198. return ( properties & Throws ) != 0;
  8199. }
  8200. bool TestCaseInfo::okToFail() const {
  8201. return ( properties & (ShouldFail | MayFail ) ) != 0;
  8202. }
  8203. bool TestCaseInfo::expectedToFail() const {
  8204. return ( properties & (ShouldFail ) ) != 0;
  8205. }
  8206. std::string TestCaseInfo::tagsAsString() const {
  8207. std::string ret;
  8208. // '[' and ']' per tag
  8209. std::size_t full_size = 2 * tags.size();
  8210. for (const auto& tag : tags) {
  8211. full_size += tag.size();
  8212. }
  8213. ret.reserve(full_size);
  8214. for (const auto& tag : tags) {
  8215. ret.push_back('[');
  8216. ret.append(tag);
  8217. ret.push_back(']');
  8218. }
  8219. return ret;
  8220. }
  8221. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  8222. TestCase TestCase::withName( std::string const& _newName ) const {
  8223. TestCase other( *this );
  8224. other.name = _newName;
  8225. return other;
  8226. }
  8227. void TestCase::invoke() const {
  8228. test->invoke();
  8229. }
  8230. bool TestCase::operator == ( TestCase const& other ) const {
  8231. return test.get() == other.test.get() &&
  8232. name == other.name &&
  8233. className == other.className;
  8234. }
  8235. bool TestCase::operator < ( TestCase const& other ) const {
  8236. return name < other.name;
  8237. }
  8238. TestCaseInfo const& TestCase::getTestCaseInfo() const
  8239. {
  8240. return *this;
  8241. }
  8242. } // end namespace Catch
  8243. // end catch_test_case_info.cpp
  8244. // start catch_test_case_registry_impl.cpp
  8245. #include <sstream>
  8246. namespace Catch {
  8247. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  8248. std::vector<TestCase> sorted = unsortedTestCases;
  8249. switch( config.runOrder() ) {
  8250. case RunTests::InLexicographicalOrder:
  8251. std::sort( sorted.begin(), sorted.end() );
  8252. break;
  8253. case RunTests::InRandomOrder:
  8254. seedRng( config );
  8255. std::shuffle( sorted.begin(), sorted.end(), rng() );
  8256. break;
  8257. case RunTests::InDeclarationOrder:
  8258. // already in declaration order
  8259. break;
  8260. }
  8261. return sorted;
  8262. }
  8263. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  8264. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  8265. }
  8266. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  8267. std::set<TestCase> seenFunctions;
  8268. for( auto const& function : functions ) {
  8269. auto prev = seenFunctions.insert( function );
  8270. CATCH_ENFORCE( prev.second,
  8271. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  8272. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  8273. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  8274. }
  8275. }
  8276. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  8277. std::vector<TestCase> filtered;
  8278. filtered.reserve( testCases.size() );
  8279. for( auto const& testCase : testCases )
  8280. if( matchTest( testCase, testSpec, config ) )
  8281. filtered.push_back( testCase );
  8282. return filtered;
  8283. }
  8284. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  8285. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  8286. }
  8287. void TestRegistry::registerTest( TestCase const& testCase ) {
  8288. std::string name = testCase.getTestCaseInfo().name;
  8289. if( name.empty() ) {
  8290. ReusableStringStream rss;
  8291. rss << "Anonymous test case " << ++m_unnamedCount;
  8292. return registerTest( testCase.withName( rss.str() ) );
  8293. }
  8294. m_functions.push_back( testCase );
  8295. }
  8296. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  8297. return m_functions;
  8298. }
  8299. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  8300. if( m_sortedFunctions.empty() )
  8301. enforceNoDuplicateTestCases( m_functions );
  8302. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  8303. m_sortedFunctions = sortTests( config, m_functions );
  8304. m_currentSortOrder = config.runOrder();
  8305. }
  8306. return m_sortedFunctions;
  8307. }
  8308. ///////////////////////////////////////////////////////////////////////////
  8309. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  8310. void TestInvokerAsFunction::invoke() const {
  8311. m_testAsFunction();
  8312. }
  8313. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  8314. std::string className = classOrQualifiedMethodName;
  8315. if( startsWith( className, '&' ) )
  8316. {
  8317. std::size_t lastColons = className.rfind( "::" );
  8318. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  8319. if( penultimateColons == std::string::npos )
  8320. penultimateColons = 1;
  8321. className = className.substr( penultimateColons, lastColons-penultimateColons );
  8322. }
  8323. return className;
  8324. }
  8325. } // end namespace Catch
  8326. // end catch_test_case_registry_impl.cpp
  8327. // start catch_test_case_tracker.cpp
  8328. #include <algorithm>
  8329. #include <cassert>
  8330. #include <stdexcept>
  8331. #include <memory>
  8332. #include <sstream>
  8333. #if defined(__clang__)
  8334. # pragma clang diagnostic push
  8335. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8336. #endif
  8337. namespace Catch {
  8338. namespace TestCaseTracking {
  8339. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  8340. : name( _name ),
  8341. location( _location )
  8342. {}
  8343. ITracker::~ITracker() = default;
  8344. TrackerContext& TrackerContext::instance() {
  8345. static TrackerContext s_instance;
  8346. return s_instance;
  8347. }
  8348. ITracker& TrackerContext::startRun() {
  8349. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  8350. m_currentTracker = nullptr;
  8351. m_runState = Executing;
  8352. return *m_rootTracker;
  8353. }
  8354. void TrackerContext::endRun() {
  8355. m_rootTracker.reset();
  8356. m_currentTracker = nullptr;
  8357. m_runState = NotStarted;
  8358. }
  8359. void TrackerContext::startCycle() {
  8360. m_currentTracker = m_rootTracker.get();
  8361. m_runState = Executing;
  8362. }
  8363. void TrackerContext::completeCycle() {
  8364. m_runState = CompletedCycle;
  8365. }
  8366. bool TrackerContext::completedCycle() const {
  8367. return m_runState == CompletedCycle;
  8368. }
  8369. ITracker& TrackerContext::currentTracker() {
  8370. return *m_currentTracker;
  8371. }
  8372. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  8373. m_currentTracker = tracker;
  8374. }
  8375. TrackerBase::TrackerHasName::TrackerHasName( NameAndLocation const& nameAndLocation ) : m_nameAndLocation( nameAndLocation ) {}
  8376. bool TrackerBase::TrackerHasName::operator ()( ITrackerPtr const& tracker ) const {
  8377. return
  8378. tracker->nameAndLocation().location == m_nameAndLocation.location &&
  8379. tracker->nameAndLocation().name == m_nameAndLocation.name;
  8380. }
  8381. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8382. : m_nameAndLocation( nameAndLocation ),
  8383. m_ctx( ctx ),
  8384. m_parent( parent )
  8385. {}
  8386. NameAndLocation const& TrackerBase::nameAndLocation() const {
  8387. return m_nameAndLocation;
  8388. }
  8389. bool TrackerBase::isComplete() const {
  8390. return m_runState == CompletedSuccessfully || m_runState == Failed;
  8391. }
  8392. bool TrackerBase::isSuccessfullyCompleted() const {
  8393. return m_runState == CompletedSuccessfully;
  8394. }
  8395. bool TrackerBase::isOpen() const {
  8396. return m_runState != NotStarted && !isComplete();
  8397. }
  8398. bool TrackerBase::hasChildren() const {
  8399. return !m_children.empty();
  8400. }
  8401. void TrackerBase::addChild( ITrackerPtr const& child ) {
  8402. m_children.push_back( child );
  8403. }
  8404. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  8405. auto it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( nameAndLocation ) );
  8406. return( it != m_children.end() )
  8407. ? *it
  8408. : nullptr;
  8409. }
  8410. ITracker& TrackerBase::parent() {
  8411. assert( m_parent ); // Should always be non-null except for root
  8412. return *m_parent;
  8413. }
  8414. void TrackerBase::openChild() {
  8415. if( m_runState != ExecutingChildren ) {
  8416. m_runState = ExecutingChildren;
  8417. if( m_parent )
  8418. m_parent->openChild();
  8419. }
  8420. }
  8421. bool TrackerBase::isSectionTracker() const { return false; }
  8422. bool TrackerBase::isIndexTracker() const { return false; }
  8423. void TrackerBase::open() {
  8424. m_runState = Executing;
  8425. moveToThis();
  8426. if( m_parent )
  8427. m_parent->openChild();
  8428. }
  8429. void TrackerBase::close() {
  8430. // Close any still open children (e.g. generators)
  8431. while( &m_ctx.currentTracker() != this )
  8432. m_ctx.currentTracker().close();
  8433. switch( m_runState ) {
  8434. case NeedsAnotherRun:
  8435. break;
  8436. case Executing:
  8437. m_runState = CompletedSuccessfully;
  8438. break;
  8439. case ExecutingChildren:
  8440. if( m_children.empty() || m_children.back()->isComplete() )
  8441. m_runState = CompletedSuccessfully;
  8442. break;
  8443. case NotStarted:
  8444. case CompletedSuccessfully:
  8445. case Failed:
  8446. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  8447. default:
  8448. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  8449. }
  8450. moveToParent();
  8451. m_ctx.completeCycle();
  8452. }
  8453. void TrackerBase::fail() {
  8454. m_runState = Failed;
  8455. if( m_parent )
  8456. m_parent->markAsNeedingAnotherRun();
  8457. moveToParent();
  8458. m_ctx.completeCycle();
  8459. }
  8460. void TrackerBase::markAsNeedingAnotherRun() {
  8461. m_runState = NeedsAnotherRun;
  8462. }
  8463. void TrackerBase::moveToParent() {
  8464. assert( m_parent );
  8465. m_ctx.setCurrentTracker( m_parent );
  8466. }
  8467. void TrackerBase::moveToThis() {
  8468. m_ctx.setCurrentTracker( this );
  8469. }
  8470. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8471. : TrackerBase( nameAndLocation, ctx, parent )
  8472. {
  8473. if( parent ) {
  8474. while( !parent->isSectionTracker() )
  8475. parent = &parent->parent();
  8476. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  8477. addNextFilters( parentSection.m_filters );
  8478. }
  8479. }
  8480. bool SectionTracker::isSectionTracker() const { return true; }
  8481. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  8482. std::shared_ptr<SectionTracker> section;
  8483. ITracker& currentTracker = ctx.currentTracker();
  8484. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8485. assert( childTracker );
  8486. assert( childTracker->isSectionTracker() );
  8487. section = std::static_pointer_cast<SectionTracker>( childTracker );
  8488. }
  8489. else {
  8490. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  8491. currentTracker.addChild( section );
  8492. }
  8493. if( !ctx.completedCycle() )
  8494. section->tryOpen();
  8495. return *section;
  8496. }
  8497. void SectionTracker::tryOpen() {
  8498. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  8499. open();
  8500. }
  8501. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  8502. if( !filters.empty() ) {
  8503. m_filters.push_back(""); // Root - should never be consulted
  8504. m_filters.push_back(""); // Test Case - not a section filter
  8505. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  8506. }
  8507. }
  8508. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  8509. if( filters.size() > 1 )
  8510. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  8511. }
  8512. IndexTracker::IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size )
  8513. : TrackerBase( nameAndLocation, ctx, parent ),
  8514. m_size( size )
  8515. {}
  8516. bool IndexTracker::isIndexTracker() const { return true; }
  8517. IndexTracker& IndexTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) {
  8518. std::shared_ptr<IndexTracker> tracker;
  8519. ITracker& currentTracker = ctx.currentTracker();
  8520. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8521. assert( childTracker );
  8522. assert( childTracker->isIndexTracker() );
  8523. tracker = std::static_pointer_cast<IndexTracker>( childTracker );
  8524. }
  8525. else {
  8526. tracker = std::make_shared<IndexTracker>( nameAndLocation, ctx, &currentTracker, size );
  8527. currentTracker.addChild( tracker );
  8528. }
  8529. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  8530. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  8531. tracker->moveNext();
  8532. tracker->open();
  8533. }
  8534. return *tracker;
  8535. }
  8536. int IndexTracker::index() const { return m_index; }
  8537. void IndexTracker::moveNext() {
  8538. m_index++;
  8539. m_children.clear();
  8540. }
  8541. void IndexTracker::close() {
  8542. TrackerBase::close();
  8543. if( m_runState == CompletedSuccessfully && m_index < m_size-1 )
  8544. m_runState = Executing;
  8545. }
  8546. } // namespace TestCaseTracking
  8547. using TestCaseTracking::ITracker;
  8548. using TestCaseTracking::TrackerContext;
  8549. using TestCaseTracking::SectionTracker;
  8550. using TestCaseTracking::IndexTracker;
  8551. } // namespace Catch
  8552. #if defined(__clang__)
  8553. # pragma clang diagnostic pop
  8554. #endif
  8555. // end catch_test_case_tracker.cpp
  8556. // start catch_test_registry.cpp
  8557. namespace Catch {
  8558. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  8559. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  8560. }
  8561. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  8562. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  8563. try {
  8564. getMutableRegistryHub()
  8565. .registerTest(
  8566. makeTestCase(
  8567. invoker,
  8568. extractClassName( classOrMethod ),
  8569. nameAndTags,
  8570. lineInfo));
  8571. } catch (...) {
  8572. // Do not throw when constructing global objects, instead register the exception to be processed later
  8573. getMutableRegistryHub().registerStartupException();
  8574. }
  8575. }
  8576. AutoReg::~AutoReg() = default;
  8577. }
  8578. // end catch_test_registry.cpp
  8579. // start catch_test_spec.cpp
  8580. #include <algorithm>
  8581. #include <string>
  8582. #include <vector>
  8583. #include <memory>
  8584. namespace Catch {
  8585. TestSpec::Pattern::~Pattern() = default;
  8586. TestSpec::NamePattern::~NamePattern() = default;
  8587. TestSpec::TagPattern::~TagPattern() = default;
  8588. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  8589. TestSpec::NamePattern::NamePattern( std::string const& name )
  8590. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  8591. {}
  8592. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  8593. return m_wildcardPattern.matches( toLower( testCase.name ) );
  8594. }
  8595. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  8596. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  8597. return std::find(begin(testCase.lcaseTags),
  8598. end(testCase.lcaseTags),
  8599. m_tag) != end(testCase.lcaseTags);
  8600. }
  8601. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  8602. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  8603. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  8604. // All patterns in a filter must match for the filter to be a match
  8605. for( auto const& pattern : m_patterns ) {
  8606. if( !pattern->matches( testCase ) )
  8607. return false;
  8608. }
  8609. return true;
  8610. }
  8611. bool TestSpec::hasFilters() const {
  8612. return !m_filters.empty();
  8613. }
  8614. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  8615. // A TestSpec matches if any filter matches
  8616. for( auto const& filter : m_filters )
  8617. if( filter.matches( testCase ) )
  8618. return true;
  8619. return false;
  8620. }
  8621. }
  8622. // end catch_test_spec.cpp
  8623. // start catch_test_spec_parser.cpp
  8624. namespace Catch {
  8625. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  8626. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  8627. m_mode = None;
  8628. m_exclusion = false;
  8629. m_start = std::string::npos;
  8630. m_arg = m_tagAliases->expandAliases( arg );
  8631. m_escapeChars.clear();
  8632. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  8633. visitChar( m_arg[m_pos] );
  8634. if( m_mode == Name )
  8635. addPattern<TestSpec::NamePattern>();
  8636. return *this;
  8637. }
  8638. TestSpec TestSpecParser::testSpec() {
  8639. addFilter();
  8640. return m_testSpec;
  8641. }
  8642. void TestSpecParser::visitChar( char c ) {
  8643. if( m_mode == None ) {
  8644. switch( c ) {
  8645. case ' ': return;
  8646. case '~': m_exclusion = true; return;
  8647. case '[': return startNewMode( Tag, ++m_pos );
  8648. case '"': return startNewMode( QuotedName, ++m_pos );
  8649. case '\\': return escape();
  8650. default: startNewMode( Name, m_pos ); break;
  8651. }
  8652. }
  8653. if( m_mode == Name ) {
  8654. if( c == ',' ) {
  8655. addPattern<TestSpec::NamePattern>();
  8656. addFilter();
  8657. }
  8658. else if( c == '[' ) {
  8659. if( subString() == "exclude:" )
  8660. m_exclusion = true;
  8661. else
  8662. addPattern<TestSpec::NamePattern>();
  8663. startNewMode( Tag, ++m_pos );
  8664. }
  8665. else if( c == '\\' )
  8666. escape();
  8667. }
  8668. else if( m_mode == EscapedName )
  8669. m_mode = Name;
  8670. else if( m_mode == QuotedName && c == '"' )
  8671. addPattern<TestSpec::NamePattern>();
  8672. else if( m_mode == Tag && c == ']' )
  8673. addPattern<TestSpec::TagPattern>();
  8674. }
  8675. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  8676. m_mode = mode;
  8677. m_start = start;
  8678. }
  8679. void TestSpecParser::escape() {
  8680. if( m_mode == None )
  8681. m_start = m_pos;
  8682. m_mode = EscapedName;
  8683. m_escapeChars.push_back( m_pos );
  8684. }
  8685. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  8686. void TestSpecParser::addFilter() {
  8687. if( !m_currentFilter.m_patterns.empty() ) {
  8688. m_testSpec.m_filters.push_back( m_currentFilter );
  8689. m_currentFilter = TestSpec::Filter();
  8690. }
  8691. }
  8692. TestSpec parseTestSpec( std::string const& arg ) {
  8693. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  8694. }
  8695. } // namespace Catch
  8696. // end catch_test_spec_parser.cpp
  8697. // start catch_timer.cpp
  8698. #include <chrono>
  8699. static const uint64_t nanosecondsInSecond = 1000000000;
  8700. namespace Catch {
  8701. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  8702. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  8703. }
  8704. namespace {
  8705. auto estimateClockResolution() -> uint64_t {
  8706. uint64_t sum = 0;
  8707. static const uint64_t iterations = 1000000;
  8708. auto startTime = getCurrentNanosecondsSinceEpoch();
  8709. for( std::size_t i = 0; i < iterations; ++i ) {
  8710. uint64_t ticks;
  8711. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  8712. do {
  8713. ticks = getCurrentNanosecondsSinceEpoch();
  8714. } while( ticks == baseTicks );
  8715. auto delta = ticks - baseTicks;
  8716. sum += delta;
  8717. // If we have been calibrating for over 3 seconds -- the clock
  8718. // is terrible and we should move on.
  8719. // TBD: How to signal that the measured resolution is probably wrong?
  8720. if (ticks > startTime + 3 * nanosecondsInSecond) {
  8721. return sum / i;
  8722. }
  8723. }
  8724. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  8725. // - and potentially do more iterations if there's a high variance.
  8726. return sum/iterations;
  8727. }
  8728. }
  8729. auto getEstimatedClockResolution() -> uint64_t {
  8730. static auto s_resolution = estimateClockResolution();
  8731. return s_resolution;
  8732. }
  8733. void Timer::start() {
  8734. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  8735. }
  8736. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  8737. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  8738. }
  8739. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  8740. return getElapsedNanoseconds()/1000;
  8741. }
  8742. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  8743. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  8744. }
  8745. auto Timer::getElapsedSeconds() const -> double {
  8746. return getElapsedMicroseconds()/1000000.0;
  8747. }
  8748. } // namespace Catch
  8749. // end catch_timer.cpp
  8750. // start catch_tostring.cpp
  8751. #if defined(__clang__)
  8752. # pragma clang diagnostic push
  8753. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8754. # pragma clang diagnostic ignored "-Wglobal-constructors"
  8755. #endif
  8756. // Enable specific decls locally
  8757. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  8758. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  8759. #endif
  8760. #include <cmath>
  8761. #include <iomanip>
  8762. namespace Catch {
  8763. namespace Detail {
  8764. const std::string unprintableString = "{?}";
  8765. namespace {
  8766. const int hexThreshold = 255;
  8767. struct Endianness {
  8768. enum Arch { Big, Little };
  8769. static Arch which() {
  8770. union _{
  8771. int asInt;
  8772. char asChar[sizeof (int)];
  8773. } u;
  8774. u.asInt = 1;
  8775. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  8776. }
  8777. };
  8778. }
  8779. std::string rawMemoryToString( const void *object, std::size_t size ) {
  8780. // Reverse order for little endian architectures
  8781. int i = 0, end = static_cast<int>( size ), inc = 1;
  8782. if( Endianness::which() == Endianness::Little ) {
  8783. i = end-1;
  8784. end = inc = -1;
  8785. }
  8786. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  8787. ReusableStringStream rss;
  8788. rss << "0x" << std::setfill('0') << std::hex;
  8789. for( ; i != end; i += inc )
  8790. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  8791. return rss.str();
  8792. }
  8793. }
  8794. template<typename T>
  8795. std::string fpToString( T value, int precision ) {
  8796. if (std::isnan(value)) {
  8797. return "nan";
  8798. }
  8799. ReusableStringStream rss;
  8800. rss << std::setprecision( precision )
  8801. << std::fixed
  8802. << value;
  8803. std::string d = rss.str();
  8804. std::size_t i = d.find_last_not_of( '0' );
  8805. if( i != std::string::npos && i != d.size()-1 ) {
  8806. if( d[i] == '.' )
  8807. i++;
  8808. d = d.substr( 0, i+1 );
  8809. }
  8810. return d;
  8811. }
  8812. //// ======================================================= ////
  8813. //
  8814. // Out-of-line defs for full specialization of StringMaker
  8815. //
  8816. //// ======================================================= ////
  8817. std::string StringMaker<std::string>::convert(const std::string& str) {
  8818. if (!getCurrentContext().getConfig()->showInvisibles()) {
  8819. return '"' + str + '"';
  8820. }
  8821. std::string s("\"");
  8822. for (char c : str) {
  8823. switch (c) {
  8824. case '\n':
  8825. s.append("\\n");
  8826. break;
  8827. case '\t':
  8828. s.append("\\t");
  8829. break;
  8830. default:
  8831. s.push_back(c);
  8832. break;
  8833. }
  8834. }
  8835. s.append("\"");
  8836. return s;
  8837. }
  8838. #ifdef CATCH_CONFIG_WCHAR
  8839. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  8840. std::string s;
  8841. s.reserve(wstr.size());
  8842. for (auto c : wstr) {
  8843. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  8844. }
  8845. return ::Catch::Detail::stringify(s);
  8846. }
  8847. #endif
  8848. std::string StringMaker<char const*>::convert(char const* str) {
  8849. if (str) {
  8850. return ::Catch::Detail::stringify(std::string{ str });
  8851. } else {
  8852. return{ "{null string}" };
  8853. }
  8854. }
  8855. std::string StringMaker<char*>::convert(char* str) {
  8856. if (str) {
  8857. return ::Catch::Detail::stringify(std::string{ str });
  8858. } else {
  8859. return{ "{null string}" };
  8860. }
  8861. }
  8862. #ifdef CATCH_CONFIG_WCHAR
  8863. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  8864. if (str) {
  8865. return ::Catch::Detail::stringify(std::wstring{ str });
  8866. } else {
  8867. return{ "{null string}" };
  8868. }
  8869. }
  8870. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  8871. if (str) {
  8872. return ::Catch::Detail::stringify(std::wstring{ str });
  8873. } else {
  8874. return{ "{null string}" };
  8875. }
  8876. }
  8877. #endif
  8878. std::string StringMaker<int>::convert(int value) {
  8879. return ::Catch::Detail::stringify(static_cast<long long>(value));
  8880. }
  8881. std::string StringMaker<long>::convert(long value) {
  8882. return ::Catch::Detail::stringify(static_cast<long long>(value));
  8883. }
  8884. std::string StringMaker<long long>::convert(long long value) {
  8885. ReusableStringStream rss;
  8886. rss << value;
  8887. if (value > Detail::hexThreshold) {
  8888. rss << " (0x" << std::hex << value << ')';
  8889. }
  8890. return rss.str();
  8891. }
  8892. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  8893. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  8894. }
  8895. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  8896. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  8897. }
  8898. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  8899. ReusableStringStream rss;
  8900. rss << value;
  8901. if (value > Detail::hexThreshold) {
  8902. rss << " (0x" << std::hex << value << ')';
  8903. }
  8904. return rss.str();
  8905. }
  8906. std::string StringMaker<bool>::convert(bool b) {
  8907. return b ? "true" : "false";
  8908. }
  8909. std::string StringMaker<char>::convert(char value) {
  8910. if (value == '\r') {
  8911. return "'\\r'";
  8912. } else if (value == '\f') {
  8913. return "'\\f'";
  8914. } else if (value == '\n') {
  8915. return "'\\n'";
  8916. } else if (value == '\t') {
  8917. return "'\\t'";
  8918. } else if ('\0' <= value && value < ' ') {
  8919. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  8920. } else {
  8921. char chstr[] = "' '";
  8922. chstr[1] = value;
  8923. return chstr;
  8924. }
  8925. }
  8926. std::string StringMaker<signed char>::convert(signed char c) {
  8927. return ::Catch::Detail::stringify(static_cast<char>(c));
  8928. }
  8929. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  8930. return ::Catch::Detail::stringify(static_cast<char>(c));
  8931. }
  8932. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  8933. return "nullptr";
  8934. }
  8935. std::string StringMaker<float>::convert(float value) {
  8936. return fpToString(value, 5) + 'f';
  8937. }
  8938. std::string StringMaker<double>::convert(double value) {
  8939. return fpToString(value, 10);
  8940. }
  8941. std::string ratio_string<std::atto>::symbol() { return "a"; }
  8942. std::string ratio_string<std::femto>::symbol() { return "f"; }
  8943. std::string ratio_string<std::pico>::symbol() { return "p"; }
  8944. std::string ratio_string<std::nano>::symbol() { return "n"; }
  8945. std::string ratio_string<std::micro>::symbol() { return "u"; }
  8946. std::string ratio_string<std::milli>::symbol() { return "m"; }
  8947. } // end namespace Catch
  8948. #if defined(__clang__)
  8949. # pragma clang diagnostic pop
  8950. #endif
  8951. // end catch_tostring.cpp
  8952. // start catch_totals.cpp
  8953. namespace Catch {
  8954. Counts Counts::operator - ( Counts const& other ) const {
  8955. Counts diff;
  8956. diff.passed = passed - other.passed;
  8957. diff.failed = failed - other.failed;
  8958. diff.failedButOk = failedButOk - other.failedButOk;
  8959. return diff;
  8960. }
  8961. Counts& Counts::operator += ( Counts const& other ) {
  8962. passed += other.passed;
  8963. failed += other.failed;
  8964. failedButOk += other.failedButOk;
  8965. return *this;
  8966. }
  8967. std::size_t Counts::total() const {
  8968. return passed + failed + failedButOk;
  8969. }
  8970. bool Counts::allPassed() const {
  8971. return failed == 0 && failedButOk == 0;
  8972. }
  8973. bool Counts::allOk() const {
  8974. return failed == 0;
  8975. }
  8976. Totals Totals::operator - ( Totals const& other ) const {
  8977. Totals diff;
  8978. diff.assertions = assertions - other.assertions;
  8979. diff.testCases = testCases - other.testCases;
  8980. return diff;
  8981. }
  8982. Totals& Totals::operator += ( Totals const& other ) {
  8983. assertions += other.assertions;
  8984. testCases += other.testCases;
  8985. return *this;
  8986. }
  8987. Totals Totals::delta( Totals const& prevTotals ) const {
  8988. Totals diff = *this - prevTotals;
  8989. if( diff.assertions.failed > 0 )
  8990. ++diff.testCases.failed;
  8991. else if( diff.assertions.failedButOk > 0 )
  8992. ++diff.testCases.failedButOk;
  8993. else
  8994. ++diff.testCases.passed;
  8995. return diff;
  8996. }
  8997. }
  8998. // end catch_totals.cpp
  8999. // start catch_uncaught_exceptions.cpp
  9000. #include <exception>
  9001. namespace Catch {
  9002. bool uncaught_exceptions() {
  9003. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  9004. return std::uncaught_exceptions() > 0;
  9005. #else
  9006. return std::uncaught_exception();
  9007. #endif
  9008. }
  9009. } // end namespace Catch
  9010. // end catch_uncaught_exceptions.cpp
  9011. // start catch_version.cpp
  9012. #include <ostream>
  9013. namespace Catch {
  9014. Version::Version
  9015. ( unsigned int _majorVersion,
  9016. unsigned int _minorVersion,
  9017. unsigned int _patchNumber,
  9018. char const * const _branchName,
  9019. unsigned int _buildNumber )
  9020. : majorVersion( _majorVersion ),
  9021. minorVersion( _minorVersion ),
  9022. patchNumber( _patchNumber ),
  9023. branchName( _branchName ),
  9024. buildNumber( _buildNumber )
  9025. {}
  9026. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  9027. os << version.majorVersion << '.'
  9028. << version.minorVersion << '.'
  9029. << version.patchNumber;
  9030. // branchName is never null -> 0th char is \0 if it is empty
  9031. if (version.branchName[0]) {
  9032. os << '-' << version.branchName
  9033. << '.' << version.buildNumber;
  9034. }
  9035. return os;
  9036. }
  9037. Version const& libraryVersion() {
  9038. static Version version( 2, 3, 0, "", 0 );
  9039. return version;
  9040. }
  9041. }
  9042. // end catch_version.cpp
  9043. // start catch_wildcard_pattern.cpp
  9044. #include <sstream>
  9045. namespace Catch {
  9046. WildcardPattern::WildcardPattern( std::string const& pattern,
  9047. CaseSensitive::Choice caseSensitivity )
  9048. : m_caseSensitivity( caseSensitivity ),
  9049. m_pattern( adjustCase( pattern ) )
  9050. {
  9051. if( startsWith( m_pattern, '*' ) ) {
  9052. m_pattern = m_pattern.substr( 1 );
  9053. m_wildcard = WildcardAtStart;
  9054. }
  9055. if( endsWith( m_pattern, '*' ) ) {
  9056. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  9057. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  9058. }
  9059. }
  9060. bool WildcardPattern::matches( std::string const& str ) const {
  9061. switch( m_wildcard ) {
  9062. case NoWildcard:
  9063. return m_pattern == adjustCase( str );
  9064. case WildcardAtStart:
  9065. return endsWith( adjustCase( str ), m_pattern );
  9066. case WildcardAtEnd:
  9067. return startsWith( adjustCase( str ), m_pattern );
  9068. case WildcardAtBothEnds:
  9069. return contains( adjustCase( str ), m_pattern );
  9070. default:
  9071. CATCH_INTERNAL_ERROR( "Unknown enum" );
  9072. }
  9073. }
  9074. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  9075. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  9076. }
  9077. }
  9078. // end catch_wildcard_pattern.cpp
  9079. // start catch_xmlwriter.cpp
  9080. #include <iomanip>
  9081. using uchar = unsigned char;
  9082. namespace Catch {
  9083. namespace {
  9084. size_t trailingBytes(unsigned char c) {
  9085. if ((c & 0xE0) == 0xC0) {
  9086. return 2;
  9087. }
  9088. if ((c & 0xF0) == 0xE0) {
  9089. return 3;
  9090. }
  9091. if ((c & 0xF8) == 0xF0) {
  9092. return 4;
  9093. }
  9094. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  9095. }
  9096. uint32_t headerValue(unsigned char c) {
  9097. if ((c & 0xE0) == 0xC0) {
  9098. return c & 0x1F;
  9099. }
  9100. if ((c & 0xF0) == 0xE0) {
  9101. return c & 0x0F;
  9102. }
  9103. if ((c & 0xF8) == 0xF0) {
  9104. return c & 0x07;
  9105. }
  9106. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  9107. }
  9108. void hexEscapeChar(std::ostream& os, unsigned char c) {
  9109. os << "\\x"
  9110. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  9111. << static_cast<int>(c);
  9112. }
  9113. } // anonymous namespace
  9114. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  9115. : m_str( str ),
  9116. m_forWhat( forWhat )
  9117. {}
  9118. void XmlEncode::encodeTo( std::ostream& os ) const {
  9119. // Apostrophe escaping not necessary if we always use " to write attributes
  9120. // (see: http://www.w3.org/TR/xml/#syntax)
  9121. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  9122. uchar c = m_str[idx];
  9123. switch (c) {
  9124. case '<': os << "&lt;"; break;
  9125. case '&': os << "&amp;"; break;
  9126. case '>':
  9127. // See: http://www.w3.org/TR/xml/#syntax
  9128. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  9129. os << "&gt;";
  9130. else
  9131. os << c;
  9132. break;
  9133. case '\"':
  9134. if (m_forWhat == ForAttributes)
  9135. os << "&quot;";
  9136. else
  9137. os << c;
  9138. break;
  9139. default:
  9140. // Check for control characters and invalid utf-8
  9141. // Escape control characters in standard ascii
  9142. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  9143. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  9144. hexEscapeChar(os, c);
  9145. break;
  9146. }
  9147. // Plain ASCII: Write it to stream
  9148. if (c < 0x7F) {
  9149. os << c;
  9150. break;
  9151. }
  9152. // UTF-8 territory
  9153. // Check if the encoding is valid and if it is not, hex escape bytes.
  9154. // Important: We do not check the exact decoded values for validity, only the encoding format
  9155. // First check that this bytes is a valid lead byte:
  9156. // This means that it is not encoded as 1111 1XXX
  9157. // Or as 10XX XXXX
  9158. if (c < 0xC0 ||
  9159. c >= 0xF8) {
  9160. hexEscapeChar(os, c);
  9161. break;
  9162. }
  9163. auto encBytes = trailingBytes(c);
  9164. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  9165. if (idx + encBytes - 1 >= m_str.size()) {
  9166. hexEscapeChar(os, c);
  9167. break;
  9168. }
  9169. // The header is valid, check data
  9170. // The next encBytes bytes must together be a valid utf-8
  9171. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  9172. bool valid = true;
  9173. uint32_t value = headerValue(c);
  9174. for (std::size_t n = 1; n < encBytes; ++n) {
  9175. uchar nc = m_str[idx + n];
  9176. valid &= ((nc & 0xC0) == 0x80);
  9177. value = (value << 6) | (nc & 0x3F);
  9178. }
  9179. if (
  9180. // Wrong bit pattern of following bytes
  9181. (!valid) ||
  9182. // Overlong encodings
  9183. (value < 0x80) ||
  9184. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  9185. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  9186. // Encoded value out of range
  9187. (value >= 0x110000)
  9188. ) {
  9189. hexEscapeChar(os, c);
  9190. break;
  9191. }
  9192. // If we got here, this is in fact a valid(ish) utf-8 sequence
  9193. for (std::size_t n = 0; n < encBytes; ++n) {
  9194. os << m_str[idx + n];
  9195. }
  9196. idx += encBytes - 1;
  9197. break;
  9198. }
  9199. }
  9200. }
  9201. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  9202. xmlEncode.encodeTo( os );
  9203. return os;
  9204. }
  9205. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  9206. : m_writer( writer )
  9207. {}
  9208. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  9209. : m_writer( other.m_writer ){
  9210. other.m_writer = nullptr;
  9211. }
  9212. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  9213. if ( m_writer ) {
  9214. m_writer->endElement();
  9215. }
  9216. m_writer = other.m_writer;
  9217. other.m_writer = nullptr;
  9218. return *this;
  9219. }
  9220. XmlWriter::ScopedElement::~ScopedElement() {
  9221. if( m_writer )
  9222. m_writer->endElement();
  9223. }
  9224. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  9225. m_writer->writeText( text, indent );
  9226. return *this;
  9227. }
  9228. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  9229. {
  9230. writeDeclaration();
  9231. }
  9232. XmlWriter::~XmlWriter() {
  9233. while( !m_tags.empty() )
  9234. endElement();
  9235. }
  9236. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  9237. ensureTagClosed();
  9238. newlineIfNecessary();
  9239. m_os << m_indent << '<' << name;
  9240. m_tags.push_back( name );
  9241. m_indent += " ";
  9242. m_tagIsOpen = true;
  9243. return *this;
  9244. }
  9245. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  9246. ScopedElement scoped( this );
  9247. startElement( name );
  9248. return scoped;
  9249. }
  9250. XmlWriter& XmlWriter::endElement() {
  9251. newlineIfNecessary();
  9252. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  9253. if( m_tagIsOpen ) {
  9254. m_os << "/>";
  9255. m_tagIsOpen = false;
  9256. }
  9257. else {
  9258. m_os << m_indent << "</" << m_tags.back() << ">";
  9259. }
  9260. m_os << std::endl;
  9261. m_tags.pop_back();
  9262. return *this;
  9263. }
  9264. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  9265. if( !name.empty() && !attribute.empty() )
  9266. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  9267. return *this;
  9268. }
  9269. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  9270. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  9271. return *this;
  9272. }
  9273. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  9274. if( !text.empty() ){
  9275. bool tagWasOpen = m_tagIsOpen;
  9276. ensureTagClosed();
  9277. if( tagWasOpen && indent )
  9278. m_os << m_indent;
  9279. m_os << XmlEncode( text );
  9280. m_needsNewline = true;
  9281. }
  9282. return *this;
  9283. }
  9284. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  9285. ensureTagClosed();
  9286. m_os << m_indent << "<!--" << text << "-->";
  9287. m_needsNewline = true;
  9288. return *this;
  9289. }
  9290. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  9291. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  9292. }
  9293. XmlWriter& XmlWriter::writeBlankLine() {
  9294. ensureTagClosed();
  9295. m_os << '\n';
  9296. return *this;
  9297. }
  9298. void XmlWriter::ensureTagClosed() {
  9299. if( m_tagIsOpen ) {
  9300. m_os << ">" << std::endl;
  9301. m_tagIsOpen = false;
  9302. }
  9303. }
  9304. void XmlWriter::writeDeclaration() {
  9305. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  9306. }
  9307. void XmlWriter::newlineIfNecessary() {
  9308. if( m_needsNewline ) {
  9309. m_os << std::endl;
  9310. m_needsNewline = false;
  9311. }
  9312. }
  9313. }
  9314. // end catch_xmlwriter.cpp
  9315. // start catch_reporter_bases.cpp
  9316. #include <cstring>
  9317. #include <cfloat>
  9318. #include <cstdio>
  9319. #include <cassert>
  9320. #include <memory>
  9321. namespace Catch {
  9322. void prepareExpandedExpression(AssertionResult& result) {
  9323. result.getExpandedExpression();
  9324. }
  9325. // Because formatting using c++ streams is stateful, drop down to C is required
  9326. // Alternatively we could use stringstream, but its performance is... not good.
  9327. std::string getFormattedDuration( double duration ) {
  9328. // Max exponent + 1 is required to represent the whole part
  9329. // + 1 for decimal point
  9330. // + 3 for the 3 decimal places
  9331. // + 1 for null terminator
  9332. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  9333. char buffer[maxDoubleSize];
  9334. // Save previous errno, to prevent sprintf from overwriting it
  9335. ErrnoGuard guard;
  9336. #ifdef _MSC_VER
  9337. sprintf_s(buffer, "%.3f", duration);
  9338. #else
  9339. sprintf(buffer, "%.3f", duration);
  9340. #endif
  9341. return std::string(buffer);
  9342. }
  9343. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  9344. :StreamingReporterBase(_config) {}
  9345. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  9346. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  9347. return false;
  9348. }
  9349. } // end namespace Catch
  9350. // end catch_reporter_bases.cpp
  9351. // start catch_reporter_compact.cpp
  9352. namespace {
  9353. #ifdef CATCH_PLATFORM_MAC
  9354. const char* failedString() { return "FAILED"; }
  9355. const char* passedString() { return "PASSED"; }
  9356. #else
  9357. const char* failedString() { return "failed"; }
  9358. const char* passedString() { return "passed"; }
  9359. #endif
  9360. // Colour::LightGrey
  9361. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  9362. std::string bothOrAll( std::size_t count ) {
  9363. return count == 1 ? std::string() :
  9364. count == 2 ? "both " : "all " ;
  9365. }
  9366. } // anon namespace
  9367. namespace Catch {
  9368. namespace {
  9369. // Colour, message variants:
  9370. // - white: No tests ran.
  9371. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  9372. // - white: Passed [both/all] N test cases (no assertions).
  9373. // - red: Failed N tests cases, failed M assertions.
  9374. // - green: Passed [both/all] N tests cases with M assertions.
  9375. void printTotals(std::ostream& out, const Totals& totals) {
  9376. if (totals.testCases.total() == 0) {
  9377. out << "No tests ran.";
  9378. } else if (totals.testCases.failed == totals.testCases.total()) {
  9379. Colour colour(Colour::ResultError);
  9380. const std::string qualify_assertions_failed =
  9381. totals.assertions.failed == totals.assertions.total() ?
  9382. bothOrAll(totals.assertions.failed) : std::string();
  9383. out <<
  9384. "Failed " << bothOrAll(totals.testCases.failed)
  9385. << pluralise(totals.testCases.failed, "test case") << ", "
  9386. "failed " << qualify_assertions_failed <<
  9387. pluralise(totals.assertions.failed, "assertion") << '.';
  9388. } else if (totals.assertions.total() == 0) {
  9389. out <<
  9390. "Passed " << bothOrAll(totals.testCases.total())
  9391. << pluralise(totals.testCases.total(), "test case")
  9392. << " (no assertions).";
  9393. } else if (totals.assertions.failed) {
  9394. Colour colour(Colour::ResultError);
  9395. out <<
  9396. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  9397. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  9398. } else {
  9399. Colour colour(Colour::ResultSuccess);
  9400. out <<
  9401. "Passed " << bothOrAll(totals.testCases.passed)
  9402. << pluralise(totals.testCases.passed, "test case") <<
  9403. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  9404. }
  9405. }
  9406. // Implementation of CompactReporter formatting
  9407. class AssertionPrinter {
  9408. public:
  9409. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  9410. AssertionPrinter(AssertionPrinter const&) = delete;
  9411. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  9412. : stream(_stream)
  9413. , result(_stats.assertionResult)
  9414. , messages(_stats.infoMessages)
  9415. , itMessage(_stats.infoMessages.begin())
  9416. , printInfoMessages(_printInfoMessages) {}
  9417. void print() {
  9418. printSourceInfo();
  9419. itMessage = messages.begin();
  9420. switch (result.getResultType()) {
  9421. case ResultWas::Ok:
  9422. printResultType(Colour::ResultSuccess, passedString());
  9423. printOriginalExpression();
  9424. printReconstructedExpression();
  9425. if (!result.hasExpression())
  9426. printRemainingMessages(Colour::None);
  9427. else
  9428. printRemainingMessages();
  9429. break;
  9430. case ResultWas::ExpressionFailed:
  9431. if (result.isOk())
  9432. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  9433. else
  9434. printResultType(Colour::Error, failedString());
  9435. printOriginalExpression();
  9436. printReconstructedExpression();
  9437. printRemainingMessages();
  9438. break;
  9439. case ResultWas::ThrewException:
  9440. printResultType(Colour::Error, failedString());
  9441. printIssue("unexpected exception with message:");
  9442. printMessage();
  9443. printExpressionWas();
  9444. printRemainingMessages();
  9445. break;
  9446. case ResultWas::FatalErrorCondition:
  9447. printResultType(Colour::Error, failedString());
  9448. printIssue("fatal error condition with message:");
  9449. printMessage();
  9450. printExpressionWas();
  9451. printRemainingMessages();
  9452. break;
  9453. case ResultWas::DidntThrowException:
  9454. printResultType(Colour::Error, failedString());
  9455. printIssue("expected exception, got none");
  9456. printExpressionWas();
  9457. printRemainingMessages();
  9458. break;
  9459. case ResultWas::Info:
  9460. printResultType(Colour::None, "info");
  9461. printMessage();
  9462. printRemainingMessages();
  9463. break;
  9464. case ResultWas::Warning:
  9465. printResultType(Colour::None, "warning");
  9466. printMessage();
  9467. printRemainingMessages();
  9468. break;
  9469. case ResultWas::ExplicitFailure:
  9470. printResultType(Colour::Error, failedString());
  9471. printIssue("explicitly");
  9472. printRemainingMessages(Colour::None);
  9473. break;
  9474. // These cases are here to prevent compiler warnings
  9475. case ResultWas::Unknown:
  9476. case ResultWas::FailureBit:
  9477. case ResultWas::Exception:
  9478. printResultType(Colour::Error, "** internal error **");
  9479. break;
  9480. }
  9481. }
  9482. private:
  9483. void printSourceInfo() const {
  9484. Colour colourGuard(Colour::FileName);
  9485. stream << result.getSourceInfo() << ':';
  9486. }
  9487. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  9488. if (!passOrFail.empty()) {
  9489. {
  9490. Colour colourGuard(colour);
  9491. stream << ' ' << passOrFail;
  9492. }
  9493. stream << ':';
  9494. }
  9495. }
  9496. void printIssue(std::string const& issue) const {
  9497. stream << ' ' << issue;
  9498. }
  9499. void printExpressionWas() {
  9500. if (result.hasExpression()) {
  9501. stream << ';';
  9502. {
  9503. Colour colour(dimColour());
  9504. stream << " expression was:";
  9505. }
  9506. printOriginalExpression();
  9507. }
  9508. }
  9509. void printOriginalExpression() const {
  9510. if (result.hasExpression()) {
  9511. stream << ' ' << result.getExpression();
  9512. }
  9513. }
  9514. void printReconstructedExpression() const {
  9515. if (result.hasExpandedExpression()) {
  9516. {
  9517. Colour colour(dimColour());
  9518. stream << " for: ";
  9519. }
  9520. stream << result.getExpandedExpression();
  9521. }
  9522. }
  9523. void printMessage() {
  9524. if (itMessage != messages.end()) {
  9525. stream << " '" << itMessage->message << '\'';
  9526. ++itMessage;
  9527. }
  9528. }
  9529. void printRemainingMessages(Colour::Code colour = dimColour()) {
  9530. if (itMessage == messages.end())
  9531. return;
  9532. // using messages.end() directly yields (or auto) compilation error:
  9533. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  9534. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  9535. {
  9536. Colour colourGuard(colour);
  9537. stream << " with " << pluralise(N, "message") << ':';
  9538. }
  9539. for (; itMessage != itEnd; ) {
  9540. // If this assertion is a warning ignore any INFO messages
  9541. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  9542. stream << " '" << itMessage->message << '\'';
  9543. if (++itMessage != itEnd) {
  9544. Colour colourGuard(dimColour());
  9545. stream << " and";
  9546. }
  9547. }
  9548. }
  9549. }
  9550. private:
  9551. std::ostream& stream;
  9552. AssertionResult const& result;
  9553. std::vector<MessageInfo> messages;
  9554. std::vector<MessageInfo>::const_iterator itMessage;
  9555. bool printInfoMessages;
  9556. };
  9557. } // anon namespace
  9558. std::string CompactReporter::getDescription() {
  9559. return "Reports test results on a single line, suitable for IDEs";
  9560. }
  9561. ReporterPreferences CompactReporter::getPreferences() const {
  9562. return m_reporterPrefs;
  9563. }
  9564. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  9565. stream << "No test cases matched '" << spec << '\'' << std::endl;
  9566. }
  9567. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  9568. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  9569. AssertionResult const& result = _assertionStats.assertionResult;
  9570. bool printInfoMessages = true;
  9571. // Drop out if result was successful and we're not printing those
  9572. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  9573. if( result.getResultType() != ResultWas::Warning )
  9574. return false;
  9575. printInfoMessages = false;
  9576. }
  9577. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  9578. printer.print();
  9579. stream << std::endl;
  9580. return true;
  9581. }
  9582. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  9583. if (m_config->showDurations() == ShowDurations::Always) {
  9584. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  9585. }
  9586. }
  9587. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  9588. printTotals( stream, _testRunStats.totals );
  9589. stream << '\n' << std::endl;
  9590. StreamingReporterBase::testRunEnded( _testRunStats );
  9591. }
  9592. CompactReporter::~CompactReporter() {}
  9593. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  9594. } // end namespace Catch
  9595. // end catch_reporter_compact.cpp
  9596. // start catch_reporter_console.cpp
  9597. #include <cfloat>
  9598. #include <cstdio>
  9599. #if defined(_MSC_VER)
  9600. #pragma warning(push)
  9601. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  9602. // Note that 4062 (not all labels are handled
  9603. // and default is missing) is enabled
  9604. #endif
  9605. namespace Catch {
  9606. namespace {
  9607. // Formatter impl for ConsoleReporter
  9608. class ConsoleAssertionPrinter {
  9609. public:
  9610. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  9611. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  9612. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  9613. : stream(_stream),
  9614. stats(_stats),
  9615. result(_stats.assertionResult),
  9616. colour(Colour::None),
  9617. message(result.getMessage()),
  9618. messages(_stats.infoMessages),
  9619. printInfoMessages(_printInfoMessages) {
  9620. switch (result.getResultType()) {
  9621. case ResultWas::Ok:
  9622. colour = Colour::Success;
  9623. passOrFail = "PASSED";
  9624. //if( result.hasMessage() )
  9625. if (_stats.infoMessages.size() == 1)
  9626. messageLabel = "with message";
  9627. if (_stats.infoMessages.size() > 1)
  9628. messageLabel = "with messages";
  9629. break;
  9630. case ResultWas::ExpressionFailed:
  9631. if (result.isOk()) {
  9632. colour = Colour::Success;
  9633. passOrFail = "FAILED - but was ok";
  9634. } else {
  9635. colour = Colour::Error;
  9636. passOrFail = "FAILED";
  9637. }
  9638. if (_stats.infoMessages.size() == 1)
  9639. messageLabel = "with message";
  9640. if (_stats.infoMessages.size() > 1)
  9641. messageLabel = "with messages";
  9642. break;
  9643. case ResultWas::ThrewException:
  9644. colour = Colour::Error;
  9645. passOrFail = "FAILED";
  9646. messageLabel = "due to unexpected exception with ";
  9647. if (_stats.infoMessages.size() == 1)
  9648. messageLabel += "message";
  9649. if (_stats.infoMessages.size() > 1)
  9650. messageLabel += "messages";
  9651. break;
  9652. case ResultWas::FatalErrorCondition:
  9653. colour = Colour::Error;
  9654. passOrFail = "FAILED";
  9655. messageLabel = "due to a fatal error condition";
  9656. break;
  9657. case ResultWas::DidntThrowException:
  9658. colour = Colour::Error;
  9659. passOrFail = "FAILED";
  9660. messageLabel = "because no exception was thrown where one was expected";
  9661. break;
  9662. case ResultWas::Info:
  9663. messageLabel = "info";
  9664. break;
  9665. case ResultWas::Warning:
  9666. messageLabel = "warning";
  9667. break;
  9668. case ResultWas::ExplicitFailure:
  9669. passOrFail = "FAILED";
  9670. colour = Colour::Error;
  9671. if (_stats.infoMessages.size() == 1)
  9672. messageLabel = "explicitly with message";
  9673. if (_stats.infoMessages.size() > 1)
  9674. messageLabel = "explicitly with messages";
  9675. break;
  9676. // These cases are here to prevent compiler warnings
  9677. case ResultWas::Unknown:
  9678. case ResultWas::FailureBit:
  9679. case ResultWas::Exception:
  9680. passOrFail = "** internal error **";
  9681. colour = Colour::Error;
  9682. break;
  9683. }
  9684. }
  9685. void print() const {
  9686. printSourceInfo();
  9687. if (stats.totals.assertions.total() > 0) {
  9688. if (result.isOk())
  9689. stream << '\n';
  9690. printResultType();
  9691. printOriginalExpression();
  9692. printReconstructedExpression();
  9693. } else {
  9694. stream << '\n';
  9695. }
  9696. printMessage();
  9697. }
  9698. private:
  9699. void printResultType() const {
  9700. if (!passOrFail.empty()) {
  9701. Colour colourGuard(colour);
  9702. stream << passOrFail << ":\n";
  9703. }
  9704. }
  9705. void printOriginalExpression() const {
  9706. if (result.hasExpression()) {
  9707. Colour colourGuard(Colour::OriginalExpression);
  9708. stream << " ";
  9709. stream << result.getExpressionInMacro();
  9710. stream << '\n';
  9711. }
  9712. }
  9713. void printReconstructedExpression() const {
  9714. if (result.hasExpandedExpression()) {
  9715. stream << "with expansion:\n";
  9716. Colour colourGuard(Colour::ReconstructedExpression);
  9717. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  9718. }
  9719. }
  9720. void printMessage() const {
  9721. if (!messageLabel.empty())
  9722. stream << messageLabel << ':' << '\n';
  9723. for (auto const& msg : messages) {
  9724. // If this assertion is a warning ignore any INFO messages
  9725. if (printInfoMessages || msg.type != ResultWas::Info)
  9726. stream << Column(msg.message).indent(2) << '\n';
  9727. }
  9728. }
  9729. void printSourceInfo() const {
  9730. Colour colourGuard(Colour::FileName);
  9731. stream << result.getSourceInfo() << ": ";
  9732. }
  9733. std::ostream& stream;
  9734. AssertionStats const& stats;
  9735. AssertionResult const& result;
  9736. Colour::Code colour;
  9737. std::string passOrFail;
  9738. std::string messageLabel;
  9739. std::string message;
  9740. std::vector<MessageInfo> messages;
  9741. bool printInfoMessages;
  9742. };
  9743. std::size_t makeRatio(std::size_t number, std::size_t total) {
  9744. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  9745. return (ratio == 0 && number > 0) ? 1 : ratio;
  9746. }
  9747. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  9748. if (i > j && i > k)
  9749. return i;
  9750. else if (j > k)
  9751. return j;
  9752. else
  9753. return k;
  9754. }
  9755. struct ColumnInfo {
  9756. enum Justification { Left, Right };
  9757. std::string name;
  9758. int width;
  9759. Justification justification;
  9760. };
  9761. struct ColumnBreak {};
  9762. struct RowBreak {};
  9763. class Duration {
  9764. enum class Unit {
  9765. Auto,
  9766. Nanoseconds,
  9767. Microseconds,
  9768. Milliseconds,
  9769. Seconds,
  9770. Minutes
  9771. };
  9772. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  9773. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  9774. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  9775. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  9776. uint64_t m_inNanoseconds;
  9777. Unit m_units;
  9778. public:
  9779. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  9780. : m_inNanoseconds(inNanoseconds),
  9781. m_units(units) {
  9782. if (m_units == Unit::Auto) {
  9783. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  9784. m_units = Unit::Nanoseconds;
  9785. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  9786. m_units = Unit::Microseconds;
  9787. else if (m_inNanoseconds < s_nanosecondsInASecond)
  9788. m_units = Unit::Milliseconds;
  9789. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  9790. m_units = Unit::Seconds;
  9791. else
  9792. m_units = Unit::Minutes;
  9793. }
  9794. }
  9795. auto value() const -> double {
  9796. switch (m_units) {
  9797. case Unit::Microseconds:
  9798. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  9799. case Unit::Milliseconds:
  9800. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  9801. case Unit::Seconds:
  9802. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  9803. case Unit::Minutes:
  9804. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  9805. default:
  9806. return static_cast<double>(m_inNanoseconds);
  9807. }
  9808. }
  9809. auto unitsAsString() const -> std::string {
  9810. switch (m_units) {
  9811. case Unit::Nanoseconds:
  9812. return "ns";
  9813. case Unit::Microseconds:
  9814. return "µs";
  9815. case Unit::Milliseconds:
  9816. return "ms";
  9817. case Unit::Seconds:
  9818. return "s";
  9819. case Unit::Minutes:
  9820. return "m";
  9821. default:
  9822. return "** internal error **";
  9823. }
  9824. }
  9825. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  9826. return os << duration.value() << " " << duration.unitsAsString();
  9827. }
  9828. };
  9829. } // end anon namespace
  9830. class TablePrinter {
  9831. std::ostream& m_os;
  9832. std::vector<ColumnInfo> m_columnInfos;
  9833. std::ostringstream m_oss;
  9834. int m_currentColumn = -1;
  9835. bool m_isOpen = false;
  9836. public:
  9837. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  9838. : m_os( os ),
  9839. m_columnInfos( std::move( columnInfos ) ) {}
  9840. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  9841. return m_columnInfos;
  9842. }
  9843. void open() {
  9844. if (!m_isOpen) {
  9845. m_isOpen = true;
  9846. *this << RowBreak();
  9847. for (auto const& info : m_columnInfos)
  9848. *this << info.name << ColumnBreak();
  9849. *this << RowBreak();
  9850. m_os << Catch::getLineOfChars<'-'>() << "\n";
  9851. }
  9852. }
  9853. void close() {
  9854. if (m_isOpen) {
  9855. *this << RowBreak();
  9856. m_os << std::endl;
  9857. m_isOpen = false;
  9858. }
  9859. }
  9860. template<typename T>
  9861. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  9862. tp.m_oss << value;
  9863. return tp;
  9864. }
  9865. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  9866. auto colStr = tp.m_oss.str();
  9867. // This takes account of utf8 encodings
  9868. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  9869. tp.m_oss.str("");
  9870. tp.open();
  9871. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  9872. tp.m_currentColumn = -1;
  9873. tp.m_os << "\n";
  9874. }
  9875. tp.m_currentColumn++;
  9876. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  9877. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  9878. ? std::string(colInfo.width - (strSize + 2), ' ')
  9879. : std::string();
  9880. if (colInfo.justification == ColumnInfo::Left)
  9881. tp.m_os << colStr << padding << " ";
  9882. else
  9883. tp.m_os << padding << colStr << " ";
  9884. return tp;
  9885. }
  9886. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  9887. if (tp.m_currentColumn > 0) {
  9888. tp.m_os << "\n";
  9889. tp.m_currentColumn = -1;
  9890. }
  9891. return tp;
  9892. }
  9893. };
  9894. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  9895. : StreamingReporterBase(config),
  9896. m_tablePrinter(new TablePrinter(config.stream(),
  9897. {
  9898. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  9899. { "iters", 8, ColumnInfo::Right },
  9900. { "elapsed ns", 14, ColumnInfo::Right },
  9901. { "average", 14, ColumnInfo::Right }
  9902. })) {}
  9903. ConsoleReporter::~ConsoleReporter() = default;
  9904. std::string ConsoleReporter::getDescription() {
  9905. return "Reports test results as plain lines of text";
  9906. }
  9907. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  9908. stream << "No test cases matched '" << spec << '\'' << std::endl;
  9909. }
  9910. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  9911. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  9912. AssertionResult const& result = _assertionStats.assertionResult;
  9913. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  9914. // Drop out if result was successful but we're not printing them.
  9915. if (!includeResults && result.getResultType() != ResultWas::Warning)
  9916. return false;
  9917. lazyPrint();
  9918. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  9919. printer.print();
  9920. stream << std::endl;
  9921. return true;
  9922. }
  9923. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  9924. m_headerPrinted = false;
  9925. StreamingReporterBase::sectionStarting(_sectionInfo);
  9926. }
  9927. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  9928. m_tablePrinter->close();
  9929. if (_sectionStats.missingAssertions) {
  9930. lazyPrint();
  9931. Colour colour(Colour::ResultError);
  9932. if (m_sectionStack.size() > 1)
  9933. stream << "\nNo assertions in section";
  9934. else
  9935. stream << "\nNo assertions in test case";
  9936. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  9937. }
  9938. if (m_config->showDurations() == ShowDurations::Always) {
  9939. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  9940. }
  9941. if (m_headerPrinted) {
  9942. m_headerPrinted = false;
  9943. }
  9944. StreamingReporterBase::sectionEnded(_sectionStats);
  9945. }
  9946. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  9947. lazyPrintWithoutClosingBenchmarkTable();
  9948. auto nameCol = Column( info.name ).width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) );
  9949. bool firstLine = true;
  9950. for (auto line : nameCol) {
  9951. if (!firstLine)
  9952. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  9953. else
  9954. firstLine = false;
  9955. (*m_tablePrinter) << line << ColumnBreak();
  9956. }
  9957. }
  9958. void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) {
  9959. Duration average(stats.elapsedTimeInNanoseconds / stats.iterations);
  9960. (*m_tablePrinter)
  9961. << stats.iterations << ColumnBreak()
  9962. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  9963. << average << ColumnBreak();
  9964. }
  9965. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  9966. m_tablePrinter->close();
  9967. StreamingReporterBase::testCaseEnded(_testCaseStats);
  9968. m_headerPrinted = false;
  9969. }
  9970. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  9971. if (currentGroupInfo.used) {
  9972. printSummaryDivider();
  9973. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  9974. printTotals(_testGroupStats.totals);
  9975. stream << '\n' << std::endl;
  9976. }
  9977. StreamingReporterBase::testGroupEnded(_testGroupStats);
  9978. }
  9979. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  9980. printTotalsDivider(_testRunStats.totals);
  9981. printTotals(_testRunStats.totals);
  9982. stream << std::endl;
  9983. StreamingReporterBase::testRunEnded(_testRunStats);
  9984. }
  9985. void ConsoleReporter::lazyPrint() {
  9986. m_tablePrinter->close();
  9987. lazyPrintWithoutClosingBenchmarkTable();
  9988. }
  9989. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  9990. if (!currentTestRunInfo.used)
  9991. lazyPrintRunInfo();
  9992. if (!currentGroupInfo.used)
  9993. lazyPrintGroupInfo();
  9994. if (!m_headerPrinted) {
  9995. printTestCaseAndSectionHeader();
  9996. m_headerPrinted = true;
  9997. }
  9998. }
  9999. void ConsoleReporter::lazyPrintRunInfo() {
  10000. stream << '\n' << getLineOfChars<'~'>() << '\n';
  10001. Colour colour(Colour::SecondaryText);
  10002. stream << currentTestRunInfo->name
  10003. << " is a Catch v" << libraryVersion() << " host application.\n"
  10004. << "Run with -? for options\n\n";
  10005. if (m_config->rngSeed() != 0)
  10006. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  10007. currentTestRunInfo.used = true;
  10008. }
  10009. void ConsoleReporter::lazyPrintGroupInfo() {
  10010. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  10011. printClosedHeader("Group: " + currentGroupInfo->name);
  10012. currentGroupInfo.used = true;
  10013. }
  10014. }
  10015. void ConsoleReporter::printTestCaseAndSectionHeader() {
  10016. assert(!m_sectionStack.empty());
  10017. printOpenHeader(currentTestCaseInfo->name);
  10018. if (m_sectionStack.size() > 1) {
  10019. Colour colourGuard(Colour::Headers);
  10020. auto
  10021. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  10022. itEnd = m_sectionStack.end();
  10023. for (; it != itEnd; ++it)
  10024. printHeaderString(it->name, 2);
  10025. }
  10026. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  10027. if (!lineInfo.empty()) {
  10028. stream << getLineOfChars<'-'>() << '\n';
  10029. Colour colourGuard(Colour::FileName);
  10030. stream << lineInfo << '\n';
  10031. }
  10032. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  10033. }
  10034. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  10035. printOpenHeader(_name);
  10036. stream << getLineOfChars<'.'>() << '\n';
  10037. }
  10038. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  10039. stream << getLineOfChars<'-'>() << '\n';
  10040. {
  10041. Colour colourGuard(Colour::Headers);
  10042. printHeaderString(_name);
  10043. }
  10044. }
  10045. // if string has a : in first line will set indent to follow it on
  10046. // subsequent lines
  10047. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  10048. std::size_t i = _string.find(": ");
  10049. if (i != std::string::npos)
  10050. i += 2;
  10051. else
  10052. i = 0;
  10053. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  10054. }
  10055. struct SummaryColumn {
  10056. SummaryColumn( std::string _label, Colour::Code _colour )
  10057. : label( std::move( _label ) ),
  10058. colour( _colour ) {}
  10059. SummaryColumn addRow( std::size_t count ) {
  10060. ReusableStringStream rss;
  10061. rss << count;
  10062. std::string row = rss.str();
  10063. for (auto& oldRow : rows) {
  10064. while (oldRow.size() < row.size())
  10065. oldRow = ' ' + oldRow;
  10066. while (oldRow.size() > row.size())
  10067. row = ' ' + row;
  10068. }
  10069. rows.push_back(row);
  10070. return *this;
  10071. }
  10072. std::string label;
  10073. Colour::Code colour;
  10074. std::vector<std::string> rows;
  10075. };
  10076. void ConsoleReporter::printTotals( Totals const& totals ) {
  10077. if (totals.testCases.total() == 0) {
  10078. stream << Colour(Colour::Warning) << "No tests ran\n";
  10079. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  10080. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  10081. stream << " ("
  10082. << pluralise(totals.assertions.passed, "assertion") << " in "
  10083. << pluralise(totals.testCases.passed, "test case") << ')'
  10084. << '\n';
  10085. } else {
  10086. std::vector<SummaryColumn> columns;
  10087. columns.push_back(SummaryColumn("", Colour::None)
  10088. .addRow(totals.testCases.total())
  10089. .addRow(totals.assertions.total()));
  10090. columns.push_back(SummaryColumn("passed", Colour::Success)
  10091. .addRow(totals.testCases.passed)
  10092. .addRow(totals.assertions.passed));
  10093. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  10094. .addRow(totals.testCases.failed)
  10095. .addRow(totals.assertions.failed));
  10096. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  10097. .addRow(totals.testCases.failedButOk)
  10098. .addRow(totals.assertions.failedButOk));
  10099. printSummaryRow("test cases", columns, 0);
  10100. printSummaryRow("assertions", columns, 1);
  10101. }
  10102. }
  10103. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  10104. for (auto col : cols) {
  10105. std::string value = col.rows[row];
  10106. if (col.label.empty()) {
  10107. stream << label << ": ";
  10108. if (value != "0")
  10109. stream << value;
  10110. else
  10111. stream << Colour(Colour::Warning) << "- none -";
  10112. } else if (value != "0") {
  10113. stream << Colour(Colour::LightGrey) << " | ";
  10114. stream << Colour(col.colour)
  10115. << value << ' ' << col.label;
  10116. }
  10117. }
  10118. stream << '\n';
  10119. }
  10120. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  10121. if (totals.testCases.total() > 0) {
  10122. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  10123. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  10124. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  10125. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  10126. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  10127. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  10128. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  10129. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  10130. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  10131. if (totals.testCases.allPassed())
  10132. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  10133. else
  10134. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  10135. } else {
  10136. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  10137. }
  10138. stream << '\n';
  10139. }
  10140. void ConsoleReporter::printSummaryDivider() {
  10141. stream << getLineOfChars<'-'>() << '\n';
  10142. }
  10143. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  10144. } // end namespace Catch
  10145. #if defined(_MSC_VER)
  10146. #pragma warning(pop)
  10147. #endif
  10148. // end catch_reporter_console.cpp
  10149. // start catch_reporter_junit.cpp
  10150. #include <cassert>
  10151. #include <sstream>
  10152. #include <ctime>
  10153. #include <algorithm>
  10154. namespace Catch {
  10155. namespace {
  10156. std::string getCurrentTimestamp() {
  10157. // Beware, this is not reentrant because of backward compatibility issues
  10158. // Also, UTC only, again because of backward compatibility (%z is C++11)
  10159. time_t rawtime;
  10160. std::time(&rawtime);
  10161. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  10162. #ifdef _MSC_VER
  10163. std::tm timeInfo = {};
  10164. gmtime_s(&timeInfo, &rawtime);
  10165. #else
  10166. std::tm* timeInfo;
  10167. timeInfo = std::gmtime(&rawtime);
  10168. #endif
  10169. char timeStamp[timeStampSize];
  10170. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  10171. #ifdef _MSC_VER
  10172. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  10173. #else
  10174. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  10175. #endif
  10176. return std::string(timeStamp);
  10177. }
  10178. std::string fileNameTag(const std::vector<std::string> &tags) {
  10179. auto it = std::find_if(begin(tags),
  10180. end(tags),
  10181. [] (std::string const& tag) {return tag.front() == '#'; });
  10182. if (it != tags.end())
  10183. return it->substr(1);
  10184. return std::string();
  10185. }
  10186. } // anonymous namespace
  10187. JunitReporter::JunitReporter( ReporterConfig const& _config )
  10188. : CumulativeReporterBase( _config ),
  10189. xml( _config.stream() )
  10190. {
  10191. m_reporterPrefs.shouldRedirectStdOut = true;
  10192. m_reporterPrefs.shouldReportAllAssertions = true;
  10193. }
  10194. JunitReporter::~JunitReporter() {}
  10195. std::string JunitReporter::getDescription() {
  10196. return "Reports test results in an XML format that looks like Ant's junitreport target";
  10197. }
  10198. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  10199. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  10200. CumulativeReporterBase::testRunStarting( runInfo );
  10201. xml.startElement( "testsuites" );
  10202. }
  10203. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  10204. suiteTimer.start();
  10205. stdOutForSuite.clear();
  10206. stdErrForSuite.clear();
  10207. unexpectedExceptions = 0;
  10208. CumulativeReporterBase::testGroupStarting( groupInfo );
  10209. }
  10210. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  10211. m_okToFail = testCaseInfo.okToFail();
  10212. }
  10213. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10214. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  10215. unexpectedExceptions++;
  10216. return CumulativeReporterBase::assertionEnded( assertionStats );
  10217. }
  10218. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10219. stdOutForSuite += testCaseStats.stdOut;
  10220. stdErrForSuite += testCaseStats.stdErr;
  10221. CumulativeReporterBase::testCaseEnded( testCaseStats );
  10222. }
  10223. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10224. double suiteTime = suiteTimer.getElapsedSeconds();
  10225. CumulativeReporterBase::testGroupEnded( testGroupStats );
  10226. writeGroup( *m_testGroups.back(), suiteTime );
  10227. }
  10228. void JunitReporter::testRunEndedCumulative() {
  10229. xml.endElement();
  10230. }
  10231. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  10232. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  10233. TestGroupStats const& stats = groupNode.value;
  10234. xml.writeAttribute( "name", stats.groupInfo.name );
  10235. xml.writeAttribute( "errors", unexpectedExceptions );
  10236. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  10237. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  10238. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  10239. if( m_config->showDurations() == ShowDurations::Never )
  10240. xml.writeAttribute( "time", "" );
  10241. else
  10242. xml.writeAttribute( "time", suiteTime );
  10243. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  10244. // Write test cases
  10245. for( auto const& child : groupNode.children )
  10246. writeTestCase( *child );
  10247. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  10248. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  10249. }
  10250. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  10251. TestCaseStats const& stats = testCaseNode.value;
  10252. // All test cases have exactly one section - which represents the
  10253. // test case itself. That section may have 0-n nested sections
  10254. assert( testCaseNode.children.size() == 1 );
  10255. SectionNode const& rootSection = *testCaseNode.children.front();
  10256. std::string className = stats.testInfo.className;
  10257. if( className.empty() ) {
  10258. className = fileNameTag(stats.testInfo.tags);
  10259. if ( className.empty() )
  10260. className = "global";
  10261. }
  10262. if ( !m_config->name().empty() )
  10263. className = m_config->name() + "." + className;
  10264. writeSection( className, "", rootSection );
  10265. }
  10266. void JunitReporter::writeSection( std::string const& className,
  10267. std::string const& rootName,
  10268. SectionNode const& sectionNode ) {
  10269. std::string name = trim( sectionNode.stats.sectionInfo.name );
  10270. if( !rootName.empty() )
  10271. name = rootName + '/' + name;
  10272. if( !sectionNode.assertions.empty() ||
  10273. !sectionNode.stdOut.empty() ||
  10274. !sectionNode.stdErr.empty() ) {
  10275. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  10276. if( className.empty() ) {
  10277. xml.writeAttribute( "classname", name );
  10278. xml.writeAttribute( "name", "root" );
  10279. }
  10280. else {
  10281. xml.writeAttribute( "classname", className );
  10282. xml.writeAttribute( "name", name );
  10283. }
  10284. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  10285. writeAssertions( sectionNode );
  10286. if( !sectionNode.stdOut.empty() )
  10287. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  10288. if( !sectionNode.stdErr.empty() )
  10289. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  10290. }
  10291. for( auto const& childNode : sectionNode.childSections )
  10292. if( className.empty() )
  10293. writeSection( name, "", *childNode );
  10294. else
  10295. writeSection( className, name, *childNode );
  10296. }
  10297. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  10298. for( auto const& assertion : sectionNode.assertions )
  10299. writeAssertion( assertion );
  10300. }
  10301. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  10302. AssertionResult const& result = stats.assertionResult;
  10303. if( !result.isOk() ) {
  10304. std::string elementName;
  10305. switch( result.getResultType() ) {
  10306. case ResultWas::ThrewException:
  10307. case ResultWas::FatalErrorCondition:
  10308. elementName = "error";
  10309. break;
  10310. case ResultWas::ExplicitFailure:
  10311. elementName = "failure";
  10312. break;
  10313. case ResultWas::ExpressionFailed:
  10314. elementName = "failure";
  10315. break;
  10316. case ResultWas::DidntThrowException:
  10317. elementName = "failure";
  10318. break;
  10319. // We should never see these here:
  10320. case ResultWas::Info:
  10321. case ResultWas::Warning:
  10322. case ResultWas::Ok:
  10323. case ResultWas::Unknown:
  10324. case ResultWas::FailureBit:
  10325. case ResultWas::Exception:
  10326. elementName = "internalError";
  10327. break;
  10328. }
  10329. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  10330. xml.writeAttribute( "message", result.getExpandedExpression() );
  10331. xml.writeAttribute( "type", result.getTestMacroName() );
  10332. ReusableStringStream rss;
  10333. if( !result.getMessage().empty() )
  10334. rss << result.getMessage() << '\n';
  10335. for( auto const& msg : stats.infoMessages )
  10336. if( msg.type == ResultWas::Info )
  10337. rss << msg.message << '\n';
  10338. rss << "at " << result.getSourceInfo();
  10339. xml.writeText( rss.str(), false );
  10340. }
  10341. }
  10342. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  10343. } // end namespace Catch
  10344. // end catch_reporter_junit.cpp
  10345. // start catch_reporter_listening.cpp
  10346. #include <cassert>
  10347. namespace Catch {
  10348. ListeningReporter::ListeningReporter() {
  10349. // We will assume that listeners will always want all assertions
  10350. m_preferences.shouldReportAllAssertions = true;
  10351. }
  10352. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  10353. m_listeners.push_back( std::move( listener ) );
  10354. }
  10355. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  10356. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  10357. m_reporter = std::move( reporter );
  10358. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  10359. }
  10360. ReporterPreferences ListeningReporter::getPreferences() const {
  10361. return m_preferences;
  10362. }
  10363. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  10364. return std::set<Verbosity>{ };
  10365. }
  10366. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  10367. for ( auto const& listener : m_listeners ) {
  10368. listener->noMatchingTestCases( spec );
  10369. }
  10370. m_reporter->noMatchingTestCases( spec );
  10371. }
  10372. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  10373. for ( auto const& listener : m_listeners ) {
  10374. listener->benchmarkStarting( benchmarkInfo );
  10375. }
  10376. m_reporter->benchmarkStarting( benchmarkInfo );
  10377. }
  10378. void ListeningReporter::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
  10379. for ( auto const& listener : m_listeners ) {
  10380. listener->benchmarkEnded( benchmarkStats );
  10381. }
  10382. m_reporter->benchmarkEnded( benchmarkStats );
  10383. }
  10384. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  10385. for ( auto const& listener : m_listeners ) {
  10386. listener->testRunStarting( testRunInfo );
  10387. }
  10388. m_reporter->testRunStarting( testRunInfo );
  10389. }
  10390. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  10391. for ( auto const& listener : m_listeners ) {
  10392. listener->testGroupStarting( groupInfo );
  10393. }
  10394. m_reporter->testGroupStarting( groupInfo );
  10395. }
  10396. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  10397. for ( auto const& listener : m_listeners ) {
  10398. listener->testCaseStarting( testInfo );
  10399. }
  10400. m_reporter->testCaseStarting( testInfo );
  10401. }
  10402. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  10403. for ( auto const& listener : m_listeners ) {
  10404. listener->sectionStarting( sectionInfo );
  10405. }
  10406. m_reporter->sectionStarting( sectionInfo );
  10407. }
  10408. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  10409. for ( auto const& listener : m_listeners ) {
  10410. listener->assertionStarting( assertionInfo );
  10411. }
  10412. m_reporter->assertionStarting( assertionInfo );
  10413. }
  10414. // The return value indicates if the messages buffer should be cleared:
  10415. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10416. for( auto const& listener : m_listeners ) {
  10417. static_cast<void>( listener->assertionEnded( assertionStats ) );
  10418. }
  10419. return m_reporter->assertionEnded( assertionStats );
  10420. }
  10421. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  10422. for ( auto const& listener : m_listeners ) {
  10423. listener->sectionEnded( sectionStats );
  10424. }
  10425. m_reporter->sectionEnded( sectionStats );
  10426. }
  10427. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10428. for ( auto const& listener : m_listeners ) {
  10429. listener->testCaseEnded( testCaseStats );
  10430. }
  10431. m_reporter->testCaseEnded( testCaseStats );
  10432. }
  10433. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10434. for ( auto const& listener : m_listeners ) {
  10435. listener->testGroupEnded( testGroupStats );
  10436. }
  10437. m_reporter->testGroupEnded( testGroupStats );
  10438. }
  10439. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  10440. for ( auto const& listener : m_listeners ) {
  10441. listener->testRunEnded( testRunStats );
  10442. }
  10443. m_reporter->testRunEnded( testRunStats );
  10444. }
  10445. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  10446. for ( auto const& listener : m_listeners ) {
  10447. listener->skipTest( testInfo );
  10448. }
  10449. m_reporter->skipTest( testInfo );
  10450. }
  10451. bool ListeningReporter::isMulti() const {
  10452. return true;
  10453. }
  10454. } // end namespace Catch
  10455. // end catch_reporter_listening.cpp
  10456. // start catch_reporter_xml.cpp
  10457. #if defined(_MSC_VER)
  10458. #pragma warning(push)
  10459. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  10460. // Note that 4062 (not all labels are handled
  10461. // and default is missing) is enabled
  10462. #endif
  10463. namespace Catch {
  10464. XmlReporter::XmlReporter( ReporterConfig const& _config )
  10465. : StreamingReporterBase( _config ),
  10466. m_xml(_config.stream())
  10467. {
  10468. m_reporterPrefs.shouldRedirectStdOut = true;
  10469. m_reporterPrefs.shouldReportAllAssertions = true;
  10470. }
  10471. XmlReporter::~XmlReporter() = default;
  10472. std::string XmlReporter::getDescription() {
  10473. return "Reports test results as an XML document";
  10474. }
  10475. std::string XmlReporter::getStylesheetRef() const {
  10476. return std::string();
  10477. }
  10478. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  10479. m_xml
  10480. .writeAttribute( "filename", sourceInfo.file )
  10481. .writeAttribute( "line", sourceInfo.line );
  10482. }
  10483. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  10484. StreamingReporterBase::noMatchingTestCases( s );
  10485. }
  10486. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  10487. StreamingReporterBase::testRunStarting( testInfo );
  10488. std::string stylesheetRef = getStylesheetRef();
  10489. if( !stylesheetRef.empty() )
  10490. m_xml.writeStylesheetRef( stylesheetRef );
  10491. m_xml.startElement( "Catch" );
  10492. if( !m_config->name().empty() )
  10493. m_xml.writeAttribute( "name", m_config->name() );
  10494. }
  10495. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  10496. StreamingReporterBase::testGroupStarting( groupInfo );
  10497. m_xml.startElement( "Group" )
  10498. .writeAttribute( "name", groupInfo.name );
  10499. }
  10500. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  10501. StreamingReporterBase::testCaseStarting(testInfo);
  10502. m_xml.startElement( "TestCase" )
  10503. .writeAttribute( "name", trim( testInfo.name ) )
  10504. .writeAttribute( "description", testInfo.description )
  10505. .writeAttribute( "tags", testInfo.tagsAsString() );
  10506. writeSourceInfo( testInfo.lineInfo );
  10507. if ( m_config->showDurations() == ShowDurations::Always )
  10508. m_testCaseTimer.start();
  10509. m_xml.ensureTagClosed();
  10510. }
  10511. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  10512. StreamingReporterBase::sectionStarting( sectionInfo );
  10513. if( m_sectionDepth++ > 0 ) {
  10514. m_xml.startElement( "Section" )
  10515. .writeAttribute( "name", trim( sectionInfo.name ) );
  10516. writeSourceInfo( sectionInfo.lineInfo );
  10517. m_xml.ensureTagClosed();
  10518. }
  10519. }
  10520. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  10521. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10522. AssertionResult const& result = assertionStats.assertionResult;
  10523. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  10524. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  10525. // Print any info messages in <Info> tags.
  10526. for( auto const& msg : assertionStats.infoMessages ) {
  10527. if( msg.type == ResultWas::Info && includeResults ) {
  10528. m_xml.scopedElement( "Info" )
  10529. .writeText( msg.message );
  10530. } else if ( msg.type == ResultWas::Warning ) {
  10531. m_xml.scopedElement( "Warning" )
  10532. .writeText( msg.message );
  10533. }
  10534. }
  10535. }
  10536. // Drop out if result was successful but we're not printing them.
  10537. if( !includeResults && result.getResultType() != ResultWas::Warning )
  10538. return true;
  10539. // Print the expression if there is one.
  10540. if( result.hasExpression() ) {
  10541. m_xml.startElement( "Expression" )
  10542. .writeAttribute( "success", result.succeeded() )
  10543. .writeAttribute( "type", result.getTestMacroName() );
  10544. writeSourceInfo( result.getSourceInfo() );
  10545. m_xml.scopedElement( "Original" )
  10546. .writeText( result.getExpression() );
  10547. m_xml.scopedElement( "Expanded" )
  10548. .writeText( result.getExpandedExpression() );
  10549. }
  10550. // And... Print a result applicable to each result type.
  10551. switch( result.getResultType() ) {
  10552. case ResultWas::ThrewException:
  10553. m_xml.startElement( "Exception" );
  10554. writeSourceInfo( result.getSourceInfo() );
  10555. m_xml.writeText( result.getMessage() );
  10556. m_xml.endElement();
  10557. break;
  10558. case ResultWas::FatalErrorCondition:
  10559. m_xml.startElement( "FatalErrorCondition" );
  10560. writeSourceInfo( result.getSourceInfo() );
  10561. m_xml.writeText( result.getMessage() );
  10562. m_xml.endElement();
  10563. break;
  10564. case ResultWas::Info:
  10565. m_xml.scopedElement( "Info" )
  10566. .writeText( result.getMessage() );
  10567. break;
  10568. case ResultWas::Warning:
  10569. // Warning will already have been written
  10570. break;
  10571. case ResultWas::ExplicitFailure:
  10572. m_xml.startElement( "Failure" );
  10573. writeSourceInfo( result.getSourceInfo() );
  10574. m_xml.writeText( result.getMessage() );
  10575. m_xml.endElement();
  10576. break;
  10577. default:
  10578. break;
  10579. }
  10580. if( result.hasExpression() )
  10581. m_xml.endElement();
  10582. return true;
  10583. }
  10584. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  10585. StreamingReporterBase::sectionEnded( sectionStats );
  10586. if( --m_sectionDepth > 0 ) {
  10587. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  10588. e.writeAttribute( "successes", sectionStats.assertions.passed );
  10589. e.writeAttribute( "failures", sectionStats.assertions.failed );
  10590. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  10591. if ( m_config->showDurations() == ShowDurations::Always )
  10592. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  10593. m_xml.endElement();
  10594. }
  10595. }
  10596. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10597. StreamingReporterBase::testCaseEnded( testCaseStats );
  10598. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  10599. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  10600. if ( m_config->showDurations() == ShowDurations::Always )
  10601. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  10602. if( !testCaseStats.stdOut.empty() )
  10603. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  10604. if( !testCaseStats.stdErr.empty() )
  10605. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  10606. m_xml.endElement();
  10607. }
  10608. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10609. StreamingReporterBase::testGroupEnded( testGroupStats );
  10610. // TODO: Check testGroupStats.aborting and act accordingly.
  10611. m_xml.scopedElement( "OverallResults" )
  10612. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  10613. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  10614. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  10615. m_xml.endElement();
  10616. }
  10617. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  10618. StreamingReporterBase::testRunEnded( testRunStats );
  10619. m_xml.scopedElement( "OverallResults" )
  10620. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  10621. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  10622. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  10623. m_xml.endElement();
  10624. }
  10625. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  10626. } // end namespace Catch
  10627. #if defined(_MSC_VER)
  10628. #pragma warning(pop)
  10629. #endif
  10630. // end catch_reporter_xml.cpp
  10631. namespace Catch {
  10632. LeakDetector leakDetector;
  10633. }
  10634. #ifdef __clang__
  10635. #pragma clang diagnostic pop
  10636. #endif
  10637. // end catch_impl.hpp
  10638. #endif
  10639. #ifdef CATCH_CONFIG_MAIN
  10640. // start catch_default_main.hpp
  10641. #ifndef __OBJC__
  10642. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  10643. // Standard C/C++ Win32 Unicode wmain entry point
  10644. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  10645. #else
  10646. // Standard C/C++ main entry point
  10647. int main (int argc, char * argv[]) {
  10648. #endif
  10649. return Catch::Session().run( argc, argv );
  10650. }
  10651. #else // __OBJC__
  10652. // Objective-C entry point
  10653. int main (int argc, char * const argv[]) {
  10654. #if !CATCH_ARC_ENABLED
  10655. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  10656. #endif
  10657. Catch::registerTestMethods();
  10658. int result = Catch::Session().run( argc, (char**)argv );
  10659. #if !CATCH_ARC_ENABLED
  10660. [pool drain];
  10661. #endif
  10662. return result;
  10663. }
  10664. #endif // __OBJC__
  10665. // end catch_default_main.hpp
  10666. #endif
  10667. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  10668. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  10669. # undef CLARA_CONFIG_MAIN
  10670. #endif
  10671. #if !defined(CATCH_CONFIG_DISABLE)
  10672. //////
  10673. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  10674. #ifdef CATCH_CONFIG_PREFIX_ALL
  10675. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10676. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10677. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", __VA_ARGS__ )
  10678. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  10679. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  10680. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10681. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  10682. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  10683. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10684. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10685. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10686. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10687. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10688. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  10689. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", __VA_ARGS__ )
  10690. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  10691. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10692. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10693. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10694. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10695. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10696. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10697. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  10698. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  10699. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10700. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  10701. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  10702. #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( "CATCH_CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  10703. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  10704. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  10705. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  10706. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  10707. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  10708. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  10709. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10710. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10711. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10712. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  10713. // "BDD-style" convenience wrappers
  10714. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  10715. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  10716. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  10717. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  10718. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And when: " << desc )
  10719. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  10720. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  10721. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  10722. #else
  10723. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10724. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10725. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10726. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  10727. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  10728. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10729. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  10730. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10731. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10732. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10733. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  10734. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10735. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10736. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  10737. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10738. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  10739. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10740. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10741. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  10742. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10743. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10744. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10745. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  10746. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  10747. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10748. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  10749. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  10750. #define CAPTURE( msg ) INTERNAL_CATCH_INFO( "CAPTURE", #msg " := " << ::Catch::Detail::stringify(msg) )
  10751. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  10752. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  10753. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  10754. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  10755. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  10756. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  10757. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  10758. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10759. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  10760. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  10761. #endif
  10762. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  10763. // "BDD-style" convenience wrappers
  10764. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  10765. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  10766. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  10767. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  10768. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And when: " << desc )
  10769. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  10770. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  10771. using Catch::Detail::Approx;
  10772. #else // CATCH_CONFIG_DISABLE
  10773. //////
  10774. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  10775. #ifdef CATCH_CONFIG_PREFIX_ALL
  10776. #define CATCH_REQUIRE( ... ) (void)(0)
  10777. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  10778. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  10779. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  10780. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  10781. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10782. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10783. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  10784. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  10785. #define CATCH_CHECK( ... ) (void)(0)
  10786. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  10787. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  10788. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  10789. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  10790. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  10791. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  10792. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  10793. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10794. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10795. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10796. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  10797. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10798. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  10799. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  10800. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10801. #define CATCH_INFO( msg ) (void)(0)
  10802. #define CATCH_WARN( msg ) (void)(0)
  10803. #define CATCH_CAPTURE( msg ) (void)(0)
  10804. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10805. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10806. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  10807. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  10808. #define CATCH_SECTION( ... )
  10809. #define CATCH_DYNAMIC_SECTION( ... )
  10810. #define CATCH_FAIL( ... ) (void)(0)
  10811. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  10812. #define CATCH_SUCCEED( ... ) (void)(0)
  10813. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10814. // "BDD-style" convenience wrappers
  10815. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10816. #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 )
  10817. #define CATCH_GIVEN( desc )
  10818. #define CATCH_WHEN( desc )
  10819. #define CATCH_AND_WHEN( desc )
  10820. #define CATCH_THEN( desc )
  10821. #define CATCH_AND_THEN( desc )
  10822. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  10823. #else
  10824. #define REQUIRE( ... ) (void)(0)
  10825. #define REQUIRE_FALSE( ... ) (void)(0)
  10826. #define REQUIRE_THROWS( ... ) (void)(0)
  10827. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  10828. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  10829. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10830. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10831. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10832. #define REQUIRE_NOTHROW( ... ) (void)(0)
  10833. #define CHECK( ... ) (void)(0)
  10834. #define CHECK_FALSE( ... ) (void)(0)
  10835. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  10836. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  10837. #define CHECK_NOFAIL( ... ) (void)(0)
  10838. #define CHECK_THROWS( ... ) (void)(0)
  10839. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  10840. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  10841. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10842. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  10843. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10844. #define CHECK_NOTHROW( ... ) (void)(0)
  10845. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  10846. #define CHECK_THAT( arg, matcher ) (void)(0)
  10847. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  10848. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  10849. #define INFO( msg ) (void)(0)
  10850. #define WARN( msg ) (void)(0)
  10851. #define CAPTURE( msg ) (void)(0)
  10852. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10853. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10854. #define METHOD_AS_TEST_CASE( method, ... )
  10855. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  10856. #define SECTION( ... )
  10857. #define DYNAMIC_SECTION( ... )
  10858. #define FAIL( ... ) (void)(0)
  10859. #define FAIL_CHECK( ... ) (void)(0)
  10860. #define SUCCEED( ... ) (void)(0)
  10861. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  10862. #endif
  10863. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  10864. // "BDD-style" convenience wrappers
  10865. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  10866. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  10867. #define GIVEN( desc )
  10868. #define WHEN( desc )
  10869. #define AND_WHEN( desc )
  10870. #define THEN( desc )
  10871. #define AND_THEN( desc )
  10872. using Catch::Detail::Approx;
  10873. #endif
  10874. #endif // ! CATCH_CONFIG_IMPL_ONLY
  10875. // start catch_reenable_warnings.h
  10876. #ifdef __clang__
  10877. # ifdef __ICC // icpc defines the __clang__ macro
  10878. # pragma warning(pop)
  10879. # else
  10880. # pragma clang diagnostic pop
  10881. # endif
  10882. #elif defined __GNUC__
  10883. # pragma GCC diagnostic pop
  10884. #endif
  10885. // end catch_reenable_warnings.h
  10886. // end catch.hpp
  10887. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED