您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

13923 行
462KB

  1. /*
  2. * Catch v2.4.0
  3. * Generated: 2018-09-04 11:55:01.682061
  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 4
  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. // CATCH_CONFIG_DISABLE_EXCEPTIONS : Are exceptions enabled?
  94. // ****************
  95. // Note to maintainers: if new toggles are added please document them
  96. // in configuration.md, too
  97. // ****************
  98. // In general each macro has a _NO_<feature name> form
  99. // (e.g. CATCH_CONFIG_NO_POSIX_SIGNALS) which disables the feature.
  100. // Many features, at point of detection, define an _INTERNAL_ macro, so they
  101. // can be combined, en-mass, with the _NO_ forms later.
  102. #ifdef __cplusplus
  103. # if __cplusplus >= 201402L
  104. # define CATCH_CPP14_OR_GREATER
  105. # endif
  106. # if __cplusplus >= 201703L
  107. # define CATCH_CPP17_OR_GREATER
  108. # endif
  109. #endif
  110. #if defined(CATCH_CPP17_OR_GREATER)
  111. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  112. #endif
  113. #ifdef __clang__
  114. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  115. _Pragma( "clang diagnostic push" ) \
  116. _Pragma( "clang diagnostic ignored \"-Wexit-time-destructors\"" ) \
  117. _Pragma( "clang diagnostic ignored \"-Wglobal-constructors\"")
  118. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  119. _Pragma( "clang diagnostic pop" )
  120. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  121. _Pragma( "clang diagnostic push" ) \
  122. _Pragma( "clang diagnostic ignored \"-Wparentheses\"" )
  123. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  124. _Pragma( "clang diagnostic pop" )
  125. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  126. _Pragma( "clang diagnostic push" ) \
  127. _Pragma( "clang diagnostic ignored \"-Wunused-variable\"" )
  128. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS \
  129. _Pragma( "clang diagnostic pop" )
  130. #endif // __clang__
  131. ////////////////////////////////////////////////////////////////////////////////
  132. // Assume that non-Windows platforms support posix signals by default
  133. #if !defined(CATCH_PLATFORM_WINDOWS)
  134. #define CATCH_INTERNAL_CONFIG_POSIX_SIGNALS
  135. #endif
  136. ////////////////////////////////////////////////////////////////////////////////
  137. // We know some environments not to support full POSIX signals
  138. #if defined(__CYGWIN__) || defined(__QNX__) || defined(__EMSCRIPTEN__) || defined(__DJGPP__)
  139. #define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  140. #endif
  141. #ifdef __OS400__
  142. # define CATCH_INTERNAL_CONFIG_NO_POSIX_SIGNALS
  143. # define CATCH_CONFIG_COLOUR_NONE
  144. #endif
  145. ////////////////////////////////////////////////////////////////////////////////
  146. // Android somehow still does not support std::to_string
  147. #if defined(__ANDROID__)
  148. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  149. #endif
  150. ////////////////////////////////////////////////////////////////////////////////
  151. // Not all Windows environments support SEH properly
  152. #if defined(__MINGW32__)
  153. # define CATCH_INTERNAL_CONFIG_NO_WINDOWS_SEH
  154. #endif
  155. ////////////////////////////////////////////////////////////////////////////////
  156. // PS4
  157. #if defined(__ORBIS__)
  158. # define CATCH_INTERNAL_CONFIG_NO_NEW_CAPTURE
  159. #endif
  160. ////////////////////////////////////////////////////////////////////////////////
  161. // Cygwin
  162. #ifdef __CYGWIN__
  163. // Required for some versions of Cygwin to declare gettimeofday
  164. // see: http://stackoverflow.com/questions/36901803/gettimeofday-not-declared-in-this-scope-cygwin
  165. # define _BSD_SOURCE
  166. #endif // __CYGWIN__
  167. ////////////////////////////////////////////////////////////////////////////////
  168. // Visual C++
  169. #ifdef _MSC_VER
  170. # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
  171. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  172. # endif
  173. // Universal Windows platform does not support SEH
  174. // Or console colours (or console at all...)
  175. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  176. # define CATCH_CONFIG_COLOUR_NONE
  177. # else
  178. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  179. # endif
  180. #endif // _MSC_VER
  181. ////////////////////////////////////////////////////////////////////////////////
  182. // Check if we are compiled with -fno-exceptions or equivalent
  183. #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
  184. # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
  185. #endif
  186. ////////////////////////////////////////////////////////////////////////////////
  187. // DJGPP
  188. #ifdef __DJGPP__
  189. # define CATCH_INTERNAL_CONFIG_NO_WCHAR
  190. #endif // __DJGPP__
  191. ////////////////////////////////////////////////////////////////////////////////
  192. // Use of __COUNTER__ is suppressed during code analysis in
  193. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  194. // handled by it.
  195. // Otherwise all supported compilers support COUNTER macro,
  196. // but user still might want to turn it off
  197. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  198. #define CATCH_INTERNAL_CONFIG_COUNTER
  199. #endif
  200. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  201. # define CATCH_CONFIG_COUNTER
  202. #endif
  203. #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)
  204. # define CATCH_CONFIG_WINDOWS_SEH
  205. #endif
  206. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  207. #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)
  208. # define CATCH_CONFIG_POSIX_SIGNALS
  209. #endif
  210. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  211. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  212. # define CATCH_CONFIG_WCHAR
  213. #endif
  214. #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
  215. # define CATCH_CONFIG_CPP11_TO_STRING
  216. #endif
  217. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  218. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  219. #endif
  220. #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  221. # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
  222. #endif
  223. #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)
  224. # define CATCH_CONFIG_NEW_CAPTURE
  225. #endif
  226. #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  227. # define CATCH_CONFIG_DISABLE_EXCEPTIONS
  228. #endif
  229. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  230. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  231. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  232. #endif
  233. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  234. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  235. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  236. #endif
  237. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
  238. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
  239. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  240. #endif
  241. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  242. #define CATCH_TRY if ((true))
  243. #define CATCH_CATCH_ALL if ((false))
  244. #define CATCH_CATCH_ANON(type) if ((false))
  245. #else
  246. #define CATCH_TRY try
  247. #define CATCH_CATCH_ALL catch (...)
  248. #define CATCH_CATCH_ANON(type) catch (type)
  249. #endif
  250. // end catch_compiler_capabilities.h
  251. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  252. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  253. #ifdef CATCH_CONFIG_COUNTER
  254. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  255. #else
  256. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  257. #endif
  258. #include <iosfwd>
  259. #include <string>
  260. #include <cstdint>
  261. namespace Catch {
  262. struct CaseSensitive { enum Choice {
  263. Yes,
  264. No
  265. }; };
  266. class NonCopyable {
  267. NonCopyable( NonCopyable const& ) = delete;
  268. NonCopyable( NonCopyable && ) = delete;
  269. NonCopyable& operator = ( NonCopyable const& ) = delete;
  270. NonCopyable& operator = ( NonCopyable && ) = delete;
  271. protected:
  272. NonCopyable();
  273. virtual ~NonCopyable();
  274. };
  275. struct SourceLineInfo {
  276. SourceLineInfo() = delete;
  277. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  278. : file( _file ),
  279. line( _line )
  280. {}
  281. SourceLineInfo( SourceLineInfo const& other ) = default;
  282. SourceLineInfo( SourceLineInfo && ) = default;
  283. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  284. SourceLineInfo& operator = ( SourceLineInfo && ) = default;
  285. bool empty() const noexcept;
  286. bool operator == ( SourceLineInfo const& other ) const noexcept;
  287. bool operator < ( SourceLineInfo const& other ) const noexcept;
  288. char const* file;
  289. std::size_t line;
  290. };
  291. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  292. // Use this in variadic streaming macros to allow
  293. // >> +StreamEndStop
  294. // as well as
  295. // >> stuff +StreamEndStop
  296. struct StreamEndStop {
  297. std::string operator+() const;
  298. };
  299. template<typename T>
  300. T const& operator + ( T const& value, StreamEndStop ) {
  301. return value;
  302. }
  303. }
  304. #define CATCH_INTERNAL_LINEINFO \
  305. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  306. // end catch_common.h
  307. namespace Catch {
  308. struct RegistrarForTagAliases {
  309. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  310. };
  311. } // end namespace Catch
  312. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  313. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  314. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  315. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  316. // end catch_tag_alias_autoregistrar.h
  317. // start catch_test_registry.h
  318. // start catch_interfaces_testcase.h
  319. #include <vector>
  320. #include <memory>
  321. namespace Catch {
  322. class TestSpec;
  323. struct ITestInvoker {
  324. virtual void invoke () const = 0;
  325. virtual ~ITestInvoker();
  326. };
  327. using ITestCasePtr = std::shared_ptr<ITestInvoker>;
  328. class TestCase;
  329. struct IConfig;
  330. struct ITestCaseRegistry {
  331. virtual ~ITestCaseRegistry();
  332. virtual std::vector<TestCase> const& getAllTests() const = 0;
  333. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  334. };
  335. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  336. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  337. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  338. }
  339. // end catch_interfaces_testcase.h
  340. // start catch_stringref.h
  341. #include <cstddef>
  342. #include <string>
  343. #include <iosfwd>
  344. namespace Catch {
  345. class StringData;
  346. /// A non-owning string class (similar to the forthcoming std::string_view)
  347. /// Note that, because a StringRef may be a substring of another string,
  348. /// it may not be null terminated. c_str() must return a null terminated
  349. /// string, however, and so the StringRef will internally take ownership
  350. /// (taking a copy), if necessary. In theory this ownership is not externally
  351. /// visible - but it does mean (substring) StringRefs should not be shared between
  352. /// threads.
  353. class StringRef {
  354. public:
  355. using size_type = std::size_t;
  356. private:
  357. friend struct StringRefTestAccess;
  358. char const* m_start;
  359. size_type m_size;
  360. char* m_data = nullptr;
  361. void takeOwnership();
  362. static constexpr char const* const s_empty = "";
  363. public: // construction/ assignment
  364. StringRef() noexcept
  365. : StringRef( s_empty, 0 )
  366. {}
  367. StringRef( StringRef const& other ) noexcept
  368. : m_start( other.m_start ),
  369. m_size( other.m_size )
  370. {}
  371. StringRef( StringRef&& other ) noexcept
  372. : m_start( other.m_start ),
  373. m_size( other.m_size ),
  374. m_data( other.m_data )
  375. {
  376. other.m_data = nullptr;
  377. }
  378. StringRef( char const* rawChars ) noexcept;
  379. StringRef( char const* rawChars, size_type size ) noexcept
  380. : m_start( rawChars ),
  381. m_size( size )
  382. {}
  383. StringRef( std::string const& stdString ) noexcept
  384. : m_start( stdString.c_str() ),
  385. m_size( stdString.size() )
  386. {}
  387. ~StringRef() noexcept {
  388. delete[] m_data;
  389. }
  390. auto operator = ( StringRef const &other ) noexcept -> StringRef& {
  391. delete[] m_data;
  392. m_data = nullptr;
  393. m_start = other.m_start;
  394. m_size = other.m_size;
  395. return *this;
  396. }
  397. operator std::string() const;
  398. void swap( StringRef& other ) noexcept;
  399. public: // operators
  400. auto operator == ( StringRef const& other ) const noexcept -> bool;
  401. auto operator != ( StringRef const& other ) const noexcept -> bool;
  402. auto operator[] ( size_type index ) const noexcept -> char;
  403. public: // named queries
  404. auto empty() const noexcept -> bool {
  405. return m_size == 0;
  406. }
  407. auto size() const noexcept -> size_type {
  408. return m_size;
  409. }
  410. auto numberOfCharacters() const noexcept -> size_type;
  411. auto c_str() const -> char const*;
  412. public: // substrings and searches
  413. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  414. // Returns the current start pointer.
  415. // Note that the pointer can change when if the StringRef is a substring
  416. auto currentData() const noexcept -> char const*;
  417. private: // ownership queries - may not be consistent between calls
  418. auto isOwned() const noexcept -> bool;
  419. auto isSubstring() const noexcept -> bool;
  420. };
  421. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  422. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  423. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  424. auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
  425. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  426. inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  427. return StringRef( rawChars, size );
  428. }
  429. } // namespace Catch
  430. inline auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
  431. return Catch::StringRef( rawChars, size );
  432. }
  433. // end catch_stringref.h
  434. namespace Catch {
  435. template<typename C>
  436. class TestInvokerAsMethod : public ITestInvoker {
  437. void (C::*m_testAsMethod)();
  438. public:
  439. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  440. void invoke() const override {
  441. C obj;
  442. (obj.*m_testAsMethod)();
  443. }
  444. };
  445. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  446. template<typename C>
  447. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  448. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  449. }
  450. struct NameAndTags {
  451. NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
  452. StringRef name;
  453. StringRef tags;
  454. };
  455. struct AutoReg : NonCopyable {
  456. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  457. ~AutoReg();
  458. };
  459. } // end namespace Catch
  460. #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
  461. #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
  462. #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
  463. #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  464. #if defined(CATCH_CONFIG_DISABLE)
  465. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  466. static void TestName()
  467. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  468. namespace{ \
  469. struct TestName : INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF ClassName) { \
  470. void test(); \
  471. }; \
  472. } \
  473. void TestName::test()
  474. #endif
  475. ///////////////////////////////////////////////////////////////////////////////
  476. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  477. static void TestName(); \
  478. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  479. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  480. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  481. static void TestName()
  482. #define INTERNAL_CATCH_TESTCASE( ... ) \
  483. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  484. ///////////////////////////////////////////////////////////////////////////////
  485. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  486. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  487. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  488. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  489. ///////////////////////////////////////////////////////////////////////////////
  490. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  491. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  492. namespace{ \
  493. struct TestName : INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF ClassName) { \
  494. void test(); \
  495. }; \
  496. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  497. } \
  498. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  499. void TestName::test()
  500. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  501. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  502. ///////////////////////////////////////////////////////////////////////////////
  503. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  504. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  505. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  506. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  507. // end catch_test_registry.h
  508. // start catch_capture.hpp
  509. // start catch_assertionhandler.h
  510. // start catch_assertioninfo.h
  511. // start catch_result_type.h
  512. namespace Catch {
  513. // ResultWas::OfType enum
  514. struct ResultWas { enum OfType {
  515. Unknown = -1,
  516. Ok = 0,
  517. Info = 1,
  518. Warning = 2,
  519. FailureBit = 0x10,
  520. ExpressionFailed = FailureBit | 1,
  521. ExplicitFailure = FailureBit | 2,
  522. Exception = 0x100 | FailureBit,
  523. ThrewException = Exception | 1,
  524. DidntThrowException = Exception | 2,
  525. FatalErrorCondition = 0x200 | FailureBit
  526. }; };
  527. bool isOk( ResultWas::OfType resultType );
  528. bool isJustInfo( int flags );
  529. // ResultDisposition::Flags enum
  530. struct ResultDisposition { enum Flags {
  531. Normal = 0x01,
  532. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  533. FalseTest = 0x04, // Prefix expression with !
  534. SuppressFail = 0x08 // Failures are reported but do not fail the test
  535. }; };
  536. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  537. bool shouldContinueOnFailure( int flags );
  538. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  539. bool shouldSuppressFailure( int flags );
  540. } // end namespace Catch
  541. // end catch_result_type.h
  542. namespace Catch {
  543. struct AssertionInfo
  544. {
  545. StringRef macroName;
  546. SourceLineInfo lineInfo;
  547. StringRef capturedExpression;
  548. ResultDisposition::Flags resultDisposition;
  549. // We want to delete this constructor but a compiler bug in 4.8 means
  550. // the struct is then treated as non-aggregate
  551. //AssertionInfo() = delete;
  552. };
  553. } // end namespace Catch
  554. // end catch_assertioninfo.h
  555. // start catch_decomposer.h
  556. // start catch_tostring.h
  557. #include <vector>
  558. #include <cstddef>
  559. #include <type_traits>
  560. #include <string>
  561. // start catch_stream.h
  562. #include <iosfwd>
  563. #include <cstddef>
  564. #include <ostream>
  565. namespace Catch {
  566. std::ostream& cout();
  567. std::ostream& cerr();
  568. std::ostream& clog();
  569. class StringRef;
  570. struct IStream {
  571. virtual ~IStream();
  572. virtual std::ostream& stream() const = 0;
  573. };
  574. auto makeStream( StringRef const &filename ) -> IStream const*;
  575. class ReusableStringStream {
  576. std::size_t m_index;
  577. std::ostream* m_oss;
  578. public:
  579. ReusableStringStream();
  580. ~ReusableStringStream();
  581. auto str() const -> std::string;
  582. template<typename T>
  583. auto operator << ( T const& value ) -> ReusableStringStream& {
  584. *m_oss << value;
  585. return *this;
  586. }
  587. auto get() -> std::ostream& { return *m_oss; }
  588. };
  589. }
  590. // end catch_stream.h
  591. #ifdef __OBJC__
  592. // start catch_objc_arc.hpp
  593. #import <Foundation/Foundation.h>
  594. #ifdef __has_feature
  595. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  596. #else
  597. #define CATCH_ARC_ENABLED 0
  598. #endif
  599. void arcSafeRelease( NSObject* obj );
  600. id performOptionalSelector( id obj, SEL sel );
  601. #if !CATCH_ARC_ENABLED
  602. inline void arcSafeRelease( NSObject* obj ) {
  603. [obj release];
  604. }
  605. inline id performOptionalSelector( id obj, SEL sel ) {
  606. if( [obj respondsToSelector: sel] )
  607. return [obj performSelector: sel];
  608. return nil;
  609. }
  610. #define CATCH_UNSAFE_UNRETAINED
  611. #define CATCH_ARC_STRONG
  612. #else
  613. inline void arcSafeRelease( NSObject* ){}
  614. inline id performOptionalSelector( id obj, SEL sel ) {
  615. #ifdef __clang__
  616. #pragma clang diagnostic push
  617. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  618. #endif
  619. if( [obj respondsToSelector: sel] )
  620. return [obj performSelector: sel];
  621. #ifdef __clang__
  622. #pragma clang diagnostic pop
  623. #endif
  624. return nil;
  625. }
  626. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  627. #define CATCH_ARC_STRONG __strong
  628. #endif
  629. // end catch_objc_arc.hpp
  630. #endif
  631. #ifdef _MSC_VER
  632. #pragma warning(push)
  633. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  634. #endif
  635. // We need a dummy global operator<< so we can bring it into Catch namespace later
  636. struct Catch_global_namespace_dummy {};
  637. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  638. namespace Catch {
  639. // Bring in operator<< from global namespace into Catch namespace
  640. using ::operator<<;
  641. namespace Detail {
  642. extern const std::string unprintableString;
  643. std::string rawMemoryToString( const void *object, std::size_t size );
  644. template<typename T>
  645. std::string rawMemoryToString( const T& object ) {
  646. return rawMemoryToString( &object, sizeof(object) );
  647. }
  648. template<typename T>
  649. class IsStreamInsertable {
  650. template<typename SS, typename TT>
  651. static auto test(int)
  652. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  653. template<typename, typename>
  654. static auto test(...)->std::false_type;
  655. public:
  656. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  657. };
  658. template<typename E>
  659. std::string convertUnknownEnumToString( E e );
  660. template<typename T>
  661. typename std::enable_if<
  662. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  663. std::string>::type convertUnstreamable( T const& ) {
  664. return Detail::unprintableString;
  665. }
  666. template<typename T>
  667. typename std::enable_if<
  668. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  669. std::string>::type convertUnstreamable(T const& ex) {
  670. return ex.what();
  671. }
  672. template<typename T>
  673. typename std::enable_if<
  674. std::is_enum<T>::value
  675. , std::string>::type convertUnstreamable( T const& value ) {
  676. return convertUnknownEnumToString( value );
  677. }
  678. #if defined(_MANAGED)
  679. //! Convert a CLR string to a utf8 std::string
  680. template<typename T>
  681. std::string clrReferenceToString( T^ ref ) {
  682. if (ref == nullptr)
  683. return std::string("null");
  684. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  685. cli::pin_ptr<System::Byte> p = &bytes[0];
  686. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  687. }
  688. #endif
  689. } // namespace Detail
  690. // If we decide for C++14, change these to enable_if_ts
  691. template <typename T, typename = void>
  692. struct StringMaker {
  693. template <typename Fake = T>
  694. static
  695. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  696. convert(const Fake& value) {
  697. ReusableStringStream rss;
  698. // NB: call using the function-like syntax to avoid ambiguity with
  699. // user-defined templated operator<< under clang.
  700. rss.operator<<(value);
  701. return rss.str();
  702. }
  703. template <typename Fake = T>
  704. static
  705. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  706. convert( const Fake& value ) {
  707. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  708. return Detail::convertUnstreamable(value);
  709. #else
  710. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  711. #endif
  712. }
  713. };
  714. namespace Detail {
  715. // This function dispatches all stringification requests inside of Catch.
  716. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  717. template <typename T>
  718. std::string stringify(const T& e) {
  719. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  720. }
  721. template<typename E>
  722. std::string convertUnknownEnumToString( E e ) {
  723. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  724. }
  725. #if defined(_MANAGED)
  726. template <typename T>
  727. std::string stringify( T^ e ) {
  728. return ::Catch::StringMaker<T^>::convert(e);
  729. }
  730. #endif
  731. } // namespace Detail
  732. // Some predefined specializations
  733. template<>
  734. struct StringMaker<std::string> {
  735. static std::string convert(const std::string& str);
  736. };
  737. #ifdef CATCH_CONFIG_WCHAR
  738. template<>
  739. struct StringMaker<std::wstring> {
  740. static std::string convert(const std::wstring& wstr);
  741. };
  742. #endif
  743. template<>
  744. struct StringMaker<char const *> {
  745. static std::string convert(char const * str);
  746. };
  747. template<>
  748. struct StringMaker<char *> {
  749. static std::string convert(char * str);
  750. };
  751. #ifdef CATCH_CONFIG_WCHAR
  752. template<>
  753. struct StringMaker<wchar_t const *> {
  754. static std::string convert(wchar_t const * str);
  755. };
  756. template<>
  757. struct StringMaker<wchar_t *> {
  758. static std::string convert(wchar_t * str);
  759. };
  760. #endif
  761. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  762. // while keeping string semantics?
  763. template<int SZ>
  764. struct StringMaker<char[SZ]> {
  765. static std::string convert(char const* str) {
  766. return ::Catch::Detail::stringify(std::string{ str });
  767. }
  768. };
  769. template<int SZ>
  770. struct StringMaker<signed char[SZ]> {
  771. static std::string convert(signed char const* str) {
  772. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  773. }
  774. };
  775. template<int SZ>
  776. struct StringMaker<unsigned char[SZ]> {
  777. static std::string convert(unsigned char const* str) {
  778. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  779. }
  780. };
  781. template<>
  782. struct StringMaker<int> {
  783. static std::string convert(int value);
  784. };
  785. template<>
  786. struct StringMaker<long> {
  787. static std::string convert(long value);
  788. };
  789. template<>
  790. struct StringMaker<long long> {
  791. static std::string convert(long long value);
  792. };
  793. template<>
  794. struct StringMaker<unsigned int> {
  795. static std::string convert(unsigned int value);
  796. };
  797. template<>
  798. struct StringMaker<unsigned long> {
  799. static std::string convert(unsigned long value);
  800. };
  801. template<>
  802. struct StringMaker<unsigned long long> {
  803. static std::string convert(unsigned long long value);
  804. };
  805. template<>
  806. struct StringMaker<bool> {
  807. static std::string convert(bool b);
  808. };
  809. template<>
  810. struct StringMaker<char> {
  811. static std::string convert(char c);
  812. };
  813. template<>
  814. struct StringMaker<signed char> {
  815. static std::string convert(signed char c);
  816. };
  817. template<>
  818. struct StringMaker<unsigned char> {
  819. static std::string convert(unsigned char c);
  820. };
  821. template<>
  822. struct StringMaker<std::nullptr_t> {
  823. static std::string convert(std::nullptr_t);
  824. };
  825. template<>
  826. struct StringMaker<float> {
  827. static std::string convert(float value);
  828. };
  829. template<>
  830. struct StringMaker<double> {
  831. static std::string convert(double value);
  832. };
  833. template <typename T>
  834. struct StringMaker<T*> {
  835. template <typename U>
  836. static std::string convert(U* p) {
  837. if (p) {
  838. return ::Catch::Detail::rawMemoryToString(p);
  839. } else {
  840. return "nullptr";
  841. }
  842. }
  843. };
  844. template <typename R, typename C>
  845. struct StringMaker<R C::*> {
  846. static std::string convert(R C::* p) {
  847. if (p) {
  848. return ::Catch::Detail::rawMemoryToString(p);
  849. } else {
  850. return "nullptr";
  851. }
  852. }
  853. };
  854. #if defined(_MANAGED)
  855. template <typename T>
  856. struct StringMaker<T^> {
  857. static std::string convert( T^ ref ) {
  858. return ::Catch::Detail::clrReferenceToString(ref);
  859. }
  860. };
  861. #endif
  862. namespace Detail {
  863. template<typename InputIterator>
  864. std::string rangeToString(InputIterator first, InputIterator last) {
  865. ReusableStringStream rss;
  866. rss << "{ ";
  867. if (first != last) {
  868. rss << ::Catch::Detail::stringify(*first);
  869. for (++first; first != last; ++first)
  870. rss << ", " << ::Catch::Detail::stringify(*first);
  871. }
  872. rss << " }";
  873. return rss.str();
  874. }
  875. }
  876. #ifdef __OBJC__
  877. template<>
  878. struct StringMaker<NSString*> {
  879. static std::string convert(NSString * nsstring) {
  880. if (!nsstring)
  881. return "nil";
  882. return std::string("@") + [nsstring UTF8String];
  883. }
  884. };
  885. template<>
  886. struct StringMaker<NSObject*> {
  887. static std::string convert(NSObject* nsObject) {
  888. return ::Catch::Detail::stringify([nsObject description]);
  889. }
  890. };
  891. namespace Detail {
  892. inline std::string stringify( NSString* nsstring ) {
  893. return StringMaker<NSString*>::convert( nsstring );
  894. }
  895. } // namespace Detail
  896. #endif // __OBJC__
  897. } // namespace Catch
  898. //////////////////////////////////////////////////////
  899. // Separate std-lib types stringification, so it can be selectively enabled
  900. // This means that we do not bring in
  901. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  902. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  903. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  904. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  905. #endif
  906. // Separate std::pair specialization
  907. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  908. #include <utility>
  909. namespace Catch {
  910. template<typename T1, typename T2>
  911. struct StringMaker<std::pair<T1, T2> > {
  912. static std::string convert(const std::pair<T1, T2>& pair) {
  913. ReusableStringStream rss;
  914. rss << "{ "
  915. << ::Catch::Detail::stringify(pair.first)
  916. << ", "
  917. << ::Catch::Detail::stringify(pair.second)
  918. << " }";
  919. return rss.str();
  920. }
  921. };
  922. }
  923. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  924. // Separate std::tuple specialization
  925. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  926. #include <tuple>
  927. namespace Catch {
  928. namespace Detail {
  929. template<
  930. typename Tuple,
  931. std::size_t N = 0,
  932. bool = (N < std::tuple_size<Tuple>::value)
  933. >
  934. struct TupleElementPrinter {
  935. static void print(const Tuple& tuple, std::ostream& os) {
  936. os << (N ? ", " : " ")
  937. << ::Catch::Detail::stringify(std::get<N>(tuple));
  938. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  939. }
  940. };
  941. template<
  942. typename Tuple,
  943. std::size_t N
  944. >
  945. struct TupleElementPrinter<Tuple, N, false> {
  946. static void print(const Tuple&, std::ostream&) {}
  947. };
  948. }
  949. template<typename ...Types>
  950. struct StringMaker<std::tuple<Types...>> {
  951. static std::string convert(const std::tuple<Types...>& tuple) {
  952. ReusableStringStream rss;
  953. rss << '{';
  954. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  955. rss << " }";
  956. return rss.str();
  957. }
  958. };
  959. }
  960. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  961. namespace Catch {
  962. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  963. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  964. using std::begin;
  965. using std::end;
  966. not_this_one begin( ... );
  967. not_this_one end( ... );
  968. template <typename T>
  969. struct is_range {
  970. static const bool value =
  971. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  972. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  973. };
  974. #if defined(_MANAGED) // Managed types are never ranges
  975. template <typename T>
  976. struct is_range<T^> {
  977. static const bool value = false;
  978. };
  979. #endif
  980. template<typename Range>
  981. std::string rangeToString( Range const& range ) {
  982. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  983. }
  984. // Handle vector<bool> specially
  985. template<typename Allocator>
  986. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  987. ReusableStringStream rss;
  988. rss << "{ ";
  989. bool first = true;
  990. for( bool b : v ) {
  991. if( first )
  992. first = false;
  993. else
  994. rss << ", ";
  995. rss << ::Catch::Detail::stringify( b );
  996. }
  997. rss << " }";
  998. return rss.str();
  999. }
  1000. template<typename R>
  1001. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  1002. static std::string convert( R const& range ) {
  1003. return rangeToString( range );
  1004. }
  1005. };
  1006. template <typename T, int SZ>
  1007. struct StringMaker<T[SZ]> {
  1008. static std::string convert(T const(&arr)[SZ]) {
  1009. return rangeToString(arr);
  1010. }
  1011. };
  1012. } // namespace Catch
  1013. // Separate std::chrono::duration specialization
  1014. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  1015. #include <ctime>
  1016. #include <ratio>
  1017. #include <chrono>
  1018. namespace Catch {
  1019. template <class Ratio>
  1020. struct ratio_string {
  1021. static std::string symbol();
  1022. };
  1023. template <class Ratio>
  1024. std::string ratio_string<Ratio>::symbol() {
  1025. Catch::ReusableStringStream rss;
  1026. rss << '[' << Ratio::num << '/'
  1027. << Ratio::den << ']';
  1028. return rss.str();
  1029. }
  1030. template <>
  1031. struct ratio_string<std::atto> {
  1032. static std::string symbol();
  1033. };
  1034. template <>
  1035. struct ratio_string<std::femto> {
  1036. static std::string symbol();
  1037. };
  1038. template <>
  1039. struct ratio_string<std::pico> {
  1040. static std::string symbol();
  1041. };
  1042. template <>
  1043. struct ratio_string<std::nano> {
  1044. static std::string symbol();
  1045. };
  1046. template <>
  1047. struct ratio_string<std::micro> {
  1048. static std::string symbol();
  1049. };
  1050. template <>
  1051. struct ratio_string<std::milli> {
  1052. static std::string symbol();
  1053. };
  1054. ////////////
  1055. // std::chrono::duration specializations
  1056. template<typename Value, typename Ratio>
  1057. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  1058. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  1059. ReusableStringStream rss;
  1060. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  1061. return rss.str();
  1062. }
  1063. };
  1064. template<typename Value>
  1065. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  1066. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  1067. ReusableStringStream rss;
  1068. rss << duration.count() << " s";
  1069. return rss.str();
  1070. }
  1071. };
  1072. template<typename Value>
  1073. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1074. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1075. ReusableStringStream rss;
  1076. rss << duration.count() << " m";
  1077. return rss.str();
  1078. }
  1079. };
  1080. template<typename Value>
  1081. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1082. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1083. ReusableStringStream rss;
  1084. rss << duration.count() << " h";
  1085. return rss.str();
  1086. }
  1087. };
  1088. ////////////
  1089. // std::chrono::time_point specialization
  1090. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1091. template<typename Clock, typename Duration>
  1092. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1093. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1094. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1095. }
  1096. };
  1097. // std::chrono::time_point<system_clock> specialization
  1098. template<typename Duration>
  1099. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1100. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1101. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1102. #ifdef _MSC_VER
  1103. std::tm timeInfo = {};
  1104. gmtime_s(&timeInfo, &converted);
  1105. #else
  1106. std::tm* timeInfo = std::gmtime(&converted);
  1107. #endif
  1108. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1109. char timeStamp[timeStampSize];
  1110. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1111. #ifdef _MSC_VER
  1112. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1113. #else
  1114. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1115. #endif
  1116. return std::string(timeStamp);
  1117. }
  1118. };
  1119. }
  1120. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1121. #ifdef _MSC_VER
  1122. #pragma warning(pop)
  1123. #endif
  1124. // end catch_tostring.h
  1125. #include <iosfwd>
  1126. #ifdef _MSC_VER
  1127. #pragma warning(push)
  1128. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1129. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1130. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1131. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1132. #endif
  1133. namespace Catch {
  1134. struct ITransientExpression {
  1135. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1136. auto getResult() const -> bool { return m_result; }
  1137. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1138. ITransientExpression( bool isBinaryExpression, bool result )
  1139. : m_isBinaryExpression( isBinaryExpression ),
  1140. m_result( result )
  1141. {}
  1142. // We don't actually need a virtual destructor, but many static analysers
  1143. // complain if it's not here :-(
  1144. virtual ~ITransientExpression();
  1145. bool m_isBinaryExpression;
  1146. bool m_result;
  1147. };
  1148. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1149. template<typename LhsT, typename RhsT>
  1150. class BinaryExpr : public ITransientExpression {
  1151. LhsT m_lhs;
  1152. StringRef m_op;
  1153. RhsT m_rhs;
  1154. void streamReconstructedExpression( std::ostream &os ) const override {
  1155. formatReconstructedExpression
  1156. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1157. }
  1158. public:
  1159. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1160. : ITransientExpression{ true, comparisonResult },
  1161. m_lhs( lhs ),
  1162. m_op( op ),
  1163. m_rhs( rhs )
  1164. {}
  1165. };
  1166. template<typename LhsT>
  1167. class UnaryExpr : public ITransientExpression {
  1168. LhsT m_lhs;
  1169. void streamReconstructedExpression( std::ostream &os ) const override {
  1170. os << Catch::Detail::stringify( m_lhs );
  1171. }
  1172. public:
  1173. explicit UnaryExpr( LhsT lhs )
  1174. : ITransientExpression{ false, lhs ? true : false },
  1175. m_lhs( lhs )
  1176. {}
  1177. };
  1178. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1179. template<typename LhsT, typename RhsT>
  1180. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1181. template<typename T>
  1182. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1183. template<typename T>
  1184. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1185. template<typename T>
  1186. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1187. template<typename T>
  1188. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1189. template<typename LhsT, typename RhsT>
  1190. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1191. template<typename T>
  1192. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1193. template<typename T>
  1194. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1195. template<typename T>
  1196. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1197. template<typename T>
  1198. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1199. template<typename LhsT>
  1200. class ExprLhs {
  1201. LhsT m_lhs;
  1202. public:
  1203. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1204. template<typename RhsT>
  1205. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1206. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1207. }
  1208. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1209. return { m_lhs == rhs, m_lhs, "==", rhs };
  1210. }
  1211. template<typename RhsT>
  1212. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1213. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1214. }
  1215. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1216. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1217. }
  1218. template<typename RhsT>
  1219. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1220. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1221. }
  1222. template<typename RhsT>
  1223. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1224. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  1225. }
  1226. template<typename RhsT>
  1227. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1228. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  1229. }
  1230. template<typename RhsT>
  1231. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1232. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  1233. }
  1234. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  1235. return UnaryExpr<LhsT>{ m_lhs };
  1236. }
  1237. };
  1238. void handleExpression( ITransientExpression const& expr );
  1239. template<typename T>
  1240. void handleExpression( ExprLhs<T> const& expr ) {
  1241. handleExpression( expr.makeUnaryExpr() );
  1242. }
  1243. struct Decomposer {
  1244. template<typename T>
  1245. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  1246. return ExprLhs<T const&>{ lhs };
  1247. }
  1248. auto operator <=( bool value ) -> ExprLhs<bool> {
  1249. return ExprLhs<bool>{ value };
  1250. }
  1251. };
  1252. } // end namespace Catch
  1253. #ifdef _MSC_VER
  1254. #pragma warning(pop)
  1255. #endif
  1256. // end catch_decomposer.h
  1257. // start catch_interfaces_capture.h
  1258. #include <string>
  1259. namespace Catch {
  1260. class AssertionResult;
  1261. struct AssertionInfo;
  1262. struct SectionInfo;
  1263. struct SectionEndInfo;
  1264. struct MessageInfo;
  1265. struct Counts;
  1266. struct BenchmarkInfo;
  1267. struct BenchmarkStats;
  1268. struct AssertionReaction;
  1269. struct SourceLineInfo;
  1270. struct ITransientExpression;
  1271. struct IGeneratorTracker;
  1272. struct IResultCapture {
  1273. virtual ~IResultCapture();
  1274. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  1275. Counts& assertions ) = 0;
  1276. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  1277. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  1278. virtual auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
  1279. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  1280. virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;
  1281. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  1282. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  1283. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  1284. virtual void handleExpr
  1285. ( AssertionInfo const& info,
  1286. ITransientExpression const& expr,
  1287. AssertionReaction& reaction ) = 0;
  1288. virtual void handleMessage
  1289. ( AssertionInfo const& info,
  1290. ResultWas::OfType resultType,
  1291. StringRef const& message,
  1292. AssertionReaction& reaction ) = 0;
  1293. virtual void handleUnexpectedExceptionNotThrown
  1294. ( AssertionInfo const& info,
  1295. AssertionReaction& reaction ) = 0;
  1296. virtual void handleUnexpectedInflightException
  1297. ( AssertionInfo const& info,
  1298. std::string const& message,
  1299. AssertionReaction& reaction ) = 0;
  1300. virtual void handleIncomplete
  1301. ( AssertionInfo const& info ) = 0;
  1302. virtual void handleNonExpr
  1303. ( AssertionInfo const &info,
  1304. ResultWas::OfType resultType,
  1305. AssertionReaction &reaction ) = 0;
  1306. virtual bool lastAssertionPassed() = 0;
  1307. virtual void assertionPassed() = 0;
  1308. // Deprecated, do not use:
  1309. virtual std::string getCurrentTestName() const = 0;
  1310. virtual const AssertionResult* getLastResult() const = 0;
  1311. virtual void exceptionEarlyReported() = 0;
  1312. };
  1313. IResultCapture& getResultCapture();
  1314. }
  1315. // end catch_interfaces_capture.h
  1316. namespace Catch {
  1317. struct TestFailureException{};
  1318. struct AssertionResultData;
  1319. struct IResultCapture;
  1320. class RunContext;
  1321. class LazyExpression {
  1322. friend class AssertionHandler;
  1323. friend struct AssertionStats;
  1324. friend class RunContext;
  1325. ITransientExpression const* m_transientExpression = nullptr;
  1326. bool m_isNegated;
  1327. public:
  1328. LazyExpression( bool isNegated );
  1329. LazyExpression( LazyExpression const& other );
  1330. LazyExpression& operator = ( LazyExpression const& ) = delete;
  1331. explicit operator bool() const;
  1332. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  1333. };
  1334. struct AssertionReaction {
  1335. bool shouldDebugBreak = false;
  1336. bool shouldThrow = false;
  1337. };
  1338. class AssertionHandler {
  1339. AssertionInfo m_assertionInfo;
  1340. AssertionReaction m_reaction;
  1341. bool m_completed = false;
  1342. IResultCapture& m_resultCapture;
  1343. public:
  1344. AssertionHandler
  1345. ( StringRef const& macroName,
  1346. SourceLineInfo const& lineInfo,
  1347. StringRef capturedExpression,
  1348. ResultDisposition::Flags resultDisposition );
  1349. ~AssertionHandler() {
  1350. if ( !m_completed ) {
  1351. m_resultCapture.handleIncomplete( m_assertionInfo );
  1352. }
  1353. }
  1354. template<typename T>
  1355. void handleExpr( ExprLhs<T> const& expr ) {
  1356. handleExpr( expr.makeUnaryExpr() );
  1357. }
  1358. void handleExpr( ITransientExpression const& expr );
  1359. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  1360. void handleExceptionThrownAsExpected();
  1361. void handleUnexpectedExceptionNotThrown();
  1362. void handleExceptionNotThrownAsExpected();
  1363. void handleThrowingCallSkipped();
  1364. void handleUnexpectedInflightException();
  1365. void complete();
  1366. void setCompleted();
  1367. // query
  1368. auto allowThrows() const -> bool;
  1369. };
  1370. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
  1371. } // namespace Catch
  1372. // end catch_assertionhandler.h
  1373. // start catch_message.h
  1374. #include <string>
  1375. #include <vector>
  1376. namespace Catch {
  1377. struct MessageInfo {
  1378. MessageInfo( StringRef const& _macroName,
  1379. SourceLineInfo const& _lineInfo,
  1380. ResultWas::OfType _type );
  1381. StringRef macroName;
  1382. std::string message;
  1383. SourceLineInfo lineInfo;
  1384. ResultWas::OfType type;
  1385. unsigned int sequence;
  1386. bool operator == ( MessageInfo const& other ) const;
  1387. bool operator < ( MessageInfo const& other ) const;
  1388. private:
  1389. static unsigned int globalCount;
  1390. };
  1391. struct MessageStream {
  1392. template<typename T>
  1393. MessageStream& operator << ( T const& value ) {
  1394. m_stream << value;
  1395. return *this;
  1396. }
  1397. ReusableStringStream m_stream;
  1398. };
  1399. struct MessageBuilder : MessageStream {
  1400. MessageBuilder( StringRef const& macroName,
  1401. SourceLineInfo const& lineInfo,
  1402. ResultWas::OfType type );
  1403. template<typename T>
  1404. MessageBuilder& operator << ( T const& value ) {
  1405. m_stream << value;
  1406. return *this;
  1407. }
  1408. MessageInfo m_info;
  1409. };
  1410. class ScopedMessage {
  1411. public:
  1412. explicit ScopedMessage( MessageBuilder const& builder );
  1413. ~ScopedMessage();
  1414. MessageInfo m_info;
  1415. };
  1416. class Capturer {
  1417. std::vector<MessageInfo> m_messages;
  1418. IResultCapture& m_resultCapture = getResultCapture();
  1419. size_t m_captured = 0;
  1420. public:
  1421. Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
  1422. ~Capturer();
  1423. void captureValue( size_t index, StringRef value );
  1424. template<typename T>
  1425. void captureValues( size_t index, T&& value ) {
  1426. captureValue( index, Catch::Detail::stringify( value ) );
  1427. }
  1428. template<typename T, typename... Ts>
  1429. void captureValues( size_t index, T&& value, Ts&&... values ) {
  1430. captureValues( index, value );
  1431. captureValues( index+1, values... );
  1432. }
  1433. };
  1434. } // end namespace Catch
  1435. // end catch_message.h
  1436. #if !defined(CATCH_CONFIG_DISABLE)
  1437. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  1438. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  1439. #else
  1440. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  1441. #endif
  1442. #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  1443. ///////////////////////////////////////////////////////////////////////////////
  1444. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  1445. // macros.
  1446. #define INTERNAL_CATCH_TRY
  1447. #define INTERNAL_CATCH_CATCH( capturer )
  1448. #else // CATCH_CONFIG_FAST_COMPILE
  1449. #define INTERNAL_CATCH_TRY try
  1450. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  1451. #endif
  1452. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  1453. ///////////////////////////////////////////////////////////////////////////////
  1454. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  1455. do { \
  1456. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1457. INTERNAL_CATCH_TRY { \
  1458. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  1459. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  1460. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  1461. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1462. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1463. } 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
  1464. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  1465. ///////////////////////////////////////////////////////////////////////////////
  1466. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  1467. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1468. if( Catch::getResultCapture().lastAssertionPassed() )
  1469. ///////////////////////////////////////////////////////////////////////////////
  1470. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  1471. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1472. if( !Catch::getResultCapture().lastAssertionPassed() )
  1473. ///////////////////////////////////////////////////////////////////////////////
  1474. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  1475. do { \
  1476. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1477. try { \
  1478. static_cast<void>(__VA_ARGS__); \
  1479. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  1480. } \
  1481. catch( ... ) { \
  1482. catchAssertionHandler.handleUnexpectedInflightException(); \
  1483. } \
  1484. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1485. } while( false )
  1486. ///////////////////////////////////////////////////////////////////////////////
  1487. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  1488. do { \
  1489. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  1490. if( catchAssertionHandler.allowThrows() ) \
  1491. try { \
  1492. static_cast<void>(__VA_ARGS__); \
  1493. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1494. } \
  1495. catch( ... ) { \
  1496. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1497. } \
  1498. else \
  1499. catchAssertionHandler.handleThrowingCallSkipped(); \
  1500. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1501. } while( false )
  1502. ///////////////////////////////////////////////////////////////////////////////
  1503. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  1504. do { \
  1505. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  1506. if( catchAssertionHandler.allowThrows() ) \
  1507. try { \
  1508. static_cast<void>(expr); \
  1509. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1510. } \
  1511. catch( exceptionType const& ) { \
  1512. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1513. } \
  1514. catch( ... ) { \
  1515. catchAssertionHandler.handleUnexpectedInflightException(); \
  1516. } \
  1517. else \
  1518. catchAssertionHandler.handleThrowingCallSkipped(); \
  1519. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1520. } while( false )
  1521. ///////////////////////////////////////////////////////////////////////////////
  1522. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  1523. do { \
  1524. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
  1525. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  1526. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1527. } while( false )
  1528. ///////////////////////////////////////////////////////////////////////////////
  1529. #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
  1530. auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
  1531. varName.captureValues( 0, __VA_ARGS__ )
  1532. ///////////////////////////////////////////////////////////////////////////////
  1533. #define INTERNAL_CATCH_INFO( macroName, log ) \
  1534. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  1535. ///////////////////////////////////////////////////////////////////////////////
  1536. // Although this is matcher-based, it can be used with just a string
  1537. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  1538. do { \
  1539. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1540. if( catchAssertionHandler.allowThrows() ) \
  1541. try { \
  1542. static_cast<void>(__VA_ARGS__); \
  1543. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1544. } \
  1545. catch( ... ) { \
  1546. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
  1547. } \
  1548. else \
  1549. catchAssertionHandler.handleThrowingCallSkipped(); \
  1550. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1551. } while( false )
  1552. #endif // CATCH_CONFIG_DISABLE
  1553. // end catch_capture.hpp
  1554. // start catch_section.h
  1555. // start catch_section_info.h
  1556. // start catch_totals.h
  1557. #include <cstddef>
  1558. namespace Catch {
  1559. struct Counts {
  1560. Counts operator - ( Counts const& other ) const;
  1561. Counts& operator += ( Counts const& other );
  1562. std::size_t total() const;
  1563. bool allPassed() const;
  1564. bool allOk() const;
  1565. std::size_t passed = 0;
  1566. std::size_t failed = 0;
  1567. std::size_t failedButOk = 0;
  1568. };
  1569. struct Totals {
  1570. Totals operator - ( Totals const& other ) const;
  1571. Totals& operator += ( Totals const& other );
  1572. Totals delta( Totals const& prevTotals ) const;
  1573. int error = 0;
  1574. Counts assertions;
  1575. Counts testCases;
  1576. };
  1577. }
  1578. // end catch_totals.h
  1579. #include <string>
  1580. namespace Catch {
  1581. struct SectionInfo {
  1582. SectionInfo
  1583. ( SourceLineInfo const& _lineInfo,
  1584. std::string const& _name );
  1585. // Deprecated
  1586. SectionInfo
  1587. ( SourceLineInfo const& _lineInfo,
  1588. std::string const& _name,
  1589. std::string const& ) : SectionInfo( _lineInfo, _name ) {}
  1590. std::string name;
  1591. std::string description; // !Deprecated: this will always be empty
  1592. SourceLineInfo lineInfo;
  1593. };
  1594. struct SectionEndInfo {
  1595. SectionInfo sectionInfo;
  1596. Counts prevAssertions;
  1597. double durationInSeconds;
  1598. };
  1599. } // end namespace Catch
  1600. // end catch_section_info.h
  1601. // start catch_timer.h
  1602. #include <cstdint>
  1603. namespace Catch {
  1604. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  1605. auto getEstimatedClockResolution() -> uint64_t;
  1606. class Timer {
  1607. uint64_t m_nanoseconds = 0;
  1608. public:
  1609. void start();
  1610. auto getElapsedNanoseconds() const -> uint64_t;
  1611. auto getElapsedMicroseconds() const -> uint64_t;
  1612. auto getElapsedMilliseconds() const -> unsigned int;
  1613. auto getElapsedSeconds() const -> double;
  1614. };
  1615. } // namespace Catch
  1616. // end catch_timer.h
  1617. #include <string>
  1618. namespace Catch {
  1619. class Section : NonCopyable {
  1620. public:
  1621. Section( SectionInfo const& info );
  1622. ~Section();
  1623. // This indicates whether the section should be executed or not
  1624. explicit operator bool() const;
  1625. private:
  1626. SectionInfo m_info;
  1627. std::string m_name;
  1628. Counts m_assertions;
  1629. bool m_sectionIncluded;
  1630. Timer m_timer;
  1631. };
  1632. } // end namespace Catch
  1633. #define INTERNAL_CATCH_SECTION( ... ) \
  1634. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  1635. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
  1636. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  1637. #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
  1638. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  1639. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
  1640. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  1641. // end catch_section.h
  1642. // start catch_benchmark.h
  1643. #include <cstdint>
  1644. #include <string>
  1645. namespace Catch {
  1646. class BenchmarkLooper {
  1647. std::string m_name;
  1648. std::size_t m_count = 0;
  1649. std::size_t m_iterationsToRun = 1;
  1650. uint64_t m_resolution;
  1651. Timer m_timer;
  1652. static auto getResolution() -> uint64_t;
  1653. public:
  1654. // Keep most of this inline as it's on the code path that is being timed
  1655. BenchmarkLooper( StringRef name )
  1656. : m_name( name ),
  1657. m_resolution( getResolution() )
  1658. {
  1659. reportStart();
  1660. m_timer.start();
  1661. }
  1662. explicit operator bool() {
  1663. if( m_count < m_iterationsToRun )
  1664. return true;
  1665. return needsMoreIterations();
  1666. }
  1667. void increment() {
  1668. ++m_count;
  1669. }
  1670. void reportStart();
  1671. auto needsMoreIterations() -> bool;
  1672. };
  1673. } // end namespace Catch
  1674. #define BENCHMARK( name ) \
  1675. for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )
  1676. // end catch_benchmark.h
  1677. // start catch_interfaces_exception.h
  1678. // start catch_interfaces_registry_hub.h
  1679. #include <string>
  1680. #include <memory>
  1681. namespace Catch {
  1682. class TestCase;
  1683. struct ITestCaseRegistry;
  1684. struct IExceptionTranslatorRegistry;
  1685. struct IExceptionTranslator;
  1686. struct IReporterRegistry;
  1687. struct IReporterFactory;
  1688. struct ITagAliasRegistry;
  1689. class StartupExceptionRegistry;
  1690. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  1691. struct IRegistryHub {
  1692. virtual ~IRegistryHub();
  1693. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  1694. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  1695. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  1696. virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
  1697. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  1698. };
  1699. struct IMutableRegistryHub {
  1700. virtual ~IMutableRegistryHub();
  1701. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  1702. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  1703. virtual void registerTest( TestCase const& testInfo ) = 0;
  1704. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  1705. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  1706. virtual void registerStartupException() noexcept = 0;
  1707. };
  1708. IRegistryHub const& getRegistryHub();
  1709. IMutableRegistryHub& getMutableRegistryHub();
  1710. void cleanUp();
  1711. std::string translateActiveException();
  1712. }
  1713. // end catch_interfaces_registry_hub.h
  1714. #if defined(CATCH_CONFIG_DISABLE)
  1715. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  1716. static std::string translatorName( signature )
  1717. #endif
  1718. #include <exception>
  1719. #include <string>
  1720. #include <vector>
  1721. namespace Catch {
  1722. using exceptionTranslateFunction = std::string(*)();
  1723. struct IExceptionTranslator;
  1724. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  1725. struct IExceptionTranslator {
  1726. virtual ~IExceptionTranslator();
  1727. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  1728. };
  1729. struct IExceptionTranslatorRegistry {
  1730. virtual ~IExceptionTranslatorRegistry();
  1731. virtual std::string translateActiveException() const = 0;
  1732. };
  1733. class ExceptionTranslatorRegistrar {
  1734. template<typename T>
  1735. class ExceptionTranslator : public IExceptionTranslator {
  1736. public:
  1737. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  1738. : m_translateFunction( translateFunction )
  1739. {}
  1740. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  1741. try {
  1742. if( it == itEnd )
  1743. std::rethrow_exception(std::current_exception());
  1744. else
  1745. return (*it)->translate( it+1, itEnd );
  1746. }
  1747. catch( T& ex ) {
  1748. return m_translateFunction( ex );
  1749. }
  1750. }
  1751. protected:
  1752. std::string(*m_translateFunction)( T& );
  1753. };
  1754. public:
  1755. template<typename T>
  1756. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  1757. getMutableRegistryHub().registerTranslator
  1758. ( new ExceptionTranslator<T>( translateFunction ) );
  1759. }
  1760. };
  1761. }
  1762. ///////////////////////////////////////////////////////////////////////////////
  1763. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  1764. static std::string translatorName( signature ); \
  1765. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1766. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  1767. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1768. static std::string translatorName( signature )
  1769. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  1770. // end catch_interfaces_exception.h
  1771. // start catch_approx.h
  1772. #include <type_traits>
  1773. namespace Catch {
  1774. namespace Detail {
  1775. class Approx {
  1776. private:
  1777. bool equalityComparisonImpl(double other) const;
  1778. // Validates the new margin (margin >= 0)
  1779. // out-of-line to avoid including stdexcept in the header
  1780. void setMargin(double margin);
  1781. // Validates the new epsilon (0 < epsilon < 1)
  1782. // out-of-line to avoid including stdexcept in the header
  1783. void setEpsilon(double epsilon);
  1784. public:
  1785. explicit Approx ( double value );
  1786. static Approx custom();
  1787. Approx operator-() const;
  1788. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1789. Approx operator()( T const& value ) {
  1790. Approx approx( static_cast<double>(value) );
  1791. approx.m_epsilon = m_epsilon;
  1792. approx.m_margin = m_margin;
  1793. approx.m_scale = m_scale;
  1794. return approx;
  1795. }
  1796. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1797. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  1798. {}
  1799. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1800. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  1801. auto lhs_v = static_cast<double>(lhs);
  1802. return rhs.equalityComparisonImpl(lhs_v);
  1803. }
  1804. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1805. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  1806. return operator==( rhs, lhs );
  1807. }
  1808. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1809. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  1810. return !operator==( lhs, rhs );
  1811. }
  1812. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1813. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  1814. return !operator==( rhs, lhs );
  1815. }
  1816. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1817. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  1818. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  1819. }
  1820. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1821. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  1822. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  1823. }
  1824. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1825. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  1826. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  1827. }
  1828. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1829. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  1830. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  1831. }
  1832. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1833. Approx& epsilon( T const& newEpsilon ) {
  1834. double epsilonAsDouble = static_cast<double>(newEpsilon);
  1835. setEpsilon(epsilonAsDouble);
  1836. return *this;
  1837. }
  1838. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1839. Approx& margin( T const& newMargin ) {
  1840. double marginAsDouble = static_cast<double>(newMargin);
  1841. setMargin(marginAsDouble);
  1842. return *this;
  1843. }
  1844. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1845. Approx& scale( T const& newScale ) {
  1846. m_scale = static_cast<double>(newScale);
  1847. return *this;
  1848. }
  1849. std::string toString() const;
  1850. private:
  1851. double m_epsilon;
  1852. double m_margin;
  1853. double m_scale;
  1854. double m_value;
  1855. };
  1856. } // end namespace Detail
  1857. namespace literals {
  1858. Detail::Approx operator "" _a(long double val);
  1859. Detail::Approx operator "" _a(unsigned long long val);
  1860. } // end namespace literals
  1861. template<>
  1862. struct StringMaker<Catch::Detail::Approx> {
  1863. static std::string convert(Catch::Detail::Approx const& value);
  1864. };
  1865. } // end namespace Catch
  1866. // end catch_approx.h
  1867. // start catch_string_manip.h
  1868. #include <string>
  1869. #include <iosfwd>
  1870. namespace Catch {
  1871. bool startsWith( std::string const& s, std::string const& prefix );
  1872. bool startsWith( std::string const& s, char prefix );
  1873. bool endsWith( std::string const& s, std::string const& suffix );
  1874. bool endsWith( std::string const& s, char suffix );
  1875. bool contains( std::string const& s, std::string const& infix );
  1876. void toLowerInPlace( std::string& s );
  1877. std::string toLower( std::string const& s );
  1878. std::string trim( std::string const& str );
  1879. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  1880. struct pluralise {
  1881. pluralise( std::size_t count, std::string const& label );
  1882. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  1883. std::size_t m_count;
  1884. std::string m_label;
  1885. };
  1886. }
  1887. // end catch_string_manip.h
  1888. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  1889. // start catch_capture_matchers.h
  1890. // start catch_matchers.h
  1891. #include <string>
  1892. #include <vector>
  1893. namespace Catch {
  1894. namespace Matchers {
  1895. namespace Impl {
  1896. template<typename ArgT> struct MatchAllOf;
  1897. template<typename ArgT> struct MatchAnyOf;
  1898. template<typename ArgT> struct MatchNotOf;
  1899. class MatcherUntypedBase {
  1900. public:
  1901. MatcherUntypedBase() = default;
  1902. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  1903. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  1904. std::string toString() const;
  1905. protected:
  1906. virtual ~MatcherUntypedBase();
  1907. virtual std::string describe() const = 0;
  1908. mutable std::string m_cachedToString;
  1909. };
  1910. #ifdef __clang__
  1911. # pragma clang diagnostic push
  1912. # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  1913. #endif
  1914. template<typename ObjectT>
  1915. struct MatcherMethod {
  1916. virtual bool match( ObjectT const& arg ) const = 0;
  1917. };
  1918. template<typename PtrT>
  1919. struct MatcherMethod<PtrT*> {
  1920. virtual bool match( PtrT* arg ) const = 0;
  1921. };
  1922. #ifdef __clang__
  1923. # pragma clang diagnostic pop
  1924. #endif
  1925. template<typename T>
  1926. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  1927. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  1928. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  1929. MatchNotOf<T> operator ! () const;
  1930. };
  1931. template<typename ArgT>
  1932. struct MatchAllOf : MatcherBase<ArgT> {
  1933. bool match( ArgT const& arg ) const override {
  1934. for( auto matcher : m_matchers ) {
  1935. if (!matcher->match(arg))
  1936. return false;
  1937. }
  1938. return true;
  1939. }
  1940. std::string describe() const override {
  1941. std::string description;
  1942. description.reserve( 4 + m_matchers.size()*32 );
  1943. description += "( ";
  1944. bool first = true;
  1945. for( auto matcher : m_matchers ) {
  1946. if( first )
  1947. first = false;
  1948. else
  1949. description += " and ";
  1950. description += matcher->toString();
  1951. }
  1952. description += " )";
  1953. return description;
  1954. }
  1955. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  1956. m_matchers.push_back( &other );
  1957. return *this;
  1958. }
  1959. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1960. };
  1961. template<typename ArgT>
  1962. struct MatchAnyOf : MatcherBase<ArgT> {
  1963. bool match( ArgT const& arg ) const override {
  1964. for( auto matcher : m_matchers ) {
  1965. if (matcher->match(arg))
  1966. return true;
  1967. }
  1968. return false;
  1969. }
  1970. std::string describe() const override {
  1971. std::string description;
  1972. description.reserve( 4 + m_matchers.size()*32 );
  1973. description += "( ";
  1974. bool first = true;
  1975. for( auto matcher : m_matchers ) {
  1976. if( first )
  1977. first = false;
  1978. else
  1979. description += " or ";
  1980. description += matcher->toString();
  1981. }
  1982. description += " )";
  1983. return description;
  1984. }
  1985. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  1986. m_matchers.push_back( &other );
  1987. return *this;
  1988. }
  1989. std::vector<MatcherBase<ArgT> const*> m_matchers;
  1990. };
  1991. template<typename ArgT>
  1992. struct MatchNotOf : MatcherBase<ArgT> {
  1993. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  1994. bool match( ArgT const& arg ) const override {
  1995. return !m_underlyingMatcher.match( arg );
  1996. }
  1997. std::string describe() const override {
  1998. return "not " + m_underlyingMatcher.toString();
  1999. }
  2000. MatcherBase<ArgT> const& m_underlyingMatcher;
  2001. };
  2002. template<typename T>
  2003. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  2004. return MatchAllOf<T>() && *this && other;
  2005. }
  2006. template<typename T>
  2007. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  2008. return MatchAnyOf<T>() || *this || other;
  2009. }
  2010. template<typename T>
  2011. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  2012. return MatchNotOf<T>( *this );
  2013. }
  2014. } // namespace Impl
  2015. } // namespace Matchers
  2016. using namespace Matchers;
  2017. using Matchers::Impl::MatcherBase;
  2018. } // namespace Catch
  2019. // end catch_matchers.h
  2020. // start catch_matchers_floating.h
  2021. #include <type_traits>
  2022. #include <cmath>
  2023. namespace Catch {
  2024. namespace Matchers {
  2025. namespace Floating {
  2026. enum class FloatingPointKind : uint8_t;
  2027. struct WithinAbsMatcher : MatcherBase<double> {
  2028. WithinAbsMatcher(double target, double margin);
  2029. bool match(double const& matchee) const override;
  2030. std::string describe() const override;
  2031. private:
  2032. double m_target;
  2033. double m_margin;
  2034. };
  2035. struct WithinUlpsMatcher : MatcherBase<double> {
  2036. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  2037. bool match(double const& matchee) const override;
  2038. std::string describe() const override;
  2039. private:
  2040. double m_target;
  2041. int m_ulps;
  2042. FloatingPointKind m_type;
  2043. };
  2044. } // namespace Floating
  2045. // The following functions create the actual matcher objects.
  2046. // This allows the types to be inferred
  2047. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  2048. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  2049. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  2050. } // namespace Matchers
  2051. } // namespace Catch
  2052. // end catch_matchers_floating.h
  2053. // start catch_matchers_generic.hpp
  2054. #include <functional>
  2055. #include <string>
  2056. namespace Catch {
  2057. namespace Matchers {
  2058. namespace Generic {
  2059. namespace Detail {
  2060. std::string finalizeDescription(const std::string& desc);
  2061. }
  2062. template <typename T>
  2063. class PredicateMatcher : public MatcherBase<T> {
  2064. std::function<bool(T const&)> m_predicate;
  2065. std::string m_description;
  2066. public:
  2067. PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
  2068. :m_predicate(std::move(elem)),
  2069. m_description(Detail::finalizeDescription(descr))
  2070. {}
  2071. bool match( T const& item ) const override {
  2072. return m_predicate(item);
  2073. }
  2074. std::string describe() const override {
  2075. return m_description;
  2076. }
  2077. };
  2078. } // namespace Generic
  2079. // The following functions create the actual matcher objects.
  2080. // The user has to explicitly specify type to the function, because
  2081. // infering std::function<bool(T const&)> is hard (but possible) and
  2082. // requires a lot of TMP.
  2083. template<typename T>
  2084. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
  2085. return Generic::PredicateMatcher<T>(predicate, description);
  2086. }
  2087. } // namespace Matchers
  2088. } // namespace Catch
  2089. // end catch_matchers_generic.hpp
  2090. // start catch_matchers_string.h
  2091. #include <string>
  2092. namespace Catch {
  2093. namespace Matchers {
  2094. namespace StdString {
  2095. struct CasedString
  2096. {
  2097. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  2098. std::string adjustString( std::string const& str ) const;
  2099. std::string caseSensitivitySuffix() const;
  2100. CaseSensitive::Choice m_caseSensitivity;
  2101. std::string m_str;
  2102. };
  2103. struct StringMatcherBase : MatcherBase<std::string> {
  2104. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  2105. std::string describe() const override;
  2106. CasedString m_comparator;
  2107. std::string m_operation;
  2108. };
  2109. struct EqualsMatcher : StringMatcherBase {
  2110. EqualsMatcher( CasedString const& comparator );
  2111. bool match( std::string const& source ) const override;
  2112. };
  2113. struct ContainsMatcher : StringMatcherBase {
  2114. ContainsMatcher( CasedString const& comparator );
  2115. bool match( std::string const& source ) const override;
  2116. };
  2117. struct StartsWithMatcher : StringMatcherBase {
  2118. StartsWithMatcher( CasedString const& comparator );
  2119. bool match( std::string const& source ) const override;
  2120. };
  2121. struct EndsWithMatcher : StringMatcherBase {
  2122. EndsWithMatcher( CasedString const& comparator );
  2123. bool match( std::string const& source ) const override;
  2124. };
  2125. struct RegexMatcher : MatcherBase<std::string> {
  2126. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  2127. bool match( std::string const& matchee ) const override;
  2128. std::string describe() const override;
  2129. private:
  2130. std::string m_regex;
  2131. CaseSensitive::Choice m_caseSensitivity;
  2132. };
  2133. } // namespace StdString
  2134. // The following functions create the actual matcher objects.
  2135. // This allows the types to be inferred
  2136. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2137. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2138. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2139. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2140. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2141. } // namespace Matchers
  2142. } // namespace Catch
  2143. // end catch_matchers_string.h
  2144. // start catch_matchers_vector.h
  2145. #include <algorithm>
  2146. namespace Catch {
  2147. namespace Matchers {
  2148. namespace Vector {
  2149. namespace Detail {
  2150. template <typename InputIterator, typename T>
  2151. size_t count(InputIterator first, InputIterator last, T const& item) {
  2152. size_t cnt = 0;
  2153. for (; first != last; ++first) {
  2154. if (*first == item) {
  2155. ++cnt;
  2156. }
  2157. }
  2158. return cnt;
  2159. }
  2160. template <typename InputIterator, typename T>
  2161. bool contains(InputIterator first, InputIterator last, T const& item) {
  2162. for (; first != last; ++first) {
  2163. if (*first == item) {
  2164. return true;
  2165. }
  2166. }
  2167. return false;
  2168. }
  2169. }
  2170. template<typename T>
  2171. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  2172. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  2173. bool match(std::vector<T> const &v) const override {
  2174. for (auto const& el : v) {
  2175. if (el == m_comparator) {
  2176. return true;
  2177. }
  2178. }
  2179. return false;
  2180. }
  2181. std::string describe() const override {
  2182. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2183. }
  2184. T const& m_comparator;
  2185. };
  2186. template<typename T>
  2187. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  2188. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2189. bool match(std::vector<T> const &v) const override {
  2190. // !TBD: see note in EqualsMatcher
  2191. if (m_comparator.size() > v.size())
  2192. return false;
  2193. for (auto const& comparator : m_comparator) {
  2194. auto present = false;
  2195. for (const auto& el : v) {
  2196. if (el == comparator) {
  2197. present = true;
  2198. break;
  2199. }
  2200. }
  2201. if (!present) {
  2202. return false;
  2203. }
  2204. }
  2205. return true;
  2206. }
  2207. std::string describe() const override {
  2208. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2209. }
  2210. std::vector<T> const& m_comparator;
  2211. };
  2212. template<typename T>
  2213. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  2214. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2215. bool match(std::vector<T> const &v) const override {
  2216. // !TBD: This currently works if all elements can be compared using !=
  2217. // - a more general approach would be via a compare template that defaults
  2218. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  2219. // - then just call that directly
  2220. if (m_comparator.size() != v.size())
  2221. return false;
  2222. for (std::size_t i = 0; i < v.size(); ++i)
  2223. if (m_comparator[i] != v[i])
  2224. return false;
  2225. return true;
  2226. }
  2227. std::string describe() const override {
  2228. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2229. }
  2230. std::vector<T> const& m_comparator;
  2231. };
  2232. template<typename T>
  2233. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2234. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2235. bool match(std::vector<T> const& vec) const override {
  2236. // Note: This is a reimplementation of std::is_permutation,
  2237. // because I don't want to include <algorithm> inside the common path
  2238. if (m_target.size() != vec.size()) {
  2239. return false;
  2240. }
  2241. auto lfirst = m_target.begin(), llast = m_target.end();
  2242. auto rfirst = vec.begin(), rlast = vec.end();
  2243. // Cut common prefix to optimize checking of permuted parts
  2244. while (lfirst != llast && *lfirst != *rfirst) {
  2245. ++lfirst; ++rfirst;
  2246. }
  2247. if (lfirst == llast) {
  2248. return true;
  2249. }
  2250. for (auto mid = lfirst; mid != llast; ++mid) {
  2251. // Skip already counted items
  2252. if (Detail::contains(lfirst, mid, *mid)) {
  2253. continue;
  2254. }
  2255. size_t num_vec = Detail::count(rfirst, rlast, *mid);
  2256. if (num_vec == 0 || Detail::count(lfirst, llast, *mid) != num_vec) {
  2257. return false;
  2258. }
  2259. }
  2260. return true;
  2261. }
  2262. std::string describe() const override {
  2263. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  2264. }
  2265. private:
  2266. std::vector<T> const& m_target;
  2267. };
  2268. } // namespace Vector
  2269. // The following functions create the actual matcher objects.
  2270. // This allows the types to be inferred
  2271. template<typename T>
  2272. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  2273. return Vector::ContainsMatcher<T>( comparator );
  2274. }
  2275. template<typename T>
  2276. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  2277. return Vector::ContainsElementMatcher<T>( comparator );
  2278. }
  2279. template<typename T>
  2280. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  2281. return Vector::EqualsMatcher<T>( comparator );
  2282. }
  2283. template<typename T>
  2284. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  2285. return Vector::UnorderedEqualsMatcher<T>(target);
  2286. }
  2287. } // namespace Matchers
  2288. } // namespace Catch
  2289. // end catch_matchers_vector.h
  2290. namespace Catch {
  2291. template<typename ArgT, typename MatcherT>
  2292. class MatchExpr : public ITransientExpression {
  2293. ArgT const& m_arg;
  2294. MatcherT m_matcher;
  2295. StringRef m_matcherString;
  2296. public:
  2297. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
  2298. : ITransientExpression{ true, matcher.match( arg ) },
  2299. m_arg( arg ),
  2300. m_matcher( matcher ),
  2301. m_matcherString( matcherString )
  2302. {}
  2303. void streamReconstructedExpression( std::ostream &os ) const override {
  2304. auto matcherAsString = m_matcher.toString();
  2305. os << Catch::Detail::stringify( m_arg ) << ' ';
  2306. if( matcherAsString == Detail::unprintableString )
  2307. os << m_matcherString;
  2308. else
  2309. os << matcherAsString;
  2310. }
  2311. };
  2312. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  2313. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
  2314. template<typename ArgT, typename MatcherT>
  2315. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
  2316. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  2317. }
  2318. } // namespace Catch
  2319. ///////////////////////////////////////////////////////////////////////////////
  2320. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  2321. do { \
  2322. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2323. INTERNAL_CATCH_TRY { \
  2324. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
  2325. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2326. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2327. } while( false )
  2328. ///////////////////////////////////////////////////////////////////////////////
  2329. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  2330. do { \
  2331. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2332. if( catchAssertionHandler.allowThrows() ) \
  2333. try { \
  2334. static_cast<void>(__VA_ARGS__ ); \
  2335. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2336. } \
  2337. catch( exceptionType const& ex ) { \
  2338. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
  2339. } \
  2340. catch( ... ) { \
  2341. catchAssertionHandler.handleUnexpectedInflightException(); \
  2342. } \
  2343. else \
  2344. catchAssertionHandler.handleThrowingCallSkipped(); \
  2345. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2346. } while( false )
  2347. // end catch_capture_matchers.h
  2348. #endif
  2349. // start catch_generators.hpp
  2350. // start catch_interfaces_generatortracker.h
  2351. #include <memory>
  2352. namespace Catch {
  2353. namespace Generators {
  2354. class GeneratorBase {
  2355. protected:
  2356. size_t m_size = 0;
  2357. public:
  2358. GeneratorBase( size_t size ) : m_size( size ) {}
  2359. virtual ~GeneratorBase();
  2360. auto size() const -> size_t { return m_size; }
  2361. };
  2362. using GeneratorBasePtr = std::unique_ptr<GeneratorBase>;
  2363. } // namespace Generators
  2364. struct IGeneratorTracker {
  2365. virtual ~IGeneratorTracker();
  2366. virtual auto hasGenerator() const -> bool = 0;
  2367. virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
  2368. virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
  2369. virtual auto getIndex() const -> std::size_t = 0;
  2370. };
  2371. } // namespace Catch
  2372. // end catch_interfaces_generatortracker.h
  2373. // start catch_enforce.h
  2374. #include <stdexcept>
  2375. namespace Catch {
  2376. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2377. template <typename Ex>
  2378. [[noreturn]]
  2379. void throw_exception(Ex const& e) {
  2380. throw e;
  2381. }
  2382. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  2383. [[noreturn]]
  2384. void throw_exception(std::exception const& e);
  2385. #endif
  2386. } // namespace Catch;
  2387. #define CATCH_PREPARE_EXCEPTION( type, msg ) \
  2388. type( ( Catch::ReusableStringStream() << msg ).str() )
  2389. #define CATCH_INTERNAL_ERROR( msg ) \
  2390. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg))
  2391. #define CATCH_ERROR( msg ) \
  2392. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::domain_error, msg ))
  2393. #define CATCH_RUNTIME_ERROR( msg ) \
  2394. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::runtime_error, msg ))
  2395. #define CATCH_ENFORCE( condition, msg ) \
  2396. do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
  2397. // end catch_enforce.h
  2398. #include <memory>
  2399. #include <vector>
  2400. #include <cassert>
  2401. #include <utility>
  2402. namespace Catch {
  2403. namespace Generators {
  2404. // !TBD move this into its own location?
  2405. namespace pf{
  2406. template<typename T, typename... Args>
  2407. std::unique_ptr<T> make_unique( Args&&... args ) {
  2408. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  2409. }
  2410. }
  2411. template<typename T>
  2412. struct IGenerator {
  2413. virtual ~IGenerator() {}
  2414. virtual auto get( size_t index ) const -> T = 0;
  2415. };
  2416. template<typename T>
  2417. class SingleValueGenerator : public IGenerator<T> {
  2418. T m_value;
  2419. public:
  2420. SingleValueGenerator( T const& value ) : m_value( value ) {}
  2421. auto get( size_t ) const -> T override {
  2422. return m_value;
  2423. }
  2424. };
  2425. template<typename T>
  2426. class FixedValuesGenerator : public IGenerator<T> {
  2427. std::vector<T> m_values;
  2428. public:
  2429. FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
  2430. auto get( size_t index ) const -> T override {
  2431. return m_values[index];
  2432. }
  2433. };
  2434. template<typename T>
  2435. class RangeGenerator : public IGenerator<T> {
  2436. T const m_first;
  2437. T const m_last;
  2438. public:
  2439. RangeGenerator( T const& first, T const& last ) : m_first( first ), m_last( last ) {
  2440. assert( m_last > m_first );
  2441. }
  2442. auto get( size_t index ) const -> T override {
  2443. // ToDo:: introduce a safe cast to catch potential overflows
  2444. return static_cast<T>(m_first+index);
  2445. }
  2446. };
  2447. template<typename T>
  2448. struct NullGenerator : IGenerator<T> {
  2449. auto get( size_t ) const -> T override {
  2450. CATCH_INTERNAL_ERROR("A Null Generator is always empty");
  2451. }
  2452. };
  2453. template<typename T>
  2454. class Generator {
  2455. std::unique_ptr<IGenerator<T>> m_generator;
  2456. size_t m_size;
  2457. public:
  2458. Generator( size_t size, std::unique_ptr<IGenerator<T>> generator )
  2459. : m_generator( std::move( generator ) ),
  2460. m_size( size )
  2461. {}
  2462. auto size() const -> size_t { return m_size; }
  2463. auto operator[]( size_t index ) const -> T {
  2464. assert( index < m_size );
  2465. return m_generator->get( index );
  2466. }
  2467. };
  2468. std::vector<size_t> randomiseIndices( size_t selectionSize, size_t sourceSize );
  2469. template<typename T>
  2470. class GeneratorRandomiser : public IGenerator<T> {
  2471. Generator<T> m_baseGenerator;
  2472. std::vector<size_t> m_indices;
  2473. public:
  2474. GeneratorRandomiser( Generator<T>&& baseGenerator, size_t numberOfItems )
  2475. : m_baseGenerator( std::move( baseGenerator ) ),
  2476. m_indices( randomiseIndices( numberOfItems, m_baseGenerator.size() ) )
  2477. {}
  2478. auto get( size_t index ) const -> T override {
  2479. return m_baseGenerator[m_indices[index]];
  2480. }
  2481. };
  2482. template<typename T>
  2483. struct RequiresASpecialisationFor;
  2484. template<typename T>
  2485. auto all() -> Generator<T> { return RequiresASpecialisationFor<T>(); }
  2486. template<>
  2487. auto all<int>() -> Generator<int>;
  2488. template<typename T>
  2489. auto range( T const& first, T const& last ) -> Generator<T> {
  2490. return Generator<T>( (last-first), pf::make_unique<RangeGenerator<T>>( first, last ) );
  2491. }
  2492. template<typename T>
  2493. auto random( T const& first, T const& last ) -> Generator<T> {
  2494. auto gen = range( first, last );
  2495. auto size = gen.size();
  2496. return Generator<T>( size, pf::make_unique<GeneratorRandomiser<T>>( std::move( gen ), size ) );
  2497. }
  2498. template<typename T>
  2499. auto random( size_t size ) -> Generator<T> {
  2500. return Generator<T>( size, pf::make_unique<GeneratorRandomiser<T>>( all<T>(), size ) );
  2501. }
  2502. template<typename T>
  2503. auto values( std::initializer_list<T> values ) -> Generator<T> {
  2504. return Generator<T>( values.size(), pf::make_unique<FixedValuesGenerator<T>>( values ) );
  2505. }
  2506. template<typename T>
  2507. auto value( T const& val ) -> Generator<T> {
  2508. return Generator<T>( 1, pf::make_unique<SingleValueGenerator<T>>( val ) );
  2509. }
  2510. template<typename T>
  2511. auto as() -> Generator<T> {
  2512. return Generator<T>( 0, pf::make_unique<NullGenerator<T>>() );
  2513. }
  2514. template<typename... Ts>
  2515. auto table( std::initializer_list<std::tuple<Ts...>>&& tuples ) -> Generator<std::tuple<Ts...>> {
  2516. return values<std::tuple<Ts...>>( std::forward<std::initializer_list<std::tuple<Ts...>>>( tuples ) );
  2517. }
  2518. template<typename T>
  2519. struct Generators : GeneratorBase {
  2520. std::vector<Generator<T>> m_generators;
  2521. using type = T;
  2522. Generators() : GeneratorBase( 0 ) {}
  2523. void populate( T&& val ) {
  2524. m_size += 1;
  2525. m_generators.emplace_back( value( std::move( val ) ) );
  2526. }
  2527. template<typename U>
  2528. void populate( U&& val ) {
  2529. populate( T( std::move( val ) ) );
  2530. }
  2531. void populate( Generator<T>&& generator ) {
  2532. m_size += generator.size();
  2533. m_generators.emplace_back( std::move( generator ) );
  2534. }
  2535. template<typename U, typename... Gs>
  2536. void populate( U&& valueOrGenerator, Gs... moreGenerators ) {
  2537. populate( std::forward<U>( valueOrGenerator ) );
  2538. populate( std::forward<Gs>( moreGenerators )... );
  2539. }
  2540. auto operator[]( size_t index ) const -> T {
  2541. size_t sizes = 0;
  2542. for( auto const& gen : m_generators ) {
  2543. auto localIndex = index-sizes;
  2544. sizes += gen.size();
  2545. if( index < sizes )
  2546. return gen[localIndex];
  2547. }
  2548. CATCH_INTERNAL_ERROR("Index '" << index << "' is out of range (" << sizes << ')');
  2549. }
  2550. };
  2551. template<typename T, typename... Gs>
  2552. auto makeGenerators( Generator<T>&& generator, Gs... moreGenerators ) -> Generators<T> {
  2553. Generators<T> generators;
  2554. generators.m_generators.reserve( 1+sizeof...(Gs) );
  2555. generators.populate( std::move( generator ), std::forward<Gs>( moreGenerators )... );
  2556. return generators;
  2557. }
  2558. template<typename T>
  2559. auto makeGenerators( Generator<T>&& generator ) -> Generators<T> {
  2560. Generators<T> generators;
  2561. generators.populate( std::move( generator ) );
  2562. return generators;
  2563. }
  2564. template<typename T, typename... Gs>
  2565. auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators<T> {
  2566. return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
  2567. }
  2568. template<typename T, typename U, typename... Gs>
  2569. auto makeGenerators( U&& val, Gs... moreGenerators ) -> Generators<T> {
  2570. return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
  2571. }
  2572. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
  2573. template<typename L>
  2574. // Note: The type after -> is weird, because VS2015 cannot parse
  2575. // the expression used in the typedef inside, when it is in
  2576. // return type. Yeah, ¯\_(ツ)_/¯
  2577. auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>()[0]) {
  2578. using UnderlyingType = typename decltype(generatorExpression())::type;
  2579. IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo );
  2580. if( !tracker.hasGenerator() )
  2581. tracker.setGenerator( pf::make_unique<Generators<UnderlyingType>>( generatorExpression() ) );
  2582. auto const& generator = static_cast<Generators<UnderlyingType> const&>( *tracker.getGenerator() );
  2583. return generator[tracker.getIndex()];
  2584. }
  2585. } // namespace Generators
  2586. } // namespace Catch
  2587. #define GENERATE( ... ) \
  2588. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, []{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  2589. // end catch_generators.hpp
  2590. // These files are included here so the single_include script doesn't put them
  2591. // in the conditionally compiled sections
  2592. // start catch_test_case_info.h
  2593. #include <string>
  2594. #include <vector>
  2595. #include <memory>
  2596. #ifdef __clang__
  2597. #pragma clang diagnostic push
  2598. #pragma clang diagnostic ignored "-Wpadded"
  2599. #endif
  2600. namespace Catch {
  2601. struct ITestInvoker;
  2602. struct TestCaseInfo {
  2603. enum SpecialProperties{
  2604. None = 0,
  2605. IsHidden = 1 << 1,
  2606. ShouldFail = 1 << 2,
  2607. MayFail = 1 << 3,
  2608. Throws = 1 << 4,
  2609. NonPortable = 1 << 5,
  2610. Benchmark = 1 << 6
  2611. };
  2612. TestCaseInfo( std::string const& _name,
  2613. std::string const& _className,
  2614. std::string const& _description,
  2615. std::vector<std::string> const& _tags,
  2616. SourceLineInfo const& _lineInfo );
  2617. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  2618. bool isHidden() const;
  2619. bool throws() const;
  2620. bool okToFail() const;
  2621. bool expectedToFail() const;
  2622. std::string tagsAsString() const;
  2623. std::string name;
  2624. std::string className;
  2625. std::string description;
  2626. std::vector<std::string> tags;
  2627. std::vector<std::string> lcaseTags;
  2628. SourceLineInfo lineInfo;
  2629. SpecialProperties properties;
  2630. };
  2631. class TestCase : public TestCaseInfo {
  2632. public:
  2633. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  2634. TestCase withName( std::string const& _newName ) const;
  2635. void invoke() const;
  2636. TestCaseInfo const& getTestCaseInfo() const;
  2637. bool operator == ( TestCase const& other ) const;
  2638. bool operator < ( TestCase const& other ) const;
  2639. private:
  2640. std::shared_ptr<ITestInvoker> test;
  2641. };
  2642. TestCase makeTestCase( ITestInvoker* testCase,
  2643. std::string const& className,
  2644. NameAndTags const& nameAndTags,
  2645. SourceLineInfo const& lineInfo );
  2646. }
  2647. #ifdef __clang__
  2648. #pragma clang diagnostic pop
  2649. #endif
  2650. // end catch_test_case_info.h
  2651. // start catch_interfaces_runner.h
  2652. namespace Catch {
  2653. struct IRunner {
  2654. virtual ~IRunner();
  2655. virtual bool aborting() const = 0;
  2656. };
  2657. }
  2658. // end catch_interfaces_runner.h
  2659. #ifdef __OBJC__
  2660. // start catch_objc.hpp
  2661. #import <objc/runtime.h>
  2662. #include <string>
  2663. // NB. Any general catch headers included here must be included
  2664. // in catch.hpp first to make sure they are included by the single
  2665. // header for non obj-usage
  2666. ///////////////////////////////////////////////////////////////////////////////
  2667. // This protocol is really only here for (self) documenting purposes, since
  2668. // all its methods are optional.
  2669. @protocol OcFixture
  2670. @optional
  2671. -(void) setUp;
  2672. -(void) tearDown;
  2673. @end
  2674. namespace Catch {
  2675. class OcMethod : public ITestInvoker {
  2676. public:
  2677. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  2678. virtual void invoke() const {
  2679. id obj = [[m_cls alloc] init];
  2680. performOptionalSelector( obj, @selector(setUp) );
  2681. performOptionalSelector( obj, m_sel );
  2682. performOptionalSelector( obj, @selector(tearDown) );
  2683. arcSafeRelease( obj );
  2684. }
  2685. private:
  2686. virtual ~OcMethod() {}
  2687. Class m_cls;
  2688. SEL m_sel;
  2689. };
  2690. namespace Detail{
  2691. inline std::string getAnnotation( Class cls,
  2692. std::string const& annotationName,
  2693. std::string const& testCaseName ) {
  2694. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  2695. SEL sel = NSSelectorFromString( selStr );
  2696. arcSafeRelease( selStr );
  2697. id value = performOptionalSelector( cls, sel );
  2698. if( value )
  2699. return [(NSString*)value UTF8String];
  2700. return "";
  2701. }
  2702. }
  2703. inline std::size_t registerTestMethods() {
  2704. std::size_t noTestMethods = 0;
  2705. int noClasses = objc_getClassList( nullptr, 0 );
  2706. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  2707. objc_getClassList( classes, noClasses );
  2708. for( int c = 0; c < noClasses; c++ ) {
  2709. Class cls = classes[c];
  2710. {
  2711. u_int count;
  2712. Method* methods = class_copyMethodList( cls, &count );
  2713. for( u_int m = 0; m < count ; m++ ) {
  2714. SEL selector = method_getName(methods[m]);
  2715. std::string methodName = sel_getName(selector);
  2716. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  2717. std::string testCaseName = methodName.substr( 15 );
  2718. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  2719. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  2720. const char* className = class_getName( cls );
  2721. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
  2722. noTestMethods++;
  2723. }
  2724. }
  2725. free(methods);
  2726. }
  2727. }
  2728. return noTestMethods;
  2729. }
  2730. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  2731. namespace Matchers {
  2732. namespace Impl {
  2733. namespace NSStringMatchers {
  2734. struct StringHolder : MatcherBase<NSString*>{
  2735. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  2736. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  2737. StringHolder() {
  2738. arcSafeRelease( m_substr );
  2739. }
  2740. bool match( NSString* arg ) const override {
  2741. return false;
  2742. }
  2743. NSString* CATCH_ARC_STRONG m_substr;
  2744. };
  2745. struct Equals : StringHolder {
  2746. Equals( NSString* substr ) : StringHolder( substr ){}
  2747. bool match( NSString* str ) const override {
  2748. return (str != nil || m_substr == nil ) &&
  2749. [str isEqualToString:m_substr];
  2750. }
  2751. std::string describe() const override {
  2752. return "equals string: " + Catch::Detail::stringify( m_substr );
  2753. }
  2754. };
  2755. struct Contains : StringHolder {
  2756. Contains( NSString* substr ) : StringHolder( substr ){}
  2757. bool match( NSString* str ) const {
  2758. return (str != nil || m_substr == nil ) &&
  2759. [str rangeOfString:m_substr].location != NSNotFound;
  2760. }
  2761. std::string describe() const override {
  2762. return "contains string: " + Catch::Detail::stringify( m_substr );
  2763. }
  2764. };
  2765. struct StartsWith : StringHolder {
  2766. StartsWith( NSString* substr ) : StringHolder( substr ){}
  2767. bool match( NSString* str ) const override {
  2768. return (str != nil || m_substr == nil ) &&
  2769. [str rangeOfString:m_substr].location == 0;
  2770. }
  2771. std::string describe() const override {
  2772. return "starts with: " + Catch::Detail::stringify( m_substr );
  2773. }
  2774. };
  2775. struct EndsWith : StringHolder {
  2776. EndsWith( NSString* substr ) : StringHolder( substr ){}
  2777. bool match( NSString* str ) const override {
  2778. return (str != nil || m_substr == nil ) &&
  2779. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  2780. }
  2781. std::string describe() const override {
  2782. return "ends with: " + Catch::Detail::stringify( m_substr );
  2783. }
  2784. };
  2785. } // namespace NSStringMatchers
  2786. } // namespace Impl
  2787. inline Impl::NSStringMatchers::Equals
  2788. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  2789. inline Impl::NSStringMatchers::Contains
  2790. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  2791. inline Impl::NSStringMatchers::StartsWith
  2792. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  2793. inline Impl::NSStringMatchers::EndsWith
  2794. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  2795. } // namespace Matchers
  2796. using namespace Matchers;
  2797. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  2798. } // namespace Catch
  2799. ///////////////////////////////////////////////////////////////////////////////
  2800. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  2801. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  2802. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  2803. { \
  2804. return @ name; \
  2805. } \
  2806. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  2807. { \
  2808. return @ desc; \
  2809. } \
  2810. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  2811. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  2812. // end catch_objc.hpp
  2813. #endif
  2814. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  2815. // start catch_external_interfaces.h
  2816. // start catch_reporter_bases.hpp
  2817. // start catch_interfaces_reporter.h
  2818. // start catch_config.hpp
  2819. // start catch_test_spec_parser.h
  2820. #ifdef __clang__
  2821. #pragma clang diagnostic push
  2822. #pragma clang diagnostic ignored "-Wpadded"
  2823. #endif
  2824. // start catch_test_spec.h
  2825. #ifdef __clang__
  2826. #pragma clang diagnostic push
  2827. #pragma clang diagnostic ignored "-Wpadded"
  2828. #endif
  2829. // start catch_wildcard_pattern.h
  2830. namespace Catch
  2831. {
  2832. class WildcardPattern {
  2833. enum WildcardPosition {
  2834. NoWildcard = 0,
  2835. WildcardAtStart = 1,
  2836. WildcardAtEnd = 2,
  2837. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  2838. };
  2839. public:
  2840. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  2841. virtual ~WildcardPattern() = default;
  2842. virtual bool matches( std::string const& str ) const;
  2843. private:
  2844. std::string adjustCase( std::string const& str ) const;
  2845. CaseSensitive::Choice m_caseSensitivity;
  2846. WildcardPosition m_wildcard = NoWildcard;
  2847. std::string m_pattern;
  2848. };
  2849. }
  2850. // end catch_wildcard_pattern.h
  2851. #include <string>
  2852. #include <vector>
  2853. #include <memory>
  2854. namespace Catch {
  2855. class TestSpec {
  2856. struct Pattern {
  2857. virtual ~Pattern();
  2858. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  2859. };
  2860. using PatternPtr = std::shared_ptr<Pattern>;
  2861. class NamePattern : public Pattern {
  2862. public:
  2863. NamePattern( std::string const& name );
  2864. virtual ~NamePattern();
  2865. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2866. private:
  2867. WildcardPattern m_wildcardPattern;
  2868. };
  2869. class TagPattern : public Pattern {
  2870. public:
  2871. TagPattern( std::string const& tag );
  2872. virtual ~TagPattern();
  2873. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2874. private:
  2875. std::string m_tag;
  2876. };
  2877. class ExcludedPattern : public Pattern {
  2878. public:
  2879. ExcludedPattern( PatternPtr const& underlyingPattern );
  2880. virtual ~ExcludedPattern();
  2881. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2882. private:
  2883. PatternPtr m_underlyingPattern;
  2884. };
  2885. struct Filter {
  2886. std::vector<PatternPtr> m_patterns;
  2887. bool matches( TestCaseInfo const& testCase ) const;
  2888. };
  2889. public:
  2890. bool hasFilters() const;
  2891. bool matches( TestCaseInfo const& testCase ) const;
  2892. private:
  2893. std::vector<Filter> m_filters;
  2894. friend class TestSpecParser;
  2895. };
  2896. }
  2897. #ifdef __clang__
  2898. #pragma clang diagnostic pop
  2899. #endif
  2900. // end catch_test_spec.h
  2901. // start catch_interfaces_tag_alias_registry.h
  2902. #include <string>
  2903. namespace Catch {
  2904. struct TagAlias;
  2905. struct ITagAliasRegistry {
  2906. virtual ~ITagAliasRegistry();
  2907. // Nullptr if not present
  2908. virtual TagAlias const* find( std::string const& alias ) const = 0;
  2909. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  2910. static ITagAliasRegistry const& get();
  2911. };
  2912. } // end namespace Catch
  2913. // end catch_interfaces_tag_alias_registry.h
  2914. namespace Catch {
  2915. class TestSpecParser {
  2916. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  2917. Mode m_mode = None;
  2918. bool m_exclusion = false;
  2919. std::size_t m_start = std::string::npos, m_pos = 0;
  2920. std::string m_arg;
  2921. std::vector<std::size_t> m_escapeChars;
  2922. TestSpec::Filter m_currentFilter;
  2923. TestSpec m_testSpec;
  2924. ITagAliasRegistry const* m_tagAliases = nullptr;
  2925. public:
  2926. TestSpecParser( ITagAliasRegistry const& tagAliases );
  2927. TestSpecParser& parse( std::string const& arg );
  2928. TestSpec testSpec();
  2929. private:
  2930. void visitChar( char c );
  2931. void startNewMode( Mode mode, std::size_t start );
  2932. void escape();
  2933. std::string subString() const;
  2934. template<typename T>
  2935. void addPattern() {
  2936. std::string token = subString();
  2937. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  2938. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  2939. m_escapeChars.clear();
  2940. if( startsWith( token, "exclude:" ) ) {
  2941. m_exclusion = true;
  2942. token = token.substr( 8 );
  2943. }
  2944. if( !token.empty() ) {
  2945. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  2946. if( m_exclusion )
  2947. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  2948. m_currentFilter.m_patterns.push_back( pattern );
  2949. }
  2950. m_exclusion = false;
  2951. m_mode = None;
  2952. }
  2953. void addFilter();
  2954. };
  2955. TestSpec parseTestSpec( std::string const& arg );
  2956. } // namespace Catch
  2957. #ifdef __clang__
  2958. #pragma clang diagnostic pop
  2959. #endif
  2960. // end catch_test_spec_parser.h
  2961. // start catch_interfaces_config.h
  2962. #include <iosfwd>
  2963. #include <string>
  2964. #include <vector>
  2965. #include <memory>
  2966. namespace Catch {
  2967. enum class Verbosity {
  2968. Quiet = 0,
  2969. Normal,
  2970. High
  2971. };
  2972. struct WarnAbout { enum What {
  2973. Nothing = 0x00,
  2974. NoAssertions = 0x01,
  2975. NoTests = 0x02
  2976. }; };
  2977. struct ShowDurations { enum OrNot {
  2978. DefaultForReporter,
  2979. Always,
  2980. Never
  2981. }; };
  2982. struct RunTests { enum InWhatOrder {
  2983. InDeclarationOrder,
  2984. InLexicographicalOrder,
  2985. InRandomOrder
  2986. }; };
  2987. struct UseColour { enum YesOrNo {
  2988. Auto,
  2989. Yes,
  2990. No
  2991. }; };
  2992. struct WaitForKeypress { enum When {
  2993. Never,
  2994. BeforeStart = 1,
  2995. BeforeExit = 2,
  2996. BeforeStartAndExit = BeforeStart | BeforeExit
  2997. }; };
  2998. class TestSpec;
  2999. struct IConfig : NonCopyable {
  3000. virtual ~IConfig();
  3001. virtual bool allowThrows() const = 0;
  3002. virtual std::ostream& stream() const = 0;
  3003. virtual std::string name() const = 0;
  3004. virtual bool includeSuccessfulResults() const = 0;
  3005. virtual bool shouldDebugBreak() const = 0;
  3006. virtual bool warnAboutMissingAssertions() const = 0;
  3007. virtual bool warnAboutNoTests() const = 0;
  3008. virtual int abortAfter() const = 0;
  3009. virtual bool showInvisibles() const = 0;
  3010. virtual ShowDurations::OrNot showDurations() const = 0;
  3011. virtual TestSpec const& testSpec() const = 0;
  3012. virtual bool hasTestFilters() const = 0;
  3013. virtual RunTests::InWhatOrder runOrder() const = 0;
  3014. virtual unsigned int rngSeed() const = 0;
  3015. virtual int benchmarkResolutionMultiple() const = 0;
  3016. virtual UseColour::YesOrNo useColour() const = 0;
  3017. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  3018. virtual Verbosity verbosity() const = 0;
  3019. };
  3020. using IConfigPtr = std::shared_ptr<IConfig const>;
  3021. }
  3022. // end catch_interfaces_config.h
  3023. // Libstdc++ doesn't like incomplete classes for unique_ptr
  3024. #include <memory>
  3025. #include <vector>
  3026. #include <string>
  3027. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  3028. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  3029. #endif
  3030. namespace Catch {
  3031. struct IStream;
  3032. struct ConfigData {
  3033. bool listTests = false;
  3034. bool listTags = false;
  3035. bool listReporters = false;
  3036. bool listTestNamesOnly = false;
  3037. bool showSuccessfulTests = false;
  3038. bool shouldDebugBreak = false;
  3039. bool noThrow = false;
  3040. bool showHelp = false;
  3041. bool showInvisibles = false;
  3042. bool filenamesAsTags = false;
  3043. bool libIdentify = false;
  3044. int abortAfter = -1;
  3045. unsigned int rngSeed = 0;
  3046. int benchmarkResolutionMultiple = 100;
  3047. Verbosity verbosity = Verbosity::Normal;
  3048. WarnAbout::What warnings = WarnAbout::Nothing;
  3049. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  3050. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  3051. UseColour::YesOrNo useColour = UseColour::Auto;
  3052. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  3053. std::string outputFilename;
  3054. std::string name;
  3055. std::string processName;
  3056. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  3057. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  3058. #endif
  3059. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  3060. #undef CATCH_CONFIG_DEFAULT_REPORTER
  3061. std::vector<std::string> testsOrTags;
  3062. std::vector<std::string> sectionsToRun;
  3063. };
  3064. class Config : public IConfig {
  3065. public:
  3066. Config() = default;
  3067. Config( ConfigData const& data );
  3068. virtual ~Config() = default;
  3069. std::string const& getFilename() const;
  3070. bool listTests() const;
  3071. bool listTestNamesOnly() const;
  3072. bool listTags() const;
  3073. bool listReporters() const;
  3074. std::string getProcessName() const;
  3075. std::string const& getReporterName() const;
  3076. std::vector<std::string> const& getTestsOrTags() const;
  3077. std::vector<std::string> const& getSectionsToRun() const override;
  3078. virtual TestSpec const& testSpec() const override;
  3079. bool hasTestFilters() const override;
  3080. bool showHelp() const;
  3081. // IConfig interface
  3082. bool allowThrows() const override;
  3083. std::ostream& stream() const override;
  3084. std::string name() const override;
  3085. bool includeSuccessfulResults() const override;
  3086. bool warnAboutMissingAssertions() const override;
  3087. bool warnAboutNoTests() const override;
  3088. ShowDurations::OrNot showDurations() const override;
  3089. RunTests::InWhatOrder runOrder() const override;
  3090. unsigned int rngSeed() const override;
  3091. int benchmarkResolutionMultiple() const override;
  3092. UseColour::YesOrNo useColour() const override;
  3093. bool shouldDebugBreak() const override;
  3094. int abortAfter() const override;
  3095. bool showInvisibles() const override;
  3096. Verbosity verbosity() const override;
  3097. private:
  3098. IStream const* openStream();
  3099. ConfigData m_data;
  3100. std::unique_ptr<IStream const> m_stream;
  3101. TestSpec m_testSpec;
  3102. bool m_hasTestFilters = false;
  3103. };
  3104. } // end namespace Catch
  3105. // end catch_config.hpp
  3106. // start catch_assertionresult.h
  3107. #include <string>
  3108. namespace Catch {
  3109. struct AssertionResultData
  3110. {
  3111. AssertionResultData() = delete;
  3112. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  3113. std::string message;
  3114. mutable std::string reconstructedExpression;
  3115. LazyExpression lazyExpression;
  3116. ResultWas::OfType resultType;
  3117. std::string reconstructExpression() const;
  3118. };
  3119. class AssertionResult {
  3120. public:
  3121. AssertionResult() = delete;
  3122. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  3123. bool isOk() const;
  3124. bool succeeded() const;
  3125. ResultWas::OfType getResultType() const;
  3126. bool hasExpression() const;
  3127. bool hasMessage() const;
  3128. std::string getExpression() const;
  3129. std::string getExpressionInMacro() const;
  3130. bool hasExpandedExpression() const;
  3131. std::string getExpandedExpression() const;
  3132. std::string getMessage() const;
  3133. SourceLineInfo getSourceInfo() const;
  3134. StringRef getTestMacroName() const;
  3135. //protected:
  3136. AssertionInfo m_info;
  3137. AssertionResultData m_resultData;
  3138. };
  3139. } // end namespace Catch
  3140. // end catch_assertionresult.h
  3141. // start catch_option.hpp
  3142. namespace Catch {
  3143. // An optional type
  3144. template<typename T>
  3145. class Option {
  3146. public:
  3147. Option() : nullableValue( nullptr ) {}
  3148. Option( T const& _value )
  3149. : nullableValue( new( storage ) T( _value ) )
  3150. {}
  3151. Option( Option const& _other )
  3152. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  3153. {}
  3154. ~Option() {
  3155. reset();
  3156. }
  3157. Option& operator= ( Option const& _other ) {
  3158. if( &_other != this ) {
  3159. reset();
  3160. if( _other )
  3161. nullableValue = new( storage ) T( *_other );
  3162. }
  3163. return *this;
  3164. }
  3165. Option& operator = ( T const& _value ) {
  3166. reset();
  3167. nullableValue = new( storage ) T( _value );
  3168. return *this;
  3169. }
  3170. void reset() {
  3171. if( nullableValue )
  3172. nullableValue->~T();
  3173. nullableValue = nullptr;
  3174. }
  3175. T& operator*() { return *nullableValue; }
  3176. T const& operator*() const { return *nullableValue; }
  3177. T* operator->() { return nullableValue; }
  3178. const T* operator->() const { return nullableValue; }
  3179. T valueOr( T const& defaultValue ) const {
  3180. return nullableValue ? *nullableValue : defaultValue;
  3181. }
  3182. bool some() const { return nullableValue != nullptr; }
  3183. bool none() const { return nullableValue == nullptr; }
  3184. bool operator !() const { return nullableValue == nullptr; }
  3185. explicit operator bool() const {
  3186. return some();
  3187. }
  3188. private:
  3189. T *nullableValue;
  3190. alignas(alignof(T)) char storage[sizeof(T)];
  3191. };
  3192. } // end namespace Catch
  3193. // end catch_option.hpp
  3194. #include <string>
  3195. #include <iosfwd>
  3196. #include <map>
  3197. #include <set>
  3198. #include <memory>
  3199. namespace Catch {
  3200. struct ReporterConfig {
  3201. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  3202. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  3203. std::ostream& stream() const;
  3204. IConfigPtr fullConfig() const;
  3205. private:
  3206. std::ostream* m_stream;
  3207. IConfigPtr m_fullConfig;
  3208. };
  3209. struct ReporterPreferences {
  3210. bool shouldRedirectStdOut = false;
  3211. bool shouldReportAllAssertions = false;
  3212. };
  3213. template<typename T>
  3214. struct LazyStat : Option<T> {
  3215. LazyStat& operator=( T const& _value ) {
  3216. Option<T>::operator=( _value );
  3217. used = false;
  3218. return *this;
  3219. }
  3220. void reset() {
  3221. Option<T>::reset();
  3222. used = false;
  3223. }
  3224. bool used = false;
  3225. };
  3226. struct TestRunInfo {
  3227. TestRunInfo( std::string const& _name );
  3228. std::string name;
  3229. };
  3230. struct GroupInfo {
  3231. GroupInfo( std::string const& _name,
  3232. std::size_t _groupIndex,
  3233. std::size_t _groupsCount );
  3234. std::string name;
  3235. std::size_t groupIndex;
  3236. std::size_t groupsCounts;
  3237. };
  3238. struct AssertionStats {
  3239. AssertionStats( AssertionResult const& _assertionResult,
  3240. std::vector<MessageInfo> const& _infoMessages,
  3241. Totals const& _totals );
  3242. AssertionStats( AssertionStats const& ) = default;
  3243. AssertionStats( AssertionStats && ) = default;
  3244. AssertionStats& operator = ( AssertionStats const& ) = default;
  3245. AssertionStats& operator = ( AssertionStats && ) = default;
  3246. virtual ~AssertionStats();
  3247. AssertionResult assertionResult;
  3248. std::vector<MessageInfo> infoMessages;
  3249. Totals totals;
  3250. };
  3251. struct SectionStats {
  3252. SectionStats( SectionInfo const& _sectionInfo,
  3253. Counts const& _assertions,
  3254. double _durationInSeconds,
  3255. bool _missingAssertions );
  3256. SectionStats( SectionStats const& ) = default;
  3257. SectionStats( SectionStats && ) = default;
  3258. SectionStats& operator = ( SectionStats const& ) = default;
  3259. SectionStats& operator = ( SectionStats && ) = default;
  3260. virtual ~SectionStats();
  3261. SectionInfo sectionInfo;
  3262. Counts assertions;
  3263. double durationInSeconds;
  3264. bool missingAssertions;
  3265. };
  3266. struct TestCaseStats {
  3267. TestCaseStats( TestCaseInfo const& _testInfo,
  3268. Totals const& _totals,
  3269. std::string const& _stdOut,
  3270. std::string const& _stdErr,
  3271. bool _aborting );
  3272. TestCaseStats( TestCaseStats const& ) = default;
  3273. TestCaseStats( TestCaseStats && ) = default;
  3274. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  3275. TestCaseStats& operator = ( TestCaseStats && ) = default;
  3276. virtual ~TestCaseStats();
  3277. TestCaseInfo testInfo;
  3278. Totals totals;
  3279. std::string stdOut;
  3280. std::string stdErr;
  3281. bool aborting;
  3282. };
  3283. struct TestGroupStats {
  3284. TestGroupStats( GroupInfo const& _groupInfo,
  3285. Totals const& _totals,
  3286. bool _aborting );
  3287. TestGroupStats( GroupInfo const& _groupInfo );
  3288. TestGroupStats( TestGroupStats const& ) = default;
  3289. TestGroupStats( TestGroupStats && ) = default;
  3290. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  3291. TestGroupStats& operator = ( TestGroupStats && ) = default;
  3292. virtual ~TestGroupStats();
  3293. GroupInfo groupInfo;
  3294. Totals totals;
  3295. bool aborting;
  3296. };
  3297. struct TestRunStats {
  3298. TestRunStats( TestRunInfo const& _runInfo,
  3299. Totals const& _totals,
  3300. bool _aborting );
  3301. TestRunStats( TestRunStats const& ) = default;
  3302. TestRunStats( TestRunStats && ) = default;
  3303. TestRunStats& operator = ( TestRunStats const& ) = default;
  3304. TestRunStats& operator = ( TestRunStats && ) = default;
  3305. virtual ~TestRunStats();
  3306. TestRunInfo runInfo;
  3307. Totals totals;
  3308. bool aborting;
  3309. };
  3310. struct BenchmarkInfo {
  3311. std::string name;
  3312. };
  3313. struct BenchmarkStats {
  3314. BenchmarkInfo info;
  3315. std::size_t iterations;
  3316. uint64_t elapsedTimeInNanoseconds;
  3317. };
  3318. struct IStreamingReporter {
  3319. virtual ~IStreamingReporter() = default;
  3320. // Implementing class must also provide the following static methods:
  3321. // static std::string getDescription();
  3322. // static std::set<Verbosity> getSupportedVerbosities()
  3323. virtual ReporterPreferences getPreferences() const = 0;
  3324. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  3325. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  3326. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  3327. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  3328. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  3329. // *** experimental ***
  3330. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  3331. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  3332. // The return value indicates if the messages buffer should be cleared:
  3333. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  3334. // *** experimental ***
  3335. virtual void benchmarkEnded( BenchmarkStats const& ) {}
  3336. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  3337. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  3338. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  3339. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  3340. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  3341. // Default empty implementation provided
  3342. virtual void fatalErrorEncountered( StringRef name );
  3343. virtual bool isMulti() const;
  3344. };
  3345. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  3346. struct IReporterFactory {
  3347. virtual ~IReporterFactory();
  3348. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  3349. virtual std::string getDescription() const = 0;
  3350. };
  3351. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  3352. struct IReporterRegistry {
  3353. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  3354. using Listeners = std::vector<IReporterFactoryPtr>;
  3355. virtual ~IReporterRegistry();
  3356. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  3357. virtual FactoryMap const& getFactories() const = 0;
  3358. virtual Listeners const& getListeners() const = 0;
  3359. };
  3360. } // end namespace Catch
  3361. // end catch_interfaces_reporter.h
  3362. #include <algorithm>
  3363. #include <cstring>
  3364. #include <cfloat>
  3365. #include <cstdio>
  3366. #include <cassert>
  3367. #include <memory>
  3368. #include <ostream>
  3369. namespace Catch {
  3370. void prepareExpandedExpression(AssertionResult& result);
  3371. // Returns double formatted as %.3f (format expected on output)
  3372. std::string getFormattedDuration( double duration );
  3373. template<typename DerivedT>
  3374. struct StreamingReporterBase : IStreamingReporter {
  3375. StreamingReporterBase( ReporterConfig const& _config )
  3376. : m_config( _config.fullConfig() ),
  3377. stream( _config.stream() )
  3378. {
  3379. m_reporterPrefs.shouldRedirectStdOut = false;
  3380. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3381. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  3382. }
  3383. ReporterPreferences getPreferences() const override {
  3384. return m_reporterPrefs;
  3385. }
  3386. static std::set<Verbosity> getSupportedVerbosities() {
  3387. return { Verbosity::Normal };
  3388. }
  3389. ~StreamingReporterBase() override = default;
  3390. void noMatchingTestCases(std::string const&) override {}
  3391. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  3392. currentTestRunInfo = _testRunInfo;
  3393. }
  3394. void testGroupStarting(GroupInfo const& _groupInfo) override {
  3395. currentGroupInfo = _groupInfo;
  3396. }
  3397. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  3398. currentTestCaseInfo = _testInfo;
  3399. }
  3400. void sectionStarting(SectionInfo const& _sectionInfo) override {
  3401. m_sectionStack.push_back(_sectionInfo);
  3402. }
  3403. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  3404. m_sectionStack.pop_back();
  3405. }
  3406. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  3407. currentTestCaseInfo.reset();
  3408. }
  3409. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  3410. currentGroupInfo.reset();
  3411. }
  3412. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  3413. currentTestCaseInfo.reset();
  3414. currentGroupInfo.reset();
  3415. currentTestRunInfo.reset();
  3416. }
  3417. void skipTest(TestCaseInfo const&) override {
  3418. // Don't do anything with this by default.
  3419. // It can optionally be overridden in the derived class.
  3420. }
  3421. IConfigPtr m_config;
  3422. std::ostream& stream;
  3423. LazyStat<TestRunInfo> currentTestRunInfo;
  3424. LazyStat<GroupInfo> currentGroupInfo;
  3425. LazyStat<TestCaseInfo> currentTestCaseInfo;
  3426. std::vector<SectionInfo> m_sectionStack;
  3427. ReporterPreferences m_reporterPrefs;
  3428. };
  3429. template<typename DerivedT>
  3430. struct CumulativeReporterBase : IStreamingReporter {
  3431. template<typename T, typename ChildNodeT>
  3432. struct Node {
  3433. explicit Node( T const& _value ) : value( _value ) {}
  3434. virtual ~Node() {}
  3435. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  3436. T value;
  3437. ChildNodes children;
  3438. };
  3439. struct SectionNode {
  3440. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  3441. virtual ~SectionNode() = default;
  3442. bool operator == (SectionNode const& other) const {
  3443. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  3444. }
  3445. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  3446. return operator==(*other);
  3447. }
  3448. SectionStats stats;
  3449. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  3450. using Assertions = std::vector<AssertionStats>;
  3451. ChildSections childSections;
  3452. Assertions assertions;
  3453. std::string stdOut;
  3454. std::string stdErr;
  3455. };
  3456. struct BySectionInfo {
  3457. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  3458. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  3459. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  3460. return ((node->stats.sectionInfo.name == m_other.name) &&
  3461. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  3462. }
  3463. void operator=(BySectionInfo const&) = delete;
  3464. private:
  3465. SectionInfo const& m_other;
  3466. };
  3467. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  3468. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  3469. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  3470. CumulativeReporterBase( ReporterConfig const& _config )
  3471. : m_config( _config.fullConfig() ),
  3472. stream( _config.stream() )
  3473. {
  3474. m_reporterPrefs.shouldRedirectStdOut = false;
  3475. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3476. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  3477. }
  3478. ~CumulativeReporterBase() override = default;
  3479. ReporterPreferences getPreferences() const override {
  3480. return m_reporterPrefs;
  3481. }
  3482. static std::set<Verbosity> getSupportedVerbosities() {
  3483. return { Verbosity::Normal };
  3484. }
  3485. void testRunStarting( TestRunInfo const& ) override {}
  3486. void testGroupStarting( GroupInfo const& ) override {}
  3487. void testCaseStarting( TestCaseInfo const& ) override {}
  3488. void sectionStarting( SectionInfo const& sectionInfo ) override {
  3489. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  3490. std::shared_ptr<SectionNode> node;
  3491. if( m_sectionStack.empty() ) {
  3492. if( !m_rootSection )
  3493. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  3494. node = m_rootSection;
  3495. }
  3496. else {
  3497. SectionNode& parentNode = *m_sectionStack.back();
  3498. auto it =
  3499. std::find_if( parentNode.childSections.begin(),
  3500. parentNode.childSections.end(),
  3501. BySectionInfo( sectionInfo ) );
  3502. if( it == parentNode.childSections.end() ) {
  3503. node = std::make_shared<SectionNode>( incompleteStats );
  3504. parentNode.childSections.push_back( node );
  3505. }
  3506. else
  3507. node = *it;
  3508. }
  3509. m_sectionStack.push_back( node );
  3510. m_deepestSection = std::move(node);
  3511. }
  3512. void assertionStarting(AssertionInfo const&) override {}
  3513. bool assertionEnded(AssertionStats const& assertionStats) override {
  3514. assert(!m_sectionStack.empty());
  3515. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  3516. // which getExpandedExpression() calls to build the expression string.
  3517. // Our section stack copy of the assertionResult will likely outlive the
  3518. // temporary, so it must be expanded or discarded now to avoid calling
  3519. // a destroyed object later.
  3520. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  3521. SectionNode& sectionNode = *m_sectionStack.back();
  3522. sectionNode.assertions.push_back(assertionStats);
  3523. return true;
  3524. }
  3525. void sectionEnded(SectionStats const& sectionStats) override {
  3526. assert(!m_sectionStack.empty());
  3527. SectionNode& node = *m_sectionStack.back();
  3528. node.stats = sectionStats;
  3529. m_sectionStack.pop_back();
  3530. }
  3531. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  3532. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  3533. assert(m_sectionStack.size() == 0);
  3534. node->children.push_back(m_rootSection);
  3535. m_testCases.push_back(node);
  3536. m_rootSection.reset();
  3537. assert(m_deepestSection);
  3538. m_deepestSection->stdOut = testCaseStats.stdOut;
  3539. m_deepestSection->stdErr = testCaseStats.stdErr;
  3540. }
  3541. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  3542. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  3543. node->children.swap(m_testCases);
  3544. m_testGroups.push_back(node);
  3545. }
  3546. void testRunEnded(TestRunStats const& testRunStats) override {
  3547. auto node = std::make_shared<TestRunNode>(testRunStats);
  3548. node->children.swap(m_testGroups);
  3549. m_testRuns.push_back(node);
  3550. testRunEndedCumulative();
  3551. }
  3552. virtual void testRunEndedCumulative() = 0;
  3553. void skipTest(TestCaseInfo const&) override {}
  3554. IConfigPtr m_config;
  3555. std::ostream& stream;
  3556. std::vector<AssertionStats> m_assertions;
  3557. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  3558. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  3559. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  3560. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  3561. std::shared_ptr<SectionNode> m_rootSection;
  3562. std::shared_ptr<SectionNode> m_deepestSection;
  3563. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  3564. ReporterPreferences m_reporterPrefs;
  3565. };
  3566. template<char C>
  3567. char const* getLineOfChars() {
  3568. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  3569. if( !*line ) {
  3570. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  3571. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  3572. }
  3573. return line;
  3574. }
  3575. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  3576. TestEventListenerBase( ReporterConfig const& _config );
  3577. void assertionStarting(AssertionInfo const&) override;
  3578. bool assertionEnded(AssertionStats const&) override;
  3579. };
  3580. } // end namespace Catch
  3581. // end catch_reporter_bases.hpp
  3582. // start catch_console_colour.h
  3583. namespace Catch {
  3584. struct Colour {
  3585. enum Code {
  3586. None = 0,
  3587. White,
  3588. Red,
  3589. Green,
  3590. Blue,
  3591. Cyan,
  3592. Yellow,
  3593. Grey,
  3594. Bright = 0x10,
  3595. BrightRed = Bright | Red,
  3596. BrightGreen = Bright | Green,
  3597. LightGrey = Bright | Grey,
  3598. BrightWhite = Bright | White,
  3599. BrightYellow = Bright | Yellow,
  3600. // By intention
  3601. FileName = LightGrey,
  3602. Warning = BrightYellow,
  3603. ResultError = BrightRed,
  3604. ResultSuccess = BrightGreen,
  3605. ResultExpectedFailure = Warning,
  3606. Error = BrightRed,
  3607. Success = Green,
  3608. OriginalExpression = Cyan,
  3609. ReconstructedExpression = BrightYellow,
  3610. SecondaryText = LightGrey,
  3611. Headers = White
  3612. };
  3613. // Use constructed object for RAII guard
  3614. Colour( Code _colourCode );
  3615. Colour( Colour&& other ) noexcept;
  3616. Colour& operator=( Colour&& other ) noexcept;
  3617. ~Colour();
  3618. // Use static method for one-shot changes
  3619. static void use( Code _colourCode );
  3620. private:
  3621. bool m_moved = false;
  3622. };
  3623. std::ostream& operator << ( std::ostream& os, Colour const& );
  3624. } // end namespace Catch
  3625. // end catch_console_colour.h
  3626. // start catch_reporter_registrars.hpp
  3627. namespace Catch {
  3628. template<typename T>
  3629. class ReporterRegistrar {
  3630. class ReporterFactory : public IReporterFactory {
  3631. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3632. return std::unique_ptr<T>( new T( config ) );
  3633. }
  3634. virtual std::string getDescription() const override {
  3635. return T::getDescription();
  3636. }
  3637. };
  3638. public:
  3639. explicit ReporterRegistrar( std::string const& name ) {
  3640. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  3641. }
  3642. };
  3643. template<typename T>
  3644. class ListenerRegistrar {
  3645. class ListenerFactory : public IReporterFactory {
  3646. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3647. return std::unique_ptr<T>( new T( config ) );
  3648. }
  3649. virtual std::string getDescription() const override {
  3650. return std::string();
  3651. }
  3652. };
  3653. public:
  3654. ListenerRegistrar() {
  3655. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  3656. }
  3657. };
  3658. }
  3659. #if !defined(CATCH_CONFIG_DISABLE)
  3660. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  3661. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3662. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  3663. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  3664. #define CATCH_REGISTER_LISTENER( listenerType ) \
  3665. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3666. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  3667. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  3668. #else // CATCH_CONFIG_DISABLE
  3669. #define CATCH_REGISTER_REPORTER(name, reporterType)
  3670. #define CATCH_REGISTER_LISTENER(listenerType)
  3671. #endif // CATCH_CONFIG_DISABLE
  3672. // end catch_reporter_registrars.hpp
  3673. // Allow users to base their work off existing reporters
  3674. // start catch_reporter_compact.h
  3675. namespace Catch {
  3676. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  3677. using StreamingReporterBase::StreamingReporterBase;
  3678. ~CompactReporter() override;
  3679. static std::string getDescription();
  3680. ReporterPreferences getPreferences() const override;
  3681. void noMatchingTestCases(std::string const& spec) override;
  3682. void assertionStarting(AssertionInfo const&) override;
  3683. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3684. void sectionEnded(SectionStats const& _sectionStats) override;
  3685. void testRunEnded(TestRunStats const& _testRunStats) override;
  3686. };
  3687. } // end namespace Catch
  3688. // end catch_reporter_compact.h
  3689. // start catch_reporter_console.h
  3690. #if defined(_MSC_VER)
  3691. #pragma warning(push)
  3692. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  3693. // Note that 4062 (not all labels are handled
  3694. // and default is missing) is enabled
  3695. #endif
  3696. namespace Catch {
  3697. // Fwd decls
  3698. struct SummaryColumn;
  3699. class TablePrinter;
  3700. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  3701. std::unique_ptr<TablePrinter> m_tablePrinter;
  3702. ConsoleReporter(ReporterConfig const& config);
  3703. ~ConsoleReporter() override;
  3704. static std::string getDescription();
  3705. void noMatchingTestCases(std::string const& spec) override;
  3706. void assertionStarting(AssertionInfo const&) override;
  3707. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3708. void sectionStarting(SectionInfo const& _sectionInfo) override;
  3709. void sectionEnded(SectionStats const& _sectionStats) override;
  3710. void benchmarkStarting(BenchmarkInfo const& info) override;
  3711. void benchmarkEnded(BenchmarkStats const& stats) override;
  3712. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  3713. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  3714. void testRunEnded(TestRunStats const& _testRunStats) override;
  3715. private:
  3716. void lazyPrint();
  3717. void lazyPrintWithoutClosingBenchmarkTable();
  3718. void lazyPrintRunInfo();
  3719. void lazyPrintGroupInfo();
  3720. void printTestCaseAndSectionHeader();
  3721. void printClosedHeader(std::string const& _name);
  3722. void printOpenHeader(std::string const& _name);
  3723. // if string has a : in first line will set indent to follow it on
  3724. // subsequent lines
  3725. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  3726. void printTotals(Totals const& totals);
  3727. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  3728. void printTotalsDivider(Totals const& totals);
  3729. void printSummaryDivider();
  3730. private:
  3731. bool m_headerPrinted = false;
  3732. };
  3733. } // end namespace Catch
  3734. #if defined(_MSC_VER)
  3735. #pragma warning(pop)
  3736. #endif
  3737. // end catch_reporter_console.h
  3738. // start catch_reporter_junit.h
  3739. // start catch_xmlwriter.h
  3740. #include <vector>
  3741. namespace Catch {
  3742. class XmlEncode {
  3743. public:
  3744. enum ForWhat { ForTextNodes, ForAttributes };
  3745. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  3746. void encodeTo( std::ostream& os ) const;
  3747. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  3748. private:
  3749. std::string m_str;
  3750. ForWhat m_forWhat;
  3751. };
  3752. class XmlWriter {
  3753. public:
  3754. class ScopedElement {
  3755. public:
  3756. ScopedElement( XmlWriter* writer );
  3757. ScopedElement( ScopedElement&& other ) noexcept;
  3758. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  3759. ~ScopedElement();
  3760. ScopedElement& writeText( std::string const& text, bool indent = true );
  3761. template<typename T>
  3762. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  3763. m_writer->writeAttribute( name, attribute );
  3764. return *this;
  3765. }
  3766. private:
  3767. mutable XmlWriter* m_writer = nullptr;
  3768. };
  3769. XmlWriter( std::ostream& os = Catch::cout() );
  3770. ~XmlWriter();
  3771. XmlWriter( XmlWriter const& ) = delete;
  3772. XmlWriter& operator=( XmlWriter const& ) = delete;
  3773. XmlWriter& startElement( std::string const& name );
  3774. ScopedElement scopedElement( std::string const& name );
  3775. XmlWriter& endElement();
  3776. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  3777. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  3778. template<typename T>
  3779. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  3780. ReusableStringStream rss;
  3781. rss << attribute;
  3782. return writeAttribute( name, rss.str() );
  3783. }
  3784. XmlWriter& writeText( std::string const& text, bool indent = true );
  3785. XmlWriter& writeComment( std::string const& text );
  3786. void writeStylesheetRef( std::string const& url );
  3787. XmlWriter& writeBlankLine();
  3788. void ensureTagClosed();
  3789. private:
  3790. void writeDeclaration();
  3791. void newlineIfNecessary();
  3792. bool m_tagIsOpen = false;
  3793. bool m_needsNewline = false;
  3794. std::vector<std::string> m_tags;
  3795. std::string m_indent;
  3796. std::ostream& m_os;
  3797. };
  3798. }
  3799. // end catch_xmlwriter.h
  3800. namespace Catch {
  3801. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  3802. public:
  3803. JunitReporter(ReporterConfig const& _config);
  3804. ~JunitReporter() override;
  3805. static std::string getDescription();
  3806. void noMatchingTestCases(std::string const& /*spec*/) override;
  3807. void testRunStarting(TestRunInfo const& runInfo) override;
  3808. void testGroupStarting(GroupInfo const& groupInfo) override;
  3809. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  3810. bool assertionEnded(AssertionStats const& assertionStats) override;
  3811. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3812. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3813. void testRunEndedCumulative() override;
  3814. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  3815. void writeTestCase(TestCaseNode const& testCaseNode);
  3816. void writeSection(std::string const& className,
  3817. std::string const& rootName,
  3818. SectionNode const& sectionNode);
  3819. void writeAssertions(SectionNode const& sectionNode);
  3820. void writeAssertion(AssertionStats const& stats);
  3821. XmlWriter xml;
  3822. Timer suiteTimer;
  3823. std::string stdOutForSuite;
  3824. std::string stdErrForSuite;
  3825. unsigned int unexpectedExceptions = 0;
  3826. bool m_okToFail = false;
  3827. };
  3828. } // end namespace Catch
  3829. // end catch_reporter_junit.h
  3830. // start catch_reporter_xml.h
  3831. namespace Catch {
  3832. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  3833. public:
  3834. XmlReporter(ReporterConfig const& _config);
  3835. ~XmlReporter() override;
  3836. static std::string getDescription();
  3837. virtual std::string getStylesheetRef() const;
  3838. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  3839. public: // StreamingReporterBase
  3840. void noMatchingTestCases(std::string const& s) override;
  3841. void testRunStarting(TestRunInfo const& testInfo) override;
  3842. void testGroupStarting(GroupInfo const& groupInfo) override;
  3843. void testCaseStarting(TestCaseInfo const& testInfo) override;
  3844. void sectionStarting(SectionInfo const& sectionInfo) override;
  3845. void assertionStarting(AssertionInfo const&) override;
  3846. bool assertionEnded(AssertionStats const& assertionStats) override;
  3847. void sectionEnded(SectionStats const& sectionStats) override;
  3848. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3849. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3850. void testRunEnded(TestRunStats const& testRunStats) override;
  3851. private:
  3852. Timer m_testCaseTimer;
  3853. XmlWriter m_xml;
  3854. int m_sectionDepth = 0;
  3855. };
  3856. } // end namespace Catch
  3857. // end catch_reporter_xml.h
  3858. // end catch_external_interfaces.h
  3859. #endif
  3860. #endif // ! CATCH_CONFIG_IMPL_ONLY
  3861. #ifdef CATCH_IMPL
  3862. // start catch_impl.hpp
  3863. #ifdef __clang__
  3864. #pragma clang diagnostic push
  3865. #pragma clang diagnostic ignored "-Wweak-vtables"
  3866. #endif
  3867. // Keep these here for external reporters
  3868. // start catch_test_case_tracker.h
  3869. #include <string>
  3870. #include <vector>
  3871. #include <memory>
  3872. namespace Catch {
  3873. namespace TestCaseTracking {
  3874. struct NameAndLocation {
  3875. std::string name;
  3876. SourceLineInfo location;
  3877. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  3878. };
  3879. struct ITracker;
  3880. using ITrackerPtr = std::shared_ptr<ITracker>;
  3881. struct ITracker {
  3882. virtual ~ITracker();
  3883. // static queries
  3884. virtual NameAndLocation const& nameAndLocation() const = 0;
  3885. // dynamic queries
  3886. virtual bool isComplete() const = 0; // Successfully completed or failed
  3887. virtual bool isSuccessfullyCompleted() const = 0;
  3888. virtual bool isOpen() const = 0; // Started but not complete
  3889. virtual bool hasChildren() const = 0;
  3890. virtual ITracker& parent() = 0;
  3891. // actions
  3892. virtual void close() = 0; // Successfully complete
  3893. virtual void fail() = 0;
  3894. virtual void markAsNeedingAnotherRun() = 0;
  3895. virtual void addChild( ITrackerPtr const& child ) = 0;
  3896. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  3897. virtual void openChild() = 0;
  3898. // Debug/ checking
  3899. virtual bool isSectionTracker() const = 0;
  3900. virtual bool isIndexTracker() const = 0;
  3901. };
  3902. class TrackerContext {
  3903. enum RunState {
  3904. NotStarted,
  3905. Executing,
  3906. CompletedCycle
  3907. };
  3908. ITrackerPtr m_rootTracker;
  3909. ITracker* m_currentTracker = nullptr;
  3910. RunState m_runState = NotStarted;
  3911. public:
  3912. static TrackerContext& instance();
  3913. ITracker& startRun();
  3914. void endRun();
  3915. void startCycle();
  3916. void completeCycle();
  3917. bool completedCycle() const;
  3918. ITracker& currentTracker();
  3919. void setCurrentTracker( ITracker* tracker );
  3920. };
  3921. class TrackerBase : public ITracker {
  3922. protected:
  3923. enum CycleState {
  3924. NotStarted,
  3925. Executing,
  3926. ExecutingChildren,
  3927. NeedsAnotherRun,
  3928. CompletedSuccessfully,
  3929. Failed
  3930. };
  3931. using Children = std::vector<ITrackerPtr>;
  3932. NameAndLocation m_nameAndLocation;
  3933. TrackerContext& m_ctx;
  3934. ITracker* m_parent;
  3935. Children m_children;
  3936. CycleState m_runState = NotStarted;
  3937. public:
  3938. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3939. NameAndLocation const& nameAndLocation() const override;
  3940. bool isComplete() const override;
  3941. bool isSuccessfullyCompleted() const override;
  3942. bool isOpen() const override;
  3943. bool hasChildren() const override;
  3944. void addChild( ITrackerPtr const& child ) override;
  3945. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  3946. ITracker& parent() override;
  3947. void openChild() override;
  3948. bool isSectionTracker() const override;
  3949. bool isIndexTracker() const override;
  3950. void open();
  3951. void close() override;
  3952. void fail() override;
  3953. void markAsNeedingAnotherRun() override;
  3954. private:
  3955. void moveToParent();
  3956. void moveToThis();
  3957. };
  3958. class SectionTracker : public TrackerBase {
  3959. std::vector<std::string> m_filters;
  3960. public:
  3961. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  3962. bool isSectionTracker() const override;
  3963. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  3964. void tryOpen();
  3965. void addInitialFilters( std::vector<std::string> const& filters );
  3966. void addNextFilters( std::vector<std::string> const& filters );
  3967. };
  3968. class IndexTracker : public TrackerBase {
  3969. int m_size;
  3970. int m_index = -1;
  3971. public:
  3972. IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size );
  3973. bool isIndexTracker() const override;
  3974. void close() override;
  3975. static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size );
  3976. int index() const;
  3977. void moveNext();
  3978. };
  3979. } // namespace TestCaseTracking
  3980. using TestCaseTracking::ITracker;
  3981. using TestCaseTracking::TrackerContext;
  3982. using TestCaseTracking::SectionTracker;
  3983. using TestCaseTracking::IndexTracker;
  3984. } // namespace Catch
  3985. // end catch_test_case_tracker.h
  3986. // start catch_leak_detector.h
  3987. namespace Catch {
  3988. struct LeakDetector {
  3989. LeakDetector();
  3990. };
  3991. }
  3992. // end catch_leak_detector.h
  3993. // Cpp files will be included in the single-header file here
  3994. // start catch_approx.cpp
  3995. #include <cmath>
  3996. #include <limits>
  3997. namespace {
  3998. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  3999. // But without the subtraction to allow for INFINITY in comparison
  4000. bool marginComparison(double lhs, double rhs, double margin) {
  4001. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  4002. }
  4003. }
  4004. namespace Catch {
  4005. namespace Detail {
  4006. Approx::Approx ( double value )
  4007. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  4008. m_margin( 0.0 ),
  4009. m_scale( 0.0 ),
  4010. m_value( value )
  4011. {}
  4012. Approx Approx::custom() {
  4013. return Approx( 0 );
  4014. }
  4015. Approx Approx::operator-() const {
  4016. auto temp(*this);
  4017. temp.m_value = -temp.m_value;
  4018. return temp;
  4019. }
  4020. std::string Approx::toString() const {
  4021. ReusableStringStream rss;
  4022. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  4023. return rss.str();
  4024. }
  4025. bool Approx::equalityComparisonImpl(const double other) const {
  4026. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  4027. // Thanks to Richard Harris for his help refining the scaled margin value
  4028. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  4029. }
  4030. void Approx::setMargin(double margin) {
  4031. CATCH_ENFORCE(margin >= 0,
  4032. "Invalid Approx::margin: " << margin << '.'
  4033. << " Approx::Margin has to be non-negative.");
  4034. m_margin = margin;
  4035. }
  4036. void Approx::setEpsilon(double epsilon) {
  4037. CATCH_ENFORCE(epsilon >= 0 && epsilon <= 1.0,
  4038. "Invalid Approx::epsilon: " << epsilon << '.'
  4039. << " Approx::epsilon has to be in [0, 1]");
  4040. m_epsilon = epsilon;
  4041. }
  4042. } // end namespace Detail
  4043. namespace literals {
  4044. Detail::Approx operator "" _a(long double val) {
  4045. return Detail::Approx(val);
  4046. }
  4047. Detail::Approx operator "" _a(unsigned long long val) {
  4048. return Detail::Approx(val);
  4049. }
  4050. } // end namespace literals
  4051. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  4052. return value.toString();
  4053. }
  4054. } // end namespace Catch
  4055. // end catch_approx.cpp
  4056. // start catch_assertionhandler.cpp
  4057. // start catch_context.h
  4058. #include <memory>
  4059. namespace Catch {
  4060. struct IResultCapture;
  4061. struct IRunner;
  4062. struct IConfig;
  4063. struct IMutableContext;
  4064. using IConfigPtr = std::shared_ptr<IConfig const>;
  4065. struct IContext
  4066. {
  4067. virtual ~IContext();
  4068. virtual IResultCapture* getResultCapture() = 0;
  4069. virtual IRunner* getRunner() = 0;
  4070. virtual IConfigPtr const& getConfig() const = 0;
  4071. };
  4072. struct IMutableContext : IContext
  4073. {
  4074. virtual ~IMutableContext();
  4075. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  4076. virtual void setRunner( IRunner* runner ) = 0;
  4077. virtual void setConfig( IConfigPtr const& config ) = 0;
  4078. private:
  4079. static IMutableContext *currentContext;
  4080. friend IMutableContext& getCurrentMutableContext();
  4081. friend void cleanUpContext();
  4082. static void createContext();
  4083. };
  4084. inline IMutableContext& getCurrentMutableContext()
  4085. {
  4086. if( !IMutableContext::currentContext )
  4087. IMutableContext::createContext();
  4088. return *IMutableContext::currentContext;
  4089. }
  4090. inline IContext& getCurrentContext()
  4091. {
  4092. return getCurrentMutableContext();
  4093. }
  4094. void cleanUpContext();
  4095. }
  4096. // end catch_context.h
  4097. // start catch_debugger.h
  4098. namespace Catch {
  4099. bool isDebuggerActive();
  4100. }
  4101. #ifdef CATCH_PLATFORM_MAC
  4102. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  4103. #elif defined(CATCH_PLATFORM_LINUX)
  4104. // If we can use inline assembler, do it because this allows us to break
  4105. // directly at the location of the failing check instead of breaking inside
  4106. // raise() called from it, i.e. one stack frame below.
  4107. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  4108. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  4109. #else // Fall back to the generic way.
  4110. #include <signal.h>
  4111. #define CATCH_TRAP() raise(SIGTRAP)
  4112. #endif
  4113. #elif defined(_MSC_VER)
  4114. #define CATCH_TRAP() __debugbreak()
  4115. #elif defined(__MINGW32__)
  4116. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  4117. #define CATCH_TRAP() DebugBreak()
  4118. #endif
  4119. #ifdef CATCH_TRAP
  4120. #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
  4121. #else
  4122. namespace Catch {
  4123. inline void doNothing() {}
  4124. }
  4125. #define CATCH_BREAK_INTO_DEBUGGER() Catch::doNothing()
  4126. #endif
  4127. // end catch_debugger.h
  4128. // start catch_run_context.h
  4129. // start catch_fatal_condition.h
  4130. // start catch_windows_h_proxy.h
  4131. #if defined(CATCH_PLATFORM_WINDOWS)
  4132. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  4133. # define CATCH_DEFINED_NOMINMAX
  4134. # define NOMINMAX
  4135. #endif
  4136. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  4137. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4138. # define WIN32_LEAN_AND_MEAN
  4139. #endif
  4140. #ifdef __AFXDLL
  4141. #include <AfxWin.h>
  4142. #else
  4143. #include <windows.h>
  4144. #endif
  4145. #ifdef CATCH_DEFINED_NOMINMAX
  4146. # undef NOMINMAX
  4147. #endif
  4148. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4149. # undef WIN32_LEAN_AND_MEAN
  4150. #endif
  4151. #endif // defined(CATCH_PLATFORM_WINDOWS)
  4152. // end catch_windows_h_proxy.h
  4153. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  4154. namespace Catch {
  4155. struct FatalConditionHandler {
  4156. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  4157. FatalConditionHandler();
  4158. static void reset();
  4159. ~FatalConditionHandler();
  4160. private:
  4161. static bool isSet;
  4162. static ULONG guaranteeSize;
  4163. static PVOID exceptionHandlerHandle;
  4164. };
  4165. } // namespace Catch
  4166. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  4167. #include <signal.h>
  4168. namespace Catch {
  4169. struct FatalConditionHandler {
  4170. static bool isSet;
  4171. static struct sigaction oldSigActions[];
  4172. static stack_t oldSigStack;
  4173. static char altStackMem[];
  4174. static void handleSignal( int sig );
  4175. FatalConditionHandler();
  4176. ~FatalConditionHandler();
  4177. static void reset();
  4178. };
  4179. } // namespace Catch
  4180. #else
  4181. namespace Catch {
  4182. struct FatalConditionHandler {
  4183. void reset();
  4184. };
  4185. }
  4186. #endif
  4187. // end catch_fatal_condition.h
  4188. #include <string>
  4189. namespace Catch {
  4190. struct IMutableContext;
  4191. ///////////////////////////////////////////////////////////////////////////
  4192. class RunContext : public IResultCapture, public IRunner {
  4193. public:
  4194. RunContext( RunContext const& ) = delete;
  4195. RunContext& operator =( RunContext const& ) = delete;
  4196. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  4197. ~RunContext() override;
  4198. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  4199. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  4200. Totals runTest(TestCase const& testCase);
  4201. IConfigPtr config() const;
  4202. IStreamingReporter& reporter() const;
  4203. public: // IResultCapture
  4204. // Assertion handlers
  4205. void handleExpr
  4206. ( AssertionInfo const& info,
  4207. ITransientExpression const& expr,
  4208. AssertionReaction& reaction ) override;
  4209. void handleMessage
  4210. ( AssertionInfo const& info,
  4211. ResultWas::OfType resultType,
  4212. StringRef const& message,
  4213. AssertionReaction& reaction ) override;
  4214. void handleUnexpectedExceptionNotThrown
  4215. ( AssertionInfo const& info,
  4216. AssertionReaction& reaction ) override;
  4217. void handleUnexpectedInflightException
  4218. ( AssertionInfo const& info,
  4219. std::string const& message,
  4220. AssertionReaction& reaction ) override;
  4221. void handleIncomplete
  4222. ( AssertionInfo const& info ) override;
  4223. void handleNonExpr
  4224. ( AssertionInfo const &info,
  4225. ResultWas::OfType resultType,
  4226. AssertionReaction &reaction ) override;
  4227. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  4228. void sectionEnded( SectionEndInfo const& endInfo ) override;
  4229. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  4230. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  4231. void benchmarkStarting( BenchmarkInfo const& info ) override;
  4232. void benchmarkEnded( BenchmarkStats const& stats ) override;
  4233. void pushScopedMessage( MessageInfo const& message ) override;
  4234. void popScopedMessage( MessageInfo const& message ) override;
  4235. std::string getCurrentTestName() const override;
  4236. const AssertionResult* getLastResult() const override;
  4237. void exceptionEarlyReported() override;
  4238. void handleFatalErrorCondition( StringRef message ) override;
  4239. bool lastAssertionPassed() override;
  4240. void assertionPassed() override;
  4241. public:
  4242. // !TBD We need to do this another way!
  4243. bool aborting() const final;
  4244. private:
  4245. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  4246. void invokeActiveTestCase();
  4247. void resetAssertionInfo();
  4248. bool testForMissingAssertions( Counts& assertions );
  4249. void assertionEnded( AssertionResult const& result );
  4250. void reportExpr
  4251. ( AssertionInfo const &info,
  4252. ResultWas::OfType resultType,
  4253. ITransientExpression const *expr,
  4254. bool negated );
  4255. void populateReaction( AssertionReaction& reaction );
  4256. private:
  4257. void handleUnfinishedSections();
  4258. TestRunInfo m_runInfo;
  4259. IMutableContext& m_context;
  4260. TestCase const* m_activeTestCase = nullptr;
  4261. ITracker* m_testCaseTracker;
  4262. Option<AssertionResult> m_lastResult;
  4263. IConfigPtr m_config;
  4264. Totals m_totals;
  4265. IStreamingReporterPtr m_reporter;
  4266. std::vector<MessageInfo> m_messages;
  4267. AssertionInfo m_lastAssertionInfo;
  4268. std::vector<SectionEndInfo> m_unfinishedSections;
  4269. std::vector<ITracker*> m_activeSections;
  4270. TrackerContext m_trackerContext;
  4271. bool m_lastAssertionPassed = false;
  4272. bool m_shouldReportUnexpected = true;
  4273. bool m_includeSuccessfulResults;
  4274. };
  4275. } // end namespace Catch
  4276. // end catch_run_context.h
  4277. namespace Catch {
  4278. namespace {
  4279. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  4280. expr.streamReconstructedExpression( os );
  4281. return os;
  4282. }
  4283. }
  4284. LazyExpression::LazyExpression( bool isNegated )
  4285. : m_isNegated( isNegated )
  4286. {}
  4287. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  4288. LazyExpression::operator bool() const {
  4289. return m_transientExpression != nullptr;
  4290. }
  4291. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  4292. if( lazyExpr.m_isNegated )
  4293. os << "!";
  4294. if( lazyExpr ) {
  4295. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  4296. os << "(" << *lazyExpr.m_transientExpression << ")";
  4297. else
  4298. os << *lazyExpr.m_transientExpression;
  4299. }
  4300. else {
  4301. os << "{** error - unchecked empty expression requested **}";
  4302. }
  4303. return os;
  4304. }
  4305. AssertionHandler::AssertionHandler
  4306. ( StringRef const& macroName,
  4307. SourceLineInfo const& lineInfo,
  4308. StringRef capturedExpression,
  4309. ResultDisposition::Flags resultDisposition )
  4310. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  4311. m_resultCapture( getResultCapture() )
  4312. {}
  4313. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  4314. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  4315. }
  4316. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  4317. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  4318. }
  4319. auto AssertionHandler::allowThrows() const -> bool {
  4320. return getCurrentContext().getConfig()->allowThrows();
  4321. }
  4322. void AssertionHandler::complete() {
  4323. setCompleted();
  4324. if( m_reaction.shouldDebugBreak ) {
  4325. // If you find your debugger stopping you here then go one level up on the
  4326. // call-stack for the code that caused it (typically a failed assertion)
  4327. // (To go back to the test and change execution, jump over the throw, next)
  4328. CATCH_BREAK_INTO_DEBUGGER();
  4329. }
  4330. if (m_reaction.shouldThrow) {
  4331. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  4332. throw Catch::TestFailureException();
  4333. #else
  4334. CATCH_ERROR( "Test failure requires aborting test!" );
  4335. #endif
  4336. }
  4337. }
  4338. void AssertionHandler::setCompleted() {
  4339. m_completed = true;
  4340. }
  4341. void AssertionHandler::handleUnexpectedInflightException() {
  4342. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  4343. }
  4344. void AssertionHandler::handleExceptionThrownAsExpected() {
  4345. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4346. }
  4347. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  4348. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4349. }
  4350. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  4351. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  4352. }
  4353. void AssertionHandler::handleThrowingCallSkipped() {
  4354. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4355. }
  4356. // This is the overload that takes a string and infers the Equals matcher from it
  4357. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  4358. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  4359. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  4360. }
  4361. } // namespace Catch
  4362. // end catch_assertionhandler.cpp
  4363. // start catch_assertionresult.cpp
  4364. namespace Catch {
  4365. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  4366. lazyExpression(_lazyExpression),
  4367. resultType(_resultType) {}
  4368. std::string AssertionResultData::reconstructExpression() const {
  4369. if( reconstructedExpression.empty() ) {
  4370. if( lazyExpression ) {
  4371. ReusableStringStream rss;
  4372. rss << lazyExpression;
  4373. reconstructedExpression = rss.str();
  4374. }
  4375. }
  4376. return reconstructedExpression;
  4377. }
  4378. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  4379. : m_info( info ),
  4380. m_resultData( data )
  4381. {}
  4382. // Result was a success
  4383. bool AssertionResult::succeeded() const {
  4384. return Catch::isOk( m_resultData.resultType );
  4385. }
  4386. // Result was a success, or failure is suppressed
  4387. bool AssertionResult::isOk() const {
  4388. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  4389. }
  4390. ResultWas::OfType AssertionResult::getResultType() const {
  4391. return m_resultData.resultType;
  4392. }
  4393. bool AssertionResult::hasExpression() const {
  4394. return m_info.capturedExpression[0] != 0;
  4395. }
  4396. bool AssertionResult::hasMessage() const {
  4397. return !m_resultData.message.empty();
  4398. }
  4399. std::string AssertionResult::getExpression() const {
  4400. if( isFalseTest( m_info.resultDisposition ) )
  4401. return "!(" + m_info.capturedExpression + ")";
  4402. else
  4403. return m_info.capturedExpression;
  4404. }
  4405. std::string AssertionResult::getExpressionInMacro() const {
  4406. std::string expr;
  4407. if( m_info.macroName[0] == 0 )
  4408. expr = m_info.capturedExpression;
  4409. else {
  4410. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  4411. expr += m_info.macroName;
  4412. expr += "( ";
  4413. expr += m_info.capturedExpression;
  4414. expr += " )";
  4415. }
  4416. return expr;
  4417. }
  4418. bool AssertionResult::hasExpandedExpression() const {
  4419. return hasExpression() && getExpandedExpression() != getExpression();
  4420. }
  4421. std::string AssertionResult::getExpandedExpression() const {
  4422. std::string expr = m_resultData.reconstructExpression();
  4423. return expr.empty()
  4424. ? getExpression()
  4425. : expr;
  4426. }
  4427. std::string AssertionResult::getMessage() const {
  4428. return m_resultData.message;
  4429. }
  4430. SourceLineInfo AssertionResult::getSourceInfo() const {
  4431. return m_info.lineInfo;
  4432. }
  4433. StringRef AssertionResult::getTestMacroName() const {
  4434. return m_info.macroName;
  4435. }
  4436. } // end namespace Catch
  4437. // end catch_assertionresult.cpp
  4438. // start catch_benchmark.cpp
  4439. namespace Catch {
  4440. auto BenchmarkLooper::getResolution() -> uint64_t {
  4441. return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
  4442. }
  4443. void BenchmarkLooper::reportStart() {
  4444. getResultCapture().benchmarkStarting( { m_name } );
  4445. }
  4446. auto BenchmarkLooper::needsMoreIterations() -> bool {
  4447. auto elapsed = m_timer.getElapsedNanoseconds();
  4448. // Exponentially increasing iterations until we're confident in our timer resolution
  4449. if( elapsed < m_resolution ) {
  4450. m_iterationsToRun *= 10;
  4451. return true;
  4452. }
  4453. getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
  4454. return false;
  4455. }
  4456. } // end namespace Catch
  4457. // end catch_benchmark.cpp
  4458. // start catch_capture_matchers.cpp
  4459. namespace Catch {
  4460. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  4461. // This is the general overload that takes a any string matcher
  4462. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  4463. // the Equals matcher (so the header does not mention matchers)
  4464. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  4465. std::string exceptionMessage = Catch::translateActiveException();
  4466. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  4467. handler.handleExpr( expr );
  4468. }
  4469. } // namespace Catch
  4470. // end catch_capture_matchers.cpp
  4471. // start catch_commandline.cpp
  4472. // start catch_commandline.h
  4473. // start catch_clara.h
  4474. // Use Catch's value for console width (store Clara's off to the side, if present)
  4475. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  4476. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4477. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4478. #endif
  4479. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  4480. #ifdef __clang__
  4481. #pragma clang diagnostic push
  4482. #pragma clang diagnostic ignored "-Wweak-vtables"
  4483. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  4484. #pragma clang diagnostic ignored "-Wshadow"
  4485. #endif
  4486. // start clara.hpp
  4487. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  4488. //
  4489. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4490. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4491. //
  4492. // See https://github.com/philsquared/Clara for more details
  4493. // Clara v1.1.4
  4494. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4495. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  4496. #endif
  4497. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4498. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4499. #endif
  4500. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  4501. #ifdef __has_include
  4502. #if __has_include(<optional>) && __cplusplus >= 201703L
  4503. #include <optional>
  4504. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  4505. #endif
  4506. #endif
  4507. #endif
  4508. // ----------- #included from clara_textflow.hpp -----------
  4509. // TextFlowCpp
  4510. //
  4511. // A single-header library for wrapping and laying out basic text, by Phil Nash
  4512. //
  4513. // This work is licensed under the BSD 2-Clause license.
  4514. // See the accompanying LICENSE file, or the one at https://opensource.org/licenses/BSD-2-Clause
  4515. //
  4516. // This project is hosted at https://github.com/philsquared/textflowcpp
  4517. #include <cassert>
  4518. #include <ostream>
  4519. #include <sstream>
  4520. #include <vector>
  4521. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4522. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  4523. #endif
  4524. namespace Catch { namespace clara { namespace TextFlow {
  4525. inline auto isWhitespace( char c ) -> bool {
  4526. static std::string chars = " \t\n\r";
  4527. return chars.find( c ) != std::string::npos;
  4528. }
  4529. inline auto isBreakableBefore( char c ) -> bool {
  4530. static std::string chars = "[({<|";
  4531. return chars.find( c ) != std::string::npos;
  4532. }
  4533. inline auto isBreakableAfter( char c ) -> bool {
  4534. static std::string chars = "])}>.,:;*+-=&/\\";
  4535. return chars.find( c ) != std::string::npos;
  4536. }
  4537. class Columns;
  4538. class Column {
  4539. std::vector<std::string> m_strings;
  4540. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  4541. size_t m_indent = 0;
  4542. size_t m_initialIndent = std::string::npos;
  4543. public:
  4544. class iterator {
  4545. friend Column;
  4546. Column const& m_column;
  4547. size_t m_stringIndex = 0;
  4548. size_t m_pos = 0;
  4549. size_t m_len = 0;
  4550. size_t m_end = 0;
  4551. bool m_suffix = false;
  4552. iterator( Column const& column, size_t stringIndex )
  4553. : m_column( column ),
  4554. m_stringIndex( stringIndex )
  4555. {}
  4556. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  4557. auto isBoundary( size_t at ) const -> bool {
  4558. assert( at > 0 );
  4559. assert( at <= line().size() );
  4560. return at == line().size() ||
  4561. ( isWhitespace( line()[at] ) && !isWhitespace( line()[at-1] ) ) ||
  4562. isBreakableBefore( line()[at] ) ||
  4563. isBreakableAfter( line()[at-1] );
  4564. }
  4565. void calcLength() {
  4566. assert( m_stringIndex < m_column.m_strings.size() );
  4567. m_suffix = false;
  4568. auto width = m_column.m_width-indent();
  4569. m_end = m_pos;
  4570. while( m_end < line().size() && line()[m_end] != '\n' )
  4571. ++m_end;
  4572. if( m_end < m_pos + width ) {
  4573. m_len = m_end - m_pos;
  4574. }
  4575. else {
  4576. size_t len = width;
  4577. while (len > 0 && !isBoundary(m_pos + len))
  4578. --len;
  4579. while (len > 0 && isWhitespace( line()[m_pos + len - 1] ))
  4580. --len;
  4581. if (len > 0) {
  4582. m_len = len;
  4583. } else {
  4584. m_suffix = true;
  4585. m_len = width - 1;
  4586. }
  4587. }
  4588. }
  4589. auto indent() const -> size_t {
  4590. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  4591. return initial == std::string::npos ? m_column.m_indent : initial;
  4592. }
  4593. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  4594. return std::string( indent(), ' ' ) + (m_suffix ? plain + "-" : plain);
  4595. }
  4596. public:
  4597. explicit iterator( Column const& column ) : m_column( column ) {
  4598. assert( m_column.m_width > m_column.m_indent );
  4599. assert( m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent );
  4600. calcLength();
  4601. if( m_len == 0 )
  4602. m_stringIndex++; // Empty string
  4603. }
  4604. auto operator *() const -> std::string {
  4605. assert( m_stringIndex < m_column.m_strings.size() );
  4606. assert( m_pos <= m_end );
  4607. if( m_pos + m_column.m_width < m_end )
  4608. return addIndentAndSuffix(line().substr(m_pos, m_len));
  4609. else
  4610. return addIndentAndSuffix(line().substr(m_pos, m_end - m_pos));
  4611. }
  4612. auto operator ++() -> iterator& {
  4613. m_pos += m_len;
  4614. if( m_pos < line().size() && line()[m_pos] == '\n' )
  4615. m_pos += 1;
  4616. else
  4617. while( m_pos < line().size() && isWhitespace( line()[m_pos] ) )
  4618. ++m_pos;
  4619. if( m_pos == line().size() ) {
  4620. m_pos = 0;
  4621. ++m_stringIndex;
  4622. }
  4623. if( m_stringIndex < m_column.m_strings.size() )
  4624. calcLength();
  4625. return *this;
  4626. }
  4627. auto operator ++(int) -> iterator {
  4628. iterator prev( *this );
  4629. operator++();
  4630. return prev;
  4631. }
  4632. auto operator ==( iterator const& other ) const -> bool {
  4633. return
  4634. m_pos == other.m_pos &&
  4635. m_stringIndex == other.m_stringIndex &&
  4636. &m_column == &other.m_column;
  4637. }
  4638. auto operator !=( iterator const& other ) const -> bool {
  4639. return !operator==( other );
  4640. }
  4641. };
  4642. using const_iterator = iterator;
  4643. explicit Column( std::string const& text ) { m_strings.push_back( text ); }
  4644. auto width( size_t newWidth ) -> Column& {
  4645. assert( newWidth > 0 );
  4646. m_width = newWidth;
  4647. return *this;
  4648. }
  4649. auto indent( size_t newIndent ) -> Column& {
  4650. m_indent = newIndent;
  4651. return *this;
  4652. }
  4653. auto initialIndent( size_t newIndent ) -> Column& {
  4654. m_initialIndent = newIndent;
  4655. return *this;
  4656. }
  4657. auto width() const -> size_t { return m_width; }
  4658. auto begin() const -> iterator { return iterator( *this ); }
  4659. auto end() const -> iterator { return { *this, m_strings.size() }; }
  4660. inline friend std::ostream& operator << ( std::ostream& os, Column const& col ) {
  4661. bool first = true;
  4662. for( auto line : col ) {
  4663. if( first )
  4664. first = false;
  4665. else
  4666. os << "\n";
  4667. os << line;
  4668. }
  4669. return os;
  4670. }
  4671. auto operator + ( Column const& other ) -> Columns;
  4672. auto toString() const -> std::string {
  4673. std::ostringstream oss;
  4674. oss << *this;
  4675. return oss.str();
  4676. }
  4677. };
  4678. class Spacer : public Column {
  4679. public:
  4680. explicit Spacer( size_t spaceWidth ) : Column( "" ) {
  4681. width( spaceWidth );
  4682. }
  4683. };
  4684. class Columns {
  4685. std::vector<Column> m_columns;
  4686. public:
  4687. class iterator {
  4688. friend Columns;
  4689. struct EndTag {};
  4690. std::vector<Column> const& m_columns;
  4691. std::vector<Column::iterator> m_iterators;
  4692. size_t m_activeIterators;
  4693. iterator( Columns const& columns, EndTag )
  4694. : m_columns( columns.m_columns ),
  4695. m_activeIterators( 0 )
  4696. {
  4697. m_iterators.reserve( m_columns.size() );
  4698. for( auto const& col : m_columns )
  4699. m_iterators.push_back( col.end() );
  4700. }
  4701. public:
  4702. explicit iterator( Columns const& columns )
  4703. : m_columns( columns.m_columns ),
  4704. m_activeIterators( m_columns.size() )
  4705. {
  4706. m_iterators.reserve( m_columns.size() );
  4707. for( auto const& col : m_columns )
  4708. m_iterators.push_back( col.begin() );
  4709. }
  4710. auto operator ==( iterator const& other ) const -> bool {
  4711. return m_iterators == other.m_iterators;
  4712. }
  4713. auto operator !=( iterator const& other ) const -> bool {
  4714. return m_iterators != other.m_iterators;
  4715. }
  4716. auto operator *() const -> std::string {
  4717. std::string row, padding;
  4718. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4719. auto width = m_columns[i].width();
  4720. if( m_iterators[i] != m_columns[i].end() ) {
  4721. std::string col = *m_iterators[i];
  4722. row += padding + col;
  4723. if( col.size() < width )
  4724. padding = std::string( width - col.size(), ' ' );
  4725. else
  4726. padding = "";
  4727. }
  4728. else {
  4729. padding += std::string( width, ' ' );
  4730. }
  4731. }
  4732. return row;
  4733. }
  4734. auto operator ++() -> iterator& {
  4735. for( size_t i = 0; i < m_columns.size(); ++i ) {
  4736. if (m_iterators[i] != m_columns[i].end())
  4737. ++m_iterators[i];
  4738. }
  4739. return *this;
  4740. }
  4741. auto operator ++(int) -> iterator {
  4742. iterator prev( *this );
  4743. operator++();
  4744. return prev;
  4745. }
  4746. };
  4747. using const_iterator = iterator;
  4748. auto begin() const -> iterator { return iterator( *this ); }
  4749. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  4750. auto operator += ( Column const& col ) -> Columns& {
  4751. m_columns.push_back( col );
  4752. return *this;
  4753. }
  4754. auto operator + ( Column const& col ) -> Columns {
  4755. Columns combined = *this;
  4756. combined += col;
  4757. return combined;
  4758. }
  4759. inline friend std::ostream& operator << ( std::ostream& os, Columns const& cols ) {
  4760. bool first = true;
  4761. for( auto line : cols ) {
  4762. if( first )
  4763. first = false;
  4764. else
  4765. os << "\n";
  4766. os << line;
  4767. }
  4768. return os;
  4769. }
  4770. auto toString() const -> std::string {
  4771. std::ostringstream oss;
  4772. oss << *this;
  4773. return oss.str();
  4774. }
  4775. };
  4776. inline auto Column::operator + ( Column const& other ) -> Columns {
  4777. Columns cols;
  4778. cols += *this;
  4779. cols += other;
  4780. return cols;
  4781. }
  4782. }}} // namespace Catch::clara::TextFlow
  4783. // ----------- end of #include from clara_textflow.hpp -----------
  4784. // ........... back in clara.hpp
  4785. #include <memory>
  4786. #include <set>
  4787. #include <algorithm>
  4788. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  4789. #define CATCH_PLATFORM_WINDOWS
  4790. #endif
  4791. namespace Catch { namespace clara {
  4792. namespace detail {
  4793. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  4794. template<typename L>
  4795. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  4796. template<typename ClassT, typename ReturnT, typename... Args>
  4797. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  4798. static const bool isValid = false;
  4799. };
  4800. template<typename ClassT, typename ReturnT, typename ArgT>
  4801. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  4802. static const bool isValid = true;
  4803. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  4804. using ReturnType = ReturnT;
  4805. };
  4806. class TokenStream;
  4807. // Transport for raw args (copied from main args, or supplied via init list for testing)
  4808. class Args {
  4809. friend TokenStream;
  4810. std::string m_exeName;
  4811. std::vector<std::string> m_args;
  4812. public:
  4813. Args( int argc, char const* const* argv )
  4814. : m_exeName(argv[0]),
  4815. m_args(argv + 1, argv + argc) {}
  4816. Args( std::initializer_list<std::string> args )
  4817. : m_exeName( *args.begin() ),
  4818. m_args( args.begin()+1, args.end() )
  4819. {}
  4820. auto exeName() const -> std::string {
  4821. return m_exeName;
  4822. }
  4823. };
  4824. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  4825. // may encode an option + its argument if the : or = form is used
  4826. enum class TokenType {
  4827. Option, Argument
  4828. };
  4829. struct Token {
  4830. TokenType type;
  4831. std::string token;
  4832. };
  4833. inline auto isOptPrefix( char c ) -> bool {
  4834. return c == '-'
  4835. #ifdef CATCH_PLATFORM_WINDOWS
  4836. || c == '/'
  4837. #endif
  4838. ;
  4839. }
  4840. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  4841. class TokenStream {
  4842. using Iterator = std::vector<std::string>::const_iterator;
  4843. Iterator it;
  4844. Iterator itEnd;
  4845. std::vector<Token> m_tokenBuffer;
  4846. void loadBuffer() {
  4847. m_tokenBuffer.resize( 0 );
  4848. // Skip any empty strings
  4849. while( it != itEnd && it->empty() )
  4850. ++it;
  4851. if( it != itEnd ) {
  4852. auto const &next = *it;
  4853. if( isOptPrefix( next[0] ) ) {
  4854. auto delimiterPos = next.find_first_of( " :=" );
  4855. if( delimiterPos != std::string::npos ) {
  4856. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  4857. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  4858. } else {
  4859. if( next[1] != '-' && next.size() > 2 ) {
  4860. std::string opt = "- ";
  4861. for( size_t i = 1; i < next.size(); ++i ) {
  4862. opt[1] = next[i];
  4863. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  4864. }
  4865. } else {
  4866. m_tokenBuffer.push_back( { TokenType::Option, next } );
  4867. }
  4868. }
  4869. } else {
  4870. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  4871. }
  4872. }
  4873. }
  4874. public:
  4875. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  4876. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  4877. loadBuffer();
  4878. }
  4879. explicit operator bool() const {
  4880. return !m_tokenBuffer.empty() || it != itEnd;
  4881. }
  4882. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  4883. auto operator*() const -> Token {
  4884. assert( !m_tokenBuffer.empty() );
  4885. return m_tokenBuffer.front();
  4886. }
  4887. auto operator->() const -> Token const * {
  4888. assert( !m_tokenBuffer.empty() );
  4889. return &m_tokenBuffer.front();
  4890. }
  4891. auto operator++() -> TokenStream & {
  4892. if( m_tokenBuffer.size() >= 2 ) {
  4893. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  4894. } else {
  4895. if( it != itEnd )
  4896. ++it;
  4897. loadBuffer();
  4898. }
  4899. return *this;
  4900. }
  4901. };
  4902. class ResultBase {
  4903. public:
  4904. enum Type {
  4905. Ok, LogicError, RuntimeError
  4906. };
  4907. protected:
  4908. ResultBase( Type type ) : m_type( type ) {}
  4909. virtual ~ResultBase() = default;
  4910. virtual void enforceOk() const = 0;
  4911. Type m_type;
  4912. };
  4913. template<typename T>
  4914. class ResultValueBase : public ResultBase {
  4915. public:
  4916. auto value() const -> T const & {
  4917. enforceOk();
  4918. return m_value;
  4919. }
  4920. protected:
  4921. ResultValueBase( Type type ) : ResultBase( type ) {}
  4922. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  4923. if( m_type == ResultBase::Ok )
  4924. new( &m_value ) T( other.m_value );
  4925. }
  4926. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  4927. new( &m_value ) T( value );
  4928. }
  4929. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  4930. if( m_type == ResultBase::Ok )
  4931. m_value.~T();
  4932. ResultBase::operator=(other);
  4933. if( m_type == ResultBase::Ok )
  4934. new( &m_value ) T( other.m_value );
  4935. return *this;
  4936. }
  4937. ~ResultValueBase() override {
  4938. if( m_type == Ok )
  4939. m_value.~T();
  4940. }
  4941. union {
  4942. T m_value;
  4943. };
  4944. };
  4945. template<>
  4946. class ResultValueBase<void> : public ResultBase {
  4947. protected:
  4948. using ResultBase::ResultBase;
  4949. };
  4950. template<typename T = void>
  4951. class BasicResult : public ResultValueBase<T> {
  4952. public:
  4953. template<typename U>
  4954. explicit BasicResult( BasicResult<U> const &other )
  4955. : ResultValueBase<T>( other.type() ),
  4956. m_errorMessage( other.errorMessage() )
  4957. {
  4958. assert( type() != ResultBase::Ok );
  4959. }
  4960. template<typename U>
  4961. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  4962. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  4963. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  4964. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  4965. explicit operator bool() const { return m_type == ResultBase::Ok; }
  4966. auto type() const -> ResultBase::Type { return m_type; }
  4967. auto errorMessage() const -> std::string { return m_errorMessage; }
  4968. protected:
  4969. void enforceOk() const override {
  4970. // Errors shouldn't reach this point, but if they do
  4971. // the actual error message will be in m_errorMessage
  4972. assert( m_type != ResultBase::LogicError );
  4973. assert( m_type != ResultBase::RuntimeError );
  4974. if( m_type != ResultBase::Ok )
  4975. std::abort();
  4976. }
  4977. std::string m_errorMessage; // Only populated if resultType is an error
  4978. BasicResult( ResultBase::Type type, std::string const &message )
  4979. : ResultValueBase<T>(type),
  4980. m_errorMessage(message)
  4981. {
  4982. assert( m_type != ResultBase::Ok );
  4983. }
  4984. using ResultValueBase<T>::ResultValueBase;
  4985. using ResultBase::m_type;
  4986. };
  4987. enum class ParseResultType {
  4988. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  4989. };
  4990. class ParseState {
  4991. public:
  4992. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  4993. : m_type(type),
  4994. m_remainingTokens( remainingTokens )
  4995. {}
  4996. auto type() const -> ParseResultType { return m_type; }
  4997. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  4998. private:
  4999. ParseResultType m_type;
  5000. TokenStream m_remainingTokens;
  5001. };
  5002. using Result = BasicResult<void>;
  5003. using ParserResult = BasicResult<ParseResultType>;
  5004. using InternalParseResult = BasicResult<ParseState>;
  5005. struct HelpColumns {
  5006. std::string left;
  5007. std::string right;
  5008. };
  5009. template<typename T>
  5010. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  5011. std::stringstream ss;
  5012. ss << source;
  5013. ss >> target;
  5014. if( ss.fail() )
  5015. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  5016. else
  5017. return ParserResult::ok( ParseResultType::Matched );
  5018. }
  5019. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  5020. target = source;
  5021. return ParserResult::ok( ParseResultType::Matched );
  5022. }
  5023. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  5024. std::string srcLC = source;
  5025. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( ::tolower(c) ); } );
  5026. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  5027. target = true;
  5028. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  5029. target = false;
  5030. else
  5031. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  5032. return ParserResult::ok( ParseResultType::Matched );
  5033. }
  5034. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  5035. template<typename T>
  5036. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  5037. T temp;
  5038. auto result = convertInto( source, temp );
  5039. if( result )
  5040. target = std::move(temp);
  5041. return result;
  5042. }
  5043. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  5044. struct NonCopyable {
  5045. NonCopyable() = default;
  5046. NonCopyable( NonCopyable const & ) = delete;
  5047. NonCopyable( NonCopyable && ) = delete;
  5048. NonCopyable &operator=( NonCopyable const & ) = delete;
  5049. NonCopyable &operator=( NonCopyable && ) = delete;
  5050. };
  5051. struct BoundRef : NonCopyable {
  5052. virtual ~BoundRef() = default;
  5053. virtual auto isContainer() const -> bool { return false; }
  5054. virtual auto isFlag() const -> bool { return false; }
  5055. };
  5056. struct BoundValueRefBase : BoundRef {
  5057. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  5058. };
  5059. struct BoundFlagRefBase : BoundRef {
  5060. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  5061. virtual auto isFlag() const -> bool { return true; }
  5062. };
  5063. template<typename T>
  5064. struct BoundValueRef : BoundValueRefBase {
  5065. T &m_ref;
  5066. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  5067. auto setValue( std::string const &arg ) -> ParserResult override {
  5068. return convertInto( arg, m_ref );
  5069. }
  5070. };
  5071. template<typename T>
  5072. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  5073. std::vector<T> &m_ref;
  5074. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  5075. auto isContainer() const -> bool override { return true; }
  5076. auto setValue( std::string const &arg ) -> ParserResult override {
  5077. T temp;
  5078. auto result = convertInto( arg, temp );
  5079. if( result )
  5080. m_ref.push_back( temp );
  5081. return result;
  5082. }
  5083. };
  5084. struct BoundFlagRef : BoundFlagRefBase {
  5085. bool &m_ref;
  5086. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  5087. auto setFlag( bool flag ) -> ParserResult override {
  5088. m_ref = flag;
  5089. return ParserResult::ok( ParseResultType::Matched );
  5090. }
  5091. };
  5092. template<typename ReturnType>
  5093. struct LambdaInvoker {
  5094. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  5095. template<typename L, typename ArgType>
  5096. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  5097. return lambda( arg );
  5098. }
  5099. };
  5100. template<>
  5101. struct LambdaInvoker<void> {
  5102. template<typename L, typename ArgType>
  5103. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  5104. lambda( arg );
  5105. return ParserResult::ok( ParseResultType::Matched );
  5106. }
  5107. };
  5108. template<typename ArgType, typename L>
  5109. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  5110. ArgType temp{};
  5111. auto result = convertInto( arg, temp );
  5112. return !result
  5113. ? result
  5114. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  5115. }
  5116. template<typename L>
  5117. struct BoundLambda : BoundValueRefBase {
  5118. L m_lambda;
  5119. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  5120. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  5121. auto setValue( std::string const &arg ) -> ParserResult override {
  5122. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  5123. }
  5124. };
  5125. template<typename L>
  5126. struct BoundFlagLambda : BoundFlagRefBase {
  5127. L m_lambda;
  5128. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  5129. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  5130. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  5131. auto setFlag( bool flag ) -> ParserResult override {
  5132. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  5133. }
  5134. };
  5135. enum class Optionality { Optional, Required };
  5136. struct Parser;
  5137. class ParserBase {
  5138. public:
  5139. virtual ~ParserBase() = default;
  5140. virtual auto validate() const -> Result { return Result::ok(); }
  5141. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  5142. virtual auto cardinality() const -> size_t { return 1; }
  5143. auto parse( Args const &args ) const -> InternalParseResult {
  5144. return parse( args.exeName(), TokenStream( args ) );
  5145. }
  5146. };
  5147. template<typename DerivedT>
  5148. class ComposableParserImpl : public ParserBase {
  5149. public:
  5150. template<typename T>
  5151. auto operator|( T const &other ) const -> Parser;
  5152. template<typename T>
  5153. auto operator+( T const &other ) const -> Parser;
  5154. };
  5155. // Common code and state for Args and Opts
  5156. template<typename DerivedT>
  5157. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  5158. protected:
  5159. Optionality m_optionality = Optionality::Optional;
  5160. std::shared_ptr<BoundRef> m_ref;
  5161. std::string m_hint;
  5162. std::string m_description;
  5163. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  5164. public:
  5165. template<typename T>
  5166. ParserRefImpl( T &ref, std::string const &hint )
  5167. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  5168. m_hint( hint )
  5169. {}
  5170. template<typename LambdaT>
  5171. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  5172. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  5173. m_hint(hint)
  5174. {}
  5175. auto operator()( std::string const &description ) -> DerivedT & {
  5176. m_description = description;
  5177. return static_cast<DerivedT &>( *this );
  5178. }
  5179. auto optional() -> DerivedT & {
  5180. m_optionality = Optionality::Optional;
  5181. return static_cast<DerivedT &>( *this );
  5182. };
  5183. auto required() -> DerivedT & {
  5184. m_optionality = Optionality::Required;
  5185. return static_cast<DerivedT &>( *this );
  5186. };
  5187. auto isOptional() const -> bool {
  5188. return m_optionality == Optionality::Optional;
  5189. }
  5190. auto cardinality() const -> size_t override {
  5191. if( m_ref->isContainer() )
  5192. return 0;
  5193. else
  5194. return 1;
  5195. }
  5196. auto hint() const -> std::string { return m_hint; }
  5197. };
  5198. class ExeName : public ComposableParserImpl<ExeName> {
  5199. std::shared_ptr<std::string> m_name;
  5200. std::shared_ptr<BoundValueRefBase> m_ref;
  5201. template<typename LambdaT>
  5202. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  5203. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  5204. }
  5205. public:
  5206. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  5207. explicit ExeName( std::string &ref ) : ExeName() {
  5208. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  5209. }
  5210. template<typename LambdaT>
  5211. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  5212. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  5213. }
  5214. // The exe name is not parsed out of the normal tokens, but is handled specially
  5215. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  5216. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  5217. }
  5218. auto name() const -> std::string { return *m_name; }
  5219. auto set( std::string const& newName ) -> ParserResult {
  5220. auto lastSlash = newName.find_last_of( "\\/" );
  5221. auto filename = ( lastSlash == std::string::npos )
  5222. ? newName
  5223. : newName.substr( lastSlash+1 );
  5224. *m_name = filename;
  5225. if( m_ref )
  5226. return m_ref->setValue( filename );
  5227. else
  5228. return ParserResult::ok( ParseResultType::Matched );
  5229. }
  5230. };
  5231. class Arg : public ParserRefImpl<Arg> {
  5232. public:
  5233. using ParserRefImpl::ParserRefImpl;
  5234. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  5235. auto validationResult = validate();
  5236. if( !validationResult )
  5237. return InternalParseResult( validationResult );
  5238. auto remainingTokens = tokens;
  5239. auto const &token = *remainingTokens;
  5240. if( token.type != TokenType::Argument )
  5241. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  5242. assert( !m_ref->isFlag() );
  5243. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  5244. auto result = valueRef->setValue( remainingTokens->token );
  5245. if( !result )
  5246. return InternalParseResult( result );
  5247. else
  5248. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  5249. }
  5250. };
  5251. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  5252. #ifdef CATCH_PLATFORM_WINDOWS
  5253. if( optName[0] == '/' )
  5254. return "-" + optName.substr( 1 );
  5255. else
  5256. #endif
  5257. return optName;
  5258. }
  5259. class Opt : public ParserRefImpl<Opt> {
  5260. protected:
  5261. std::vector<std::string> m_optNames;
  5262. public:
  5263. template<typename LambdaT>
  5264. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  5265. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  5266. template<typename LambdaT>
  5267. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  5268. template<typename T>
  5269. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  5270. auto operator[]( std::string const &optName ) -> Opt & {
  5271. m_optNames.push_back( optName );
  5272. return *this;
  5273. }
  5274. auto getHelpColumns() const -> std::vector<HelpColumns> {
  5275. std::ostringstream oss;
  5276. bool first = true;
  5277. for( auto const &opt : m_optNames ) {
  5278. if (first)
  5279. first = false;
  5280. else
  5281. oss << ", ";
  5282. oss << opt;
  5283. }
  5284. if( !m_hint.empty() )
  5285. oss << " <" << m_hint << ">";
  5286. return { { oss.str(), m_description } };
  5287. }
  5288. auto isMatch( std::string const &optToken ) const -> bool {
  5289. auto normalisedToken = normaliseOpt( optToken );
  5290. for( auto const &name : m_optNames ) {
  5291. if( normaliseOpt( name ) == normalisedToken )
  5292. return true;
  5293. }
  5294. return false;
  5295. }
  5296. using ParserBase::parse;
  5297. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  5298. auto validationResult = validate();
  5299. if( !validationResult )
  5300. return InternalParseResult( validationResult );
  5301. auto remainingTokens = tokens;
  5302. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  5303. auto const &token = *remainingTokens;
  5304. if( isMatch(token.token ) ) {
  5305. if( m_ref->isFlag() ) {
  5306. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  5307. auto result = flagRef->setFlag( true );
  5308. if( !result )
  5309. return InternalParseResult( result );
  5310. if( result.value() == ParseResultType::ShortCircuitAll )
  5311. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  5312. } else {
  5313. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  5314. ++remainingTokens;
  5315. if( !remainingTokens )
  5316. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  5317. auto const &argToken = *remainingTokens;
  5318. if( argToken.type != TokenType::Argument )
  5319. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  5320. auto result = valueRef->setValue( argToken.token );
  5321. if( !result )
  5322. return InternalParseResult( result );
  5323. if( result.value() == ParseResultType::ShortCircuitAll )
  5324. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  5325. }
  5326. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  5327. }
  5328. }
  5329. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  5330. }
  5331. auto validate() const -> Result override {
  5332. if( m_optNames.empty() )
  5333. return Result::logicError( "No options supplied to Opt" );
  5334. for( auto const &name : m_optNames ) {
  5335. if( name.empty() )
  5336. return Result::logicError( "Option name cannot be empty" );
  5337. #ifdef CATCH_PLATFORM_WINDOWS
  5338. if( name[0] != '-' && name[0] != '/' )
  5339. return Result::logicError( "Option name must begin with '-' or '/'" );
  5340. #else
  5341. if( name[0] != '-' )
  5342. return Result::logicError( "Option name must begin with '-'" );
  5343. #endif
  5344. }
  5345. return ParserRefImpl::validate();
  5346. }
  5347. };
  5348. struct Help : Opt {
  5349. Help( bool &showHelpFlag )
  5350. : Opt([&]( bool flag ) {
  5351. showHelpFlag = flag;
  5352. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  5353. })
  5354. {
  5355. static_cast<Opt &>( *this )
  5356. ("display usage information")
  5357. ["-?"]["-h"]["--help"]
  5358. .optional();
  5359. }
  5360. };
  5361. struct Parser : ParserBase {
  5362. mutable ExeName m_exeName;
  5363. std::vector<Opt> m_options;
  5364. std::vector<Arg> m_args;
  5365. auto operator|=( ExeName const &exeName ) -> Parser & {
  5366. m_exeName = exeName;
  5367. return *this;
  5368. }
  5369. auto operator|=( Arg const &arg ) -> Parser & {
  5370. m_args.push_back(arg);
  5371. return *this;
  5372. }
  5373. auto operator|=( Opt const &opt ) -> Parser & {
  5374. m_options.push_back(opt);
  5375. return *this;
  5376. }
  5377. auto operator|=( Parser const &other ) -> Parser & {
  5378. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  5379. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  5380. return *this;
  5381. }
  5382. template<typename T>
  5383. auto operator|( T const &other ) const -> Parser {
  5384. return Parser( *this ) |= other;
  5385. }
  5386. // Forward deprecated interface with '+' instead of '|'
  5387. template<typename T>
  5388. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  5389. template<typename T>
  5390. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  5391. auto getHelpColumns() const -> std::vector<HelpColumns> {
  5392. std::vector<HelpColumns> cols;
  5393. for (auto const &o : m_options) {
  5394. auto childCols = o.getHelpColumns();
  5395. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  5396. }
  5397. return cols;
  5398. }
  5399. void writeToStream( std::ostream &os ) const {
  5400. if (!m_exeName.name().empty()) {
  5401. os << "usage:\n" << " " << m_exeName.name() << " ";
  5402. bool required = true, first = true;
  5403. for( auto const &arg : m_args ) {
  5404. if (first)
  5405. first = false;
  5406. else
  5407. os << " ";
  5408. if( arg.isOptional() && required ) {
  5409. os << "[";
  5410. required = false;
  5411. }
  5412. os << "<" << arg.hint() << ">";
  5413. if( arg.cardinality() == 0 )
  5414. os << " ... ";
  5415. }
  5416. if( !required )
  5417. os << "]";
  5418. if( !m_options.empty() )
  5419. os << " options";
  5420. os << "\n\nwhere options are:" << std::endl;
  5421. }
  5422. auto rows = getHelpColumns();
  5423. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  5424. size_t optWidth = 0;
  5425. for( auto const &cols : rows )
  5426. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  5427. optWidth = (std::min)(optWidth, consoleWidth/2);
  5428. for( auto const &cols : rows ) {
  5429. auto row =
  5430. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  5431. TextFlow::Spacer(4) +
  5432. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  5433. os << row << std::endl;
  5434. }
  5435. }
  5436. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  5437. parser.writeToStream( os );
  5438. return os;
  5439. }
  5440. auto validate() const -> Result override {
  5441. for( auto const &opt : m_options ) {
  5442. auto result = opt.validate();
  5443. if( !result )
  5444. return result;
  5445. }
  5446. for( auto const &arg : m_args ) {
  5447. auto result = arg.validate();
  5448. if( !result )
  5449. return result;
  5450. }
  5451. return Result::ok();
  5452. }
  5453. using ParserBase::parse;
  5454. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  5455. struct ParserInfo {
  5456. ParserBase const* parser = nullptr;
  5457. size_t count = 0;
  5458. };
  5459. const size_t totalParsers = m_options.size() + m_args.size();
  5460. assert( totalParsers < 512 );
  5461. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  5462. ParserInfo parseInfos[512];
  5463. {
  5464. size_t i = 0;
  5465. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  5466. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  5467. }
  5468. m_exeName.set( exeName );
  5469. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  5470. while( result.value().remainingTokens() ) {
  5471. bool tokenParsed = false;
  5472. for( size_t i = 0; i < totalParsers; ++i ) {
  5473. auto& parseInfo = parseInfos[i];
  5474. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  5475. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  5476. if (!result)
  5477. return result;
  5478. if (result.value().type() != ParseResultType::NoMatch) {
  5479. tokenParsed = true;
  5480. ++parseInfo.count;
  5481. break;
  5482. }
  5483. }
  5484. }
  5485. if( result.value().type() == ParseResultType::ShortCircuitAll )
  5486. return result;
  5487. if( !tokenParsed )
  5488. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  5489. }
  5490. // !TBD Check missing required options
  5491. return result;
  5492. }
  5493. };
  5494. template<typename DerivedT>
  5495. template<typename T>
  5496. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  5497. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  5498. }
  5499. } // namespace detail
  5500. // A Combined parser
  5501. using detail::Parser;
  5502. // A parser for options
  5503. using detail::Opt;
  5504. // A parser for arguments
  5505. using detail::Arg;
  5506. // Wrapper for argc, argv from main()
  5507. using detail::Args;
  5508. // Specifies the name of the executable
  5509. using detail::ExeName;
  5510. // Convenience wrapper for option parser that specifies the help option
  5511. using detail::Help;
  5512. // enum of result types from a parse
  5513. using detail::ParseResultType;
  5514. // Result type for parser operation
  5515. using detail::ParserResult;
  5516. }} // namespace Catch::clara
  5517. // end clara.hpp
  5518. #ifdef __clang__
  5519. #pragma clang diagnostic pop
  5520. #endif
  5521. // Restore Clara's value for console width, if present
  5522. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5523. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5524. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5525. #endif
  5526. // end catch_clara.h
  5527. namespace Catch {
  5528. clara::Parser makeCommandLineParser( ConfigData& config );
  5529. } // end namespace Catch
  5530. // end catch_commandline.h
  5531. #include <fstream>
  5532. #include <ctime>
  5533. namespace Catch {
  5534. clara::Parser makeCommandLineParser( ConfigData& config ) {
  5535. using namespace clara;
  5536. auto const setWarning = [&]( std::string const& warning ) {
  5537. auto warningSet = [&]() {
  5538. if( warning == "NoAssertions" )
  5539. return WarnAbout::NoAssertions;
  5540. if ( warning == "NoTests" )
  5541. return WarnAbout::NoTests;
  5542. return WarnAbout::Nothing;
  5543. }();
  5544. if (warningSet == WarnAbout::Nothing)
  5545. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  5546. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  5547. return ParserResult::ok( ParseResultType::Matched );
  5548. };
  5549. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  5550. std::ifstream f( filename.c_str() );
  5551. if( !f.is_open() )
  5552. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  5553. std::string line;
  5554. while( std::getline( f, line ) ) {
  5555. line = trim(line);
  5556. if( !line.empty() && !startsWith( line, '#' ) ) {
  5557. if( !startsWith( line, '"' ) )
  5558. line = '"' + line + '"';
  5559. config.testsOrTags.push_back( line + ',' );
  5560. }
  5561. }
  5562. return ParserResult::ok( ParseResultType::Matched );
  5563. };
  5564. auto const setTestOrder = [&]( std::string const& order ) {
  5565. if( startsWith( "declared", order ) )
  5566. config.runOrder = RunTests::InDeclarationOrder;
  5567. else if( startsWith( "lexical", order ) )
  5568. config.runOrder = RunTests::InLexicographicalOrder;
  5569. else if( startsWith( "random", order ) )
  5570. config.runOrder = RunTests::InRandomOrder;
  5571. else
  5572. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  5573. return ParserResult::ok( ParseResultType::Matched );
  5574. };
  5575. auto const setRngSeed = [&]( std::string const& seed ) {
  5576. if( seed != "time" )
  5577. return clara::detail::convertInto( seed, config.rngSeed );
  5578. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  5579. return ParserResult::ok( ParseResultType::Matched );
  5580. };
  5581. auto const setColourUsage = [&]( std::string const& useColour ) {
  5582. auto mode = toLower( useColour );
  5583. if( mode == "yes" )
  5584. config.useColour = UseColour::Yes;
  5585. else if( mode == "no" )
  5586. config.useColour = UseColour::No;
  5587. else if( mode == "auto" )
  5588. config.useColour = UseColour::Auto;
  5589. else
  5590. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  5591. return ParserResult::ok( ParseResultType::Matched );
  5592. };
  5593. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  5594. auto keypressLc = toLower( keypress );
  5595. if( keypressLc == "start" )
  5596. config.waitForKeypress = WaitForKeypress::BeforeStart;
  5597. else if( keypressLc == "exit" )
  5598. config.waitForKeypress = WaitForKeypress::BeforeExit;
  5599. else if( keypressLc == "both" )
  5600. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  5601. else
  5602. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  5603. return ParserResult::ok( ParseResultType::Matched );
  5604. };
  5605. auto const setVerbosity = [&]( std::string const& verbosity ) {
  5606. auto lcVerbosity = toLower( verbosity );
  5607. if( lcVerbosity == "quiet" )
  5608. config.verbosity = Verbosity::Quiet;
  5609. else if( lcVerbosity == "normal" )
  5610. config.verbosity = Verbosity::Normal;
  5611. else if( lcVerbosity == "high" )
  5612. config.verbosity = Verbosity::High;
  5613. else
  5614. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  5615. return ParserResult::ok( ParseResultType::Matched );
  5616. };
  5617. auto cli
  5618. = ExeName( config.processName )
  5619. | Help( config.showHelp )
  5620. | Opt( config.listTests )
  5621. ["-l"]["--list-tests"]
  5622. ( "list all/matching test cases" )
  5623. | Opt( config.listTags )
  5624. ["-t"]["--list-tags"]
  5625. ( "list all/matching tags" )
  5626. | Opt( config.showSuccessfulTests )
  5627. ["-s"]["--success"]
  5628. ( "include successful tests in output" )
  5629. | Opt( config.shouldDebugBreak )
  5630. ["-b"]["--break"]
  5631. ( "break into debugger on failure" )
  5632. | Opt( config.noThrow )
  5633. ["-e"]["--nothrow"]
  5634. ( "skip exception tests" )
  5635. | Opt( config.showInvisibles )
  5636. ["-i"]["--invisibles"]
  5637. ( "show invisibles (tabs, newlines)" )
  5638. | Opt( config.outputFilename, "filename" )
  5639. ["-o"]["--out"]
  5640. ( "output filename" )
  5641. | Opt( config.reporterName, "name" )
  5642. ["-r"]["--reporter"]
  5643. ( "reporter to use (defaults to console)" )
  5644. | Opt( config.name, "name" )
  5645. ["-n"]["--name"]
  5646. ( "suite name" )
  5647. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  5648. ["-a"]["--abort"]
  5649. ( "abort at first failure" )
  5650. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  5651. ["-x"]["--abortx"]
  5652. ( "abort after x failures" )
  5653. | Opt( setWarning, "warning name" )
  5654. ["-w"]["--warn"]
  5655. ( "enable warnings" )
  5656. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  5657. ["-d"]["--durations"]
  5658. ( "show test durations" )
  5659. | Opt( loadTestNamesFromFile, "filename" )
  5660. ["-f"]["--input-file"]
  5661. ( "load test names to run from a file" )
  5662. | Opt( config.filenamesAsTags )
  5663. ["-#"]["--filenames-as-tags"]
  5664. ( "adds a tag for the filename" )
  5665. | Opt( config.sectionsToRun, "section name" )
  5666. ["-c"]["--section"]
  5667. ( "specify section to run" )
  5668. | Opt( setVerbosity, "quiet|normal|high" )
  5669. ["-v"]["--verbosity"]
  5670. ( "set output verbosity" )
  5671. | Opt( config.listTestNamesOnly )
  5672. ["--list-test-names-only"]
  5673. ( "list all/matching test cases names only" )
  5674. | Opt( config.listReporters )
  5675. ["--list-reporters"]
  5676. ( "list all reporters" )
  5677. | Opt( setTestOrder, "decl|lex|rand" )
  5678. ["--order"]
  5679. ( "test case order (defaults to decl)" )
  5680. | Opt( setRngSeed, "'time'|number" )
  5681. ["--rng-seed"]
  5682. ( "set a specific seed for random numbers" )
  5683. | Opt( setColourUsage, "yes|no" )
  5684. ["--use-colour"]
  5685. ( "should output be colourised" )
  5686. | Opt( config.libIdentify )
  5687. ["--libidentify"]
  5688. ( "report name and version according to libidentify standard" )
  5689. | Opt( setWaitForKeypress, "start|exit|both" )
  5690. ["--wait-for-keypress"]
  5691. ( "waits for a keypress before exiting" )
  5692. | Opt( config.benchmarkResolutionMultiple, "multiplier" )
  5693. ["--benchmark-resolution-multiple"]
  5694. ( "multiple of clock resolution to run benchmarks" )
  5695. | Arg( config.testsOrTags, "test name|pattern|tags" )
  5696. ( "which test or tests to use" );
  5697. return cli;
  5698. }
  5699. } // end namespace Catch
  5700. // end catch_commandline.cpp
  5701. // start catch_common.cpp
  5702. #include <cstring>
  5703. #include <ostream>
  5704. namespace Catch {
  5705. bool SourceLineInfo::empty() const noexcept {
  5706. return file[0] == '\0';
  5707. }
  5708. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  5709. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  5710. }
  5711. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  5712. // We can assume that the same file will usually have the same pointer.
  5713. // Thus, if the pointers are the same, there is no point in calling the strcmp
  5714. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  5715. }
  5716. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  5717. #ifndef __GNUG__
  5718. os << info.file << '(' << info.line << ')';
  5719. #else
  5720. os << info.file << ':' << info.line;
  5721. #endif
  5722. return os;
  5723. }
  5724. std::string StreamEndStop::operator+() const {
  5725. return std::string();
  5726. }
  5727. NonCopyable::NonCopyable() = default;
  5728. NonCopyable::~NonCopyable() = default;
  5729. }
  5730. // end catch_common.cpp
  5731. // start catch_config.cpp
  5732. namespace Catch {
  5733. Config::Config( ConfigData const& data )
  5734. : m_data( data ),
  5735. m_stream( openStream() )
  5736. {
  5737. TestSpecParser parser(ITagAliasRegistry::get());
  5738. if (data.testsOrTags.empty()) {
  5739. parser.parse("~[.]"); // All not hidden tests
  5740. }
  5741. else {
  5742. m_hasTestFilters = true;
  5743. for( auto const& testOrTags : data.testsOrTags )
  5744. parser.parse( testOrTags );
  5745. }
  5746. m_testSpec = parser.testSpec();
  5747. }
  5748. std::string const& Config::getFilename() const {
  5749. return m_data.outputFilename ;
  5750. }
  5751. bool Config::listTests() const { return m_data.listTests; }
  5752. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  5753. bool Config::listTags() const { return m_data.listTags; }
  5754. bool Config::listReporters() const { return m_data.listReporters; }
  5755. std::string Config::getProcessName() const { return m_data.processName; }
  5756. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  5757. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  5758. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  5759. TestSpec const& Config::testSpec() const { return m_testSpec; }
  5760. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  5761. bool Config::showHelp() const { return m_data.showHelp; }
  5762. // IConfig interface
  5763. bool Config::allowThrows() const { return !m_data.noThrow; }
  5764. std::ostream& Config::stream() const { return m_stream->stream(); }
  5765. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  5766. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  5767. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  5768. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  5769. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  5770. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  5771. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  5772. int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
  5773. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  5774. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  5775. int Config::abortAfter() const { return m_data.abortAfter; }
  5776. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  5777. Verbosity Config::verbosity() const { return m_data.verbosity; }
  5778. IStream const* Config::openStream() {
  5779. return Catch::makeStream(m_data.outputFilename);
  5780. }
  5781. } // end namespace Catch
  5782. // end catch_config.cpp
  5783. // start catch_console_colour.cpp
  5784. #if defined(__clang__)
  5785. # pragma clang diagnostic push
  5786. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  5787. #endif
  5788. // start catch_errno_guard.h
  5789. namespace Catch {
  5790. class ErrnoGuard {
  5791. public:
  5792. ErrnoGuard();
  5793. ~ErrnoGuard();
  5794. private:
  5795. int m_oldErrno;
  5796. };
  5797. }
  5798. // end catch_errno_guard.h
  5799. #include <sstream>
  5800. namespace Catch {
  5801. namespace {
  5802. struct IColourImpl {
  5803. virtual ~IColourImpl() = default;
  5804. virtual void use( Colour::Code _colourCode ) = 0;
  5805. };
  5806. struct NoColourImpl : IColourImpl {
  5807. void use( Colour::Code ) {}
  5808. static IColourImpl* instance() {
  5809. static NoColourImpl s_instance;
  5810. return &s_instance;
  5811. }
  5812. };
  5813. } // anon namespace
  5814. } // namespace Catch
  5815. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  5816. # ifdef CATCH_PLATFORM_WINDOWS
  5817. # define CATCH_CONFIG_COLOUR_WINDOWS
  5818. # else
  5819. # define CATCH_CONFIG_COLOUR_ANSI
  5820. # endif
  5821. #endif
  5822. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  5823. namespace Catch {
  5824. namespace {
  5825. class Win32ColourImpl : public IColourImpl {
  5826. public:
  5827. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  5828. {
  5829. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  5830. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  5831. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  5832. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  5833. }
  5834. virtual void use( Colour::Code _colourCode ) override {
  5835. switch( _colourCode ) {
  5836. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  5837. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5838. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  5839. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  5840. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  5841. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  5842. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  5843. case Colour::Grey: return setTextAttribute( 0 );
  5844. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  5845. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  5846. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  5847. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5848. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  5849. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5850. default:
  5851. CATCH_ERROR( "Unknown colour requested" );
  5852. }
  5853. }
  5854. private:
  5855. void setTextAttribute( WORD _textAttribute ) {
  5856. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  5857. }
  5858. HANDLE stdoutHandle;
  5859. WORD originalForegroundAttributes;
  5860. WORD originalBackgroundAttributes;
  5861. };
  5862. IColourImpl* platformColourInstance() {
  5863. static Win32ColourImpl s_instance;
  5864. IConfigPtr config = getCurrentContext().getConfig();
  5865. UseColour::YesOrNo colourMode = config
  5866. ? config->useColour()
  5867. : UseColour::Auto;
  5868. if( colourMode == UseColour::Auto )
  5869. colourMode = UseColour::Yes;
  5870. return colourMode == UseColour::Yes
  5871. ? &s_instance
  5872. : NoColourImpl::instance();
  5873. }
  5874. } // end anon namespace
  5875. } // end namespace Catch
  5876. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  5877. #include <unistd.h>
  5878. namespace Catch {
  5879. namespace {
  5880. // use POSIX/ ANSI console terminal codes
  5881. // Thanks to Adam Strzelecki for original contribution
  5882. // (http://github.com/nanoant)
  5883. // https://github.com/philsquared/Catch/pull/131
  5884. class PosixColourImpl : public IColourImpl {
  5885. public:
  5886. virtual void use( Colour::Code _colourCode ) override {
  5887. switch( _colourCode ) {
  5888. case Colour::None:
  5889. case Colour::White: return setColour( "[0m" );
  5890. case Colour::Red: return setColour( "[0;31m" );
  5891. case Colour::Green: return setColour( "[0;32m" );
  5892. case Colour::Blue: return setColour( "[0;34m" );
  5893. case Colour::Cyan: return setColour( "[0;36m" );
  5894. case Colour::Yellow: return setColour( "[0;33m" );
  5895. case Colour::Grey: return setColour( "[1;30m" );
  5896. case Colour::LightGrey: return setColour( "[0;37m" );
  5897. case Colour::BrightRed: return setColour( "[1;31m" );
  5898. case Colour::BrightGreen: return setColour( "[1;32m" );
  5899. case Colour::BrightWhite: return setColour( "[1;37m" );
  5900. case Colour::BrightYellow: return setColour( "[1;33m" );
  5901. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5902. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  5903. }
  5904. }
  5905. static IColourImpl* instance() {
  5906. static PosixColourImpl s_instance;
  5907. return &s_instance;
  5908. }
  5909. private:
  5910. void setColour( const char* _escapeCode ) {
  5911. Catch::cout() << '\033' << _escapeCode;
  5912. }
  5913. };
  5914. bool useColourOnPlatform() {
  5915. return
  5916. #ifdef CATCH_PLATFORM_MAC
  5917. !isDebuggerActive() &&
  5918. #endif
  5919. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  5920. isatty(STDOUT_FILENO)
  5921. #else
  5922. false
  5923. #endif
  5924. ;
  5925. }
  5926. IColourImpl* platformColourInstance() {
  5927. ErrnoGuard guard;
  5928. IConfigPtr config = getCurrentContext().getConfig();
  5929. UseColour::YesOrNo colourMode = config
  5930. ? config->useColour()
  5931. : UseColour::Auto;
  5932. if( colourMode == UseColour::Auto )
  5933. colourMode = useColourOnPlatform()
  5934. ? UseColour::Yes
  5935. : UseColour::No;
  5936. return colourMode == UseColour::Yes
  5937. ? PosixColourImpl::instance()
  5938. : NoColourImpl::instance();
  5939. }
  5940. } // end anon namespace
  5941. } // end namespace Catch
  5942. #else // not Windows or ANSI ///////////////////////////////////////////////
  5943. namespace Catch {
  5944. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  5945. } // end namespace Catch
  5946. #endif // Windows/ ANSI/ None
  5947. namespace Catch {
  5948. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  5949. Colour::Colour( Colour&& rhs ) noexcept {
  5950. m_moved = rhs.m_moved;
  5951. rhs.m_moved = true;
  5952. }
  5953. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  5954. m_moved = rhs.m_moved;
  5955. rhs.m_moved = true;
  5956. return *this;
  5957. }
  5958. Colour::~Colour(){ if( !m_moved ) use( None ); }
  5959. void Colour::use( Code _colourCode ) {
  5960. static IColourImpl* impl = platformColourInstance();
  5961. impl->use( _colourCode );
  5962. }
  5963. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  5964. return os;
  5965. }
  5966. } // end namespace Catch
  5967. #if defined(__clang__)
  5968. # pragma clang diagnostic pop
  5969. #endif
  5970. // end catch_console_colour.cpp
  5971. // start catch_context.cpp
  5972. namespace Catch {
  5973. class Context : public IMutableContext, NonCopyable {
  5974. public: // IContext
  5975. virtual IResultCapture* getResultCapture() override {
  5976. return m_resultCapture;
  5977. }
  5978. virtual IRunner* getRunner() override {
  5979. return m_runner;
  5980. }
  5981. virtual IConfigPtr const& getConfig() const override {
  5982. return m_config;
  5983. }
  5984. virtual ~Context() override;
  5985. public: // IMutableContext
  5986. virtual void setResultCapture( IResultCapture* resultCapture ) override {
  5987. m_resultCapture = resultCapture;
  5988. }
  5989. virtual void setRunner( IRunner* runner ) override {
  5990. m_runner = runner;
  5991. }
  5992. virtual void setConfig( IConfigPtr const& config ) override {
  5993. m_config = config;
  5994. }
  5995. friend IMutableContext& getCurrentMutableContext();
  5996. private:
  5997. IConfigPtr m_config;
  5998. IRunner* m_runner = nullptr;
  5999. IResultCapture* m_resultCapture = nullptr;
  6000. };
  6001. IMutableContext *IMutableContext::currentContext = nullptr;
  6002. void IMutableContext::createContext()
  6003. {
  6004. currentContext = new Context();
  6005. }
  6006. void cleanUpContext() {
  6007. delete IMutableContext::currentContext;
  6008. IMutableContext::currentContext = nullptr;
  6009. }
  6010. IContext::~IContext() = default;
  6011. IMutableContext::~IMutableContext() = default;
  6012. Context::~Context() = default;
  6013. }
  6014. // end catch_context.cpp
  6015. // start catch_debug_console.cpp
  6016. // start catch_debug_console.h
  6017. #include <string>
  6018. namespace Catch {
  6019. void writeToDebugConsole( std::string const& text );
  6020. }
  6021. // end catch_debug_console.h
  6022. #ifdef CATCH_PLATFORM_WINDOWS
  6023. namespace Catch {
  6024. void writeToDebugConsole( std::string const& text ) {
  6025. ::OutputDebugStringA( text.c_str() );
  6026. }
  6027. }
  6028. #else
  6029. namespace Catch {
  6030. void writeToDebugConsole( std::string const& text ) {
  6031. // !TBD: Need a version for Mac/ XCode and other IDEs
  6032. Catch::cout() << text;
  6033. }
  6034. }
  6035. #endif // Platform
  6036. // end catch_debug_console.cpp
  6037. // start catch_debugger.cpp
  6038. #ifdef CATCH_PLATFORM_MAC
  6039. # include <assert.h>
  6040. # include <stdbool.h>
  6041. # include <sys/types.h>
  6042. # include <unistd.h>
  6043. # include <sys/sysctl.h>
  6044. # include <cstddef>
  6045. # include <ostream>
  6046. namespace Catch {
  6047. // The following function is taken directly from the following technical note:
  6048. // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  6049. // Returns true if the current process is being debugged (either
  6050. // running under the debugger or has a debugger attached post facto).
  6051. bool isDebuggerActive(){
  6052. int mib[4];
  6053. struct kinfo_proc info;
  6054. std::size_t size;
  6055. // Initialize the flags so that, if sysctl fails for some bizarre
  6056. // reason, we get a predictable result.
  6057. info.kp_proc.p_flag = 0;
  6058. // Initialize mib, which tells sysctl the info we want, in this case
  6059. // we're looking for information about a specific process ID.
  6060. mib[0] = CTL_KERN;
  6061. mib[1] = KERN_PROC;
  6062. mib[2] = KERN_PROC_PID;
  6063. mib[3] = getpid();
  6064. // Call sysctl.
  6065. size = sizeof(info);
  6066. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  6067. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  6068. return false;
  6069. }
  6070. // We're being debugged if the P_TRACED flag is set.
  6071. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  6072. }
  6073. } // namespace Catch
  6074. #elif defined(CATCH_PLATFORM_LINUX)
  6075. #include <fstream>
  6076. #include <string>
  6077. namespace Catch{
  6078. // The standard POSIX way of detecting a debugger is to attempt to
  6079. // ptrace() the process, but this needs to be done from a child and not
  6080. // this process itself to still allow attaching to this process later
  6081. // if wanted, so is rather heavy. Under Linux we have the PID of the
  6082. // "debugger" (which doesn't need to be gdb, of course, it could also
  6083. // be strace, for example) in /proc/$PID/status, so just get it from
  6084. // there instead.
  6085. bool isDebuggerActive(){
  6086. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  6087. // This way our users can properly assert over errno values
  6088. ErrnoGuard guard;
  6089. std::ifstream in("/proc/self/status");
  6090. for( std::string line; std::getline(in, line); ) {
  6091. static const int PREFIX_LEN = 11;
  6092. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  6093. // We're traced if the PID is not 0 and no other PID starts
  6094. // with 0 digit, so it's enough to check for just a single
  6095. // character.
  6096. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  6097. }
  6098. }
  6099. return false;
  6100. }
  6101. } // namespace Catch
  6102. #elif defined(_MSC_VER)
  6103. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  6104. namespace Catch {
  6105. bool isDebuggerActive() {
  6106. return IsDebuggerPresent() != 0;
  6107. }
  6108. }
  6109. #elif defined(__MINGW32__)
  6110. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  6111. namespace Catch {
  6112. bool isDebuggerActive() {
  6113. return IsDebuggerPresent() != 0;
  6114. }
  6115. }
  6116. #else
  6117. namespace Catch {
  6118. bool isDebuggerActive() { return false; }
  6119. }
  6120. #endif // Platform
  6121. // end catch_debugger.cpp
  6122. // start catch_decomposer.cpp
  6123. namespace Catch {
  6124. ITransientExpression::~ITransientExpression() = default;
  6125. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  6126. if( lhs.size() + rhs.size() < 40 &&
  6127. lhs.find('\n') == std::string::npos &&
  6128. rhs.find('\n') == std::string::npos )
  6129. os << lhs << " " << op << " " << rhs;
  6130. else
  6131. os << lhs << "\n" << op << "\n" << rhs;
  6132. }
  6133. }
  6134. // end catch_decomposer.cpp
  6135. // start catch_enforce.cpp
  6136. namespace Catch {
  6137. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  6138. [[noreturn]]
  6139. void throw_exception(std::exception const& e) {
  6140. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  6141. << "The message was: " << e.what() << '\n';
  6142. std::terminate();
  6143. }
  6144. #endif
  6145. } // namespace Catch;
  6146. // end catch_enforce.cpp
  6147. // start catch_errno_guard.cpp
  6148. #include <cerrno>
  6149. namespace Catch {
  6150. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  6151. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  6152. }
  6153. // end catch_errno_guard.cpp
  6154. // start catch_exception_translator_registry.cpp
  6155. // start catch_exception_translator_registry.h
  6156. #include <vector>
  6157. #include <string>
  6158. #include <memory>
  6159. namespace Catch {
  6160. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  6161. public:
  6162. ~ExceptionTranslatorRegistry();
  6163. virtual void registerTranslator( const IExceptionTranslator* translator );
  6164. virtual std::string translateActiveException() const override;
  6165. std::string tryTranslators() const;
  6166. private:
  6167. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  6168. };
  6169. }
  6170. // end catch_exception_translator_registry.h
  6171. #ifdef __OBJC__
  6172. #import "Foundation/Foundation.h"
  6173. #endif
  6174. namespace Catch {
  6175. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  6176. }
  6177. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  6178. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  6179. }
  6180. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6181. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  6182. try {
  6183. #ifdef __OBJC__
  6184. // In Objective-C try objective-c exceptions first
  6185. @try {
  6186. return tryTranslators();
  6187. }
  6188. @catch (NSException *exception) {
  6189. return Catch::Detail::stringify( [exception description] );
  6190. }
  6191. #else
  6192. // Compiling a mixed mode project with MSVC means that CLR
  6193. // exceptions will be caught in (...) as well. However, these
  6194. // do not fill-in std::current_exception and thus lead to crash
  6195. // when attempting rethrow.
  6196. // /EHa switch also causes structured exceptions to be caught
  6197. // here, but they fill-in current_exception properly, so
  6198. // at worst the output should be a little weird, instead of
  6199. // causing a crash.
  6200. if (std::current_exception() == nullptr) {
  6201. return "Non C++ exception. Possibly a CLR exception.";
  6202. }
  6203. return tryTranslators();
  6204. #endif
  6205. }
  6206. catch( TestFailureException& ) {
  6207. std::rethrow_exception(std::current_exception());
  6208. }
  6209. catch( std::exception& ex ) {
  6210. return ex.what();
  6211. }
  6212. catch( std::string& msg ) {
  6213. return msg;
  6214. }
  6215. catch( const char* msg ) {
  6216. return msg;
  6217. }
  6218. catch(...) {
  6219. return "Unknown exception";
  6220. }
  6221. }
  6222. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  6223. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  6224. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  6225. }
  6226. #endif
  6227. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  6228. if( m_translators.empty() )
  6229. std::rethrow_exception(std::current_exception());
  6230. else
  6231. return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() );
  6232. }
  6233. }
  6234. // end catch_exception_translator_registry.cpp
  6235. // start catch_fatal_condition.cpp
  6236. #if defined(__GNUC__)
  6237. # pragma GCC diagnostic push
  6238. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  6239. #endif
  6240. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  6241. namespace {
  6242. // Report the error condition
  6243. void reportFatal( char const * const message ) {
  6244. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  6245. }
  6246. }
  6247. #endif // signals/SEH handling
  6248. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  6249. namespace Catch {
  6250. struct SignalDefs { DWORD id; const char* name; };
  6251. // There is no 1-1 mapping between signals and windows exceptions.
  6252. // Windows can easily distinguish between SO and SigSegV,
  6253. // but SigInt, SigTerm, etc are handled differently.
  6254. static SignalDefs signalDefs[] = {
  6255. { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
  6256. { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
  6257. { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
  6258. { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
  6259. };
  6260. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  6261. for (auto const& def : signalDefs) {
  6262. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  6263. reportFatal(def.name);
  6264. }
  6265. }
  6266. // If its not an exception we care about, pass it along.
  6267. // This stops us from eating debugger breaks etc.
  6268. return EXCEPTION_CONTINUE_SEARCH;
  6269. }
  6270. FatalConditionHandler::FatalConditionHandler() {
  6271. isSet = true;
  6272. // 32k seems enough for Catch to handle stack overflow,
  6273. // but the value was found experimentally, so there is no strong guarantee
  6274. guaranteeSize = 32 * 1024;
  6275. exceptionHandlerHandle = nullptr;
  6276. // Register as first handler in current chain
  6277. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  6278. // Pass in guarantee size to be filled
  6279. SetThreadStackGuarantee(&guaranteeSize);
  6280. }
  6281. void FatalConditionHandler::reset() {
  6282. if (isSet) {
  6283. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  6284. SetThreadStackGuarantee(&guaranteeSize);
  6285. exceptionHandlerHandle = nullptr;
  6286. isSet = false;
  6287. }
  6288. }
  6289. FatalConditionHandler::~FatalConditionHandler() {
  6290. reset();
  6291. }
  6292. bool FatalConditionHandler::isSet = false;
  6293. ULONG FatalConditionHandler::guaranteeSize = 0;
  6294. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  6295. } // namespace Catch
  6296. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  6297. namespace Catch {
  6298. struct SignalDefs {
  6299. int id;
  6300. const char* name;
  6301. };
  6302. // 32kb for the alternate stack seems to be sufficient. However, this value
  6303. // is experimentally determined, so that's not guaranteed.
  6304. constexpr static std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
  6305. static SignalDefs signalDefs[] = {
  6306. { SIGINT, "SIGINT - Terminal interrupt signal" },
  6307. { SIGILL, "SIGILL - Illegal instruction signal" },
  6308. { SIGFPE, "SIGFPE - Floating point error signal" },
  6309. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  6310. { SIGTERM, "SIGTERM - Termination request signal" },
  6311. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  6312. };
  6313. void FatalConditionHandler::handleSignal( int sig ) {
  6314. char const * name = "<unknown signal>";
  6315. for (auto const& def : signalDefs) {
  6316. if (sig == def.id) {
  6317. name = def.name;
  6318. break;
  6319. }
  6320. }
  6321. reset();
  6322. reportFatal(name);
  6323. raise( sig );
  6324. }
  6325. FatalConditionHandler::FatalConditionHandler() {
  6326. isSet = true;
  6327. stack_t sigStack;
  6328. sigStack.ss_sp = altStackMem;
  6329. sigStack.ss_size = sigStackSize;
  6330. sigStack.ss_flags = 0;
  6331. sigaltstack(&sigStack, &oldSigStack);
  6332. struct sigaction sa = { };
  6333. sa.sa_handler = handleSignal;
  6334. sa.sa_flags = SA_ONSTACK;
  6335. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  6336. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  6337. }
  6338. }
  6339. FatalConditionHandler::~FatalConditionHandler() {
  6340. reset();
  6341. }
  6342. void FatalConditionHandler::reset() {
  6343. if( isSet ) {
  6344. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  6345. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  6346. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  6347. }
  6348. // Return the old stack
  6349. sigaltstack(&oldSigStack, nullptr);
  6350. isSet = false;
  6351. }
  6352. }
  6353. bool FatalConditionHandler::isSet = false;
  6354. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  6355. stack_t FatalConditionHandler::oldSigStack = {};
  6356. char FatalConditionHandler::altStackMem[sigStackSize] = {};
  6357. } // namespace Catch
  6358. #else
  6359. namespace Catch {
  6360. void FatalConditionHandler::reset() {}
  6361. }
  6362. #endif // signals/SEH handling
  6363. #if defined(__GNUC__)
  6364. # pragma GCC diagnostic pop
  6365. #endif
  6366. // end catch_fatal_condition.cpp
  6367. // start catch_generators.cpp
  6368. // start catch_random_number_generator.h
  6369. #include <algorithm>
  6370. #include <random>
  6371. namespace Catch {
  6372. struct IConfig;
  6373. std::mt19937& rng();
  6374. void seedRng( IConfig const& config );
  6375. unsigned int rngSeed();
  6376. }
  6377. // end catch_random_number_generator.h
  6378. #include <limits>
  6379. #include <set>
  6380. namespace Catch {
  6381. IGeneratorTracker::~IGeneratorTracker() {}
  6382. namespace Generators {
  6383. GeneratorBase::~GeneratorBase() {}
  6384. std::vector<size_t> randomiseIndices( size_t selectionSize, size_t sourceSize ) {
  6385. assert( selectionSize <= sourceSize );
  6386. std::vector<size_t> indices;
  6387. indices.reserve( selectionSize );
  6388. std::uniform_int_distribution<size_t> uid( 0, sourceSize-1 );
  6389. std::set<size_t> seen;
  6390. // !TBD: improve this algorithm
  6391. while( indices.size() < selectionSize ) {
  6392. auto index = uid( rng() );
  6393. if( seen.insert( index ).second )
  6394. indices.push_back( index );
  6395. }
  6396. return indices;
  6397. }
  6398. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  6399. return getResultCapture().acquireGeneratorTracker( lineInfo );
  6400. }
  6401. template<>
  6402. auto all<int>() -> Generator<int> {
  6403. return range( std::numeric_limits<int>::min(), std::numeric_limits<int>::max() );
  6404. }
  6405. } // namespace Generators
  6406. } // namespace Catch
  6407. // end catch_generators.cpp
  6408. // start catch_interfaces_capture.cpp
  6409. namespace Catch {
  6410. IResultCapture::~IResultCapture() = default;
  6411. }
  6412. // end catch_interfaces_capture.cpp
  6413. // start catch_interfaces_config.cpp
  6414. namespace Catch {
  6415. IConfig::~IConfig() = default;
  6416. }
  6417. // end catch_interfaces_config.cpp
  6418. // start catch_interfaces_exception.cpp
  6419. namespace Catch {
  6420. IExceptionTranslator::~IExceptionTranslator() = default;
  6421. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  6422. }
  6423. // end catch_interfaces_exception.cpp
  6424. // start catch_interfaces_registry_hub.cpp
  6425. namespace Catch {
  6426. IRegistryHub::~IRegistryHub() = default;
  6427. IMutableRegistryHub::~IMutableRegistryHub() = default;
  6428. }
  6429. // end catch_interfaces_registry_hub.cpp
  6430. // start catch_interfaces_reporter.cpp
  6431. // start catch_reporter_listening.h
  6432. namespace Catch {
  6433. class ListeningReporter : public IStreamingReporter {
  6434. using Reporters = std::vector<IStreamingReporterPtr>;
  6435. Reporters m_listeners;
  6436. IStreamingReporterPtr m_reporter = nullptr;
  6437. ReporterPreferences m_preferences;
  6438. public:
  6439. ListeningReporter();
  6440. void addListener( IStreamingReporterPtr&& listener );
  6441. void addReporter( IStreamingReporterPtr&& reporter );
  6442. public: // IStreamingReporter
  6443. ReporterPreferences getPreferences() const override;
  6444. void noMatchingTestCases( std::string const& spec ) override;
  6445. static std::set<Verbosity> getSupportedVerbosities();
  6446. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  6447. void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override;
  6448. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  6449. void testGroupStarting( GroupInfo const& groupInfo ) override;
  6450. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  6451. void sectionStarting( SectionInfo const& sectionInfo ) override;
  6452. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  6453. // The return value indicates if the messages buffer should be cleared:
  6454. bool assertionEnded( AssertionStats const& assertionStats ) override;
  6455. void sectionEnded( SectionStats const& sectionStats ) override;
  6456. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  6457. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  6458. void testRunEnded( TestRunStats const& testRunStats ) override;
  6459. void skipTest( TestCaseInfo const& testInfo ) override;
  6460. bool isMulti() const override;
  6461. };
  6462. } // end namespace Catch
  6463. // end catch_reporter_listening.h
  6464. namespace Catch {
  6465. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  6466. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  6467. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  6468. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  6469. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  6470. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  6471. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  6472. GroupInfo::GroupInfo( std::string const& _name,
  6473. std::size_t _groupIndex,
  6474. std::size_t _groupsCount )
  6475. : name( _name ),
  6476. groupIndex( _groupIndex ),
  6477. groupsCounts( _groupsCount )
  6478. {}
  6479. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  6480. std::vector<MessageInfo> const& _infoMessages,
  6481. Totals const& _totals )
  6482. : assertionResult( _assertionResult ),
  6483. infoMessages( _infoMessages ),
  6484. totals( _totals )
  6485. {
  6486. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  6487. if( assertionResult.hasMessage() ) {
  6488. // Copy message into messages list.
  6489. // !TBD This should have been done earlier, somewhere
  6490. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  6491. builder << assertionResult.getMessage();
  6492. builder.m_info.message = builder.m_stream.str();
  6493. infoMessages.push_back( builder.m_info );
  6494. }
  6495. }
  6496. AssertionStats::~AssertionStats() = default;
  6497. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  6498. Counts const& _assertions,
  6499. double _durationInSeconds,
  6500. bool _missingAssertions )
  6501. : sectionInfo( _sectionInfo ),
  6502. assertions( _assertions ),
  6503. durationInSeconds( _durationInSeconds ),
  6504. missingAssertions( _missingAssertions )
  6505. {}
  6506. SectionStats::~SectionStats() = default;
  6507. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  6508. Totals const& _totals,
  6509. std::string const& _stdOut,
  6510. std::string const& _stdErr,
  6511. bool _aborting )
  6512. : testInfo( _testInfo ),
  6513. totals( _totals ),
  6514. stdOut( _stdOut ),
  6515. stdErr( _stdErr ),
  6516. aborting( _aborting )
  6517. {}
  6518. TestCaseStats::~TestCaseStats() = default;
  6519. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  6520. Totals const& _totals,
  6521. bool _aborting )
  6522. : groupInfo( _groupInfo ),
  6523. totals( _totals ),
  6524. aborting( _aborting )
  6525. {}
  6526. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  6527. : groupInfo( _groupInfo ),
  6528. aborting( false )
  6529. {}
  6530. TestGroupStats::~TestGroupStats() = default;
  6531. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  6532. Totals const& _totals,
  6533. bool _aborting )
  6534. : runInfo( _runInfo ),
  6535. totals( _totals ),
  6536. aborting( _aborting )
  6537. {}
  6538. TestRunStats::~TestRunStats() = default;
  6539. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  6540. bool IStreamingReporter::isMulti() const { return false; }
  6541. IReporterFactory::~IReporterFactory() = default;
  6542. IReporterRegistry::~IReporterRegistry() = default;
  6543. } // end namespace Catch
  6544. // end catch_interfaces_reporter.cpp
  6545. // start catch_interfaces_runner.cpp
  6546. namespace Catch {
  6547. IRunner::~IRunner() = default;
  6548. }
  6549. // end catch_interfaces_runner.cpp
  6550. // start catch_interfaces_testcase.cpp
  6551. namespace Catch {
  6552. ITestInvoker::~ITestInvoker() = default;
  6553. ITestCaseRegistry::~ITestCaseRegistry() = default;
  6554. }
  6555. // end catch_interfaces_testcase.cpp
  6556. // start catch_leak_detector.cpp
  6557. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  6558. #include <crtdbg.h>
  6559. namespace Catch {
  6560. LeakDetector::LeakDetector() {
  6561. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  6562. flag |= _CRTDBG_LEAK_CHECK_DF;
  6563. flag |= _CRTDBG_ALLOC_MEM_DF;
  6564. _CrtSetDbgFlag(flag);
  6565. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  6566. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  6567. // Change this to leaking allocation's number to break there
  6568. _CrtSetBreakAlloc(-1);
  6569. }
  6570. }
  6571. #else
  6572. Catch::LeakDetector::LeakDetector() {}
  6573. #endif
  6574. // end catch_leak_detector.cpp
  6575. // start catch_list.cpp
  6576. // start catch_list.h
  6577. #include <set>
  6578. namespace Catch {
  6579. std::size_t listTests( Config const& config );
  6580. std::size_t listTestsNamesOnly( Config const& config );
  6581. struct TagInfo {
  6582. void add( std::string const& spelling );
  6583. std::string all() const;
  6584. std::set<std::string> spellings;
  6585. std::size_t count = 0;
  6586. };
  6587. std::size_t listTags( Config const& config );
  6588. std::size_t listReporters( Config const& /*config*/ );
  6589. Option<std::size_t> list( Config const& config );
  6590. } // end namespace Catch
  6591. // end catch_list.h
  6592. // start catch_text.h
  6593. namespace Catch {
  6594. using namespace clara::TextFlow;
  6595. }
  6596. // end catch_text.h
  6597. #include <limits>
  6598. #include <algorithm>
  6599. #include <iomanip>
  6600. namespace Catch {
  6601. std::size_t listTests( Config const& config ) {
  6602. TestSpec testSpec = config.testSpec();
  6603. if( config.hasTestFilters() )
  6604. Catch::cout() << "Matching test cases:\n";
  6605. else {
  6606. Catch::cout() << "All available test cases:\n";
  6607. }
  6608. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6609. for( auto const& testCaseInfo : matchedTestCases ) {
  6610. Colour::Code colour = testCaseInfo.isHidden()
  6611. ? Colour::SecondaryText
  6612. : Colour::None;
  6613. Colour colourGuard( colour );
  6614. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  6615. if( config.verbosity() >= Verbosity::High ) {
  6616. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  6617. std::string description = testCaseInfo.description;
  6618. if( description.empty() )
  6619. description = "(NO DESCRIPTION)";
  6620. Catch::cout() << Column( description ).indent(4) << std::endl;
  6621. }
  6622. if( !testCaseInfo.tags.empty() )
  6623. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  6624. }
  6625. if( !config.hasTestFilters() )
  6626. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  6627. else
  6628. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  6629. return matchedTestCases.size();
  6630. }
  6631. std::size_t listTestsNamesOnly( Config const& config ) {
  6632. TestSpec testSpec = config.testSpec();
  6633. std::size_t matchedTests = 0;
  6634. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6635. for( auto const& testCaseInfo : matchedTestCases ) {
  6636. matchedTests++;
  6637. if( startsWith( testCaseInfo.name, '#' ) )
  6638. Catch::cout() << '"' << testCaseInfo.name << '"';
  6639. else
  6640. Catch::cout() << testCaseInfo.name;
  6641. if ( config.verbosity() >= Verbosity::High )
  6642. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  6643. Catch::cout() << std::endl;
  6644. }
  6645. return matchedTests;
  6646. }
  6647. void TagInfo::add( std::string const& spelling ) {
  6648. ++count;
  6649. spellings.insert( spelling );
  6650. }
  6651. std::string TagInfo::all() const {
  6652. std::string out;
  6653. for( auto const& spelling : spellings )
  6654. out += "[" + spelling + "]";
  6655. return out;
  6656. }
  6657. std::size_t listTags( Config const& config ) {
  6658. TestSpec testSpec = config.testSpec();
  6659. if( config.hasTestFilters() )
  6660. Catch::cout() << "Tags for matching test cases:\n";
  6661. else {
  6662. Catch::cout() << "All available tags:\n";
  6663. }
  6664. std::map<std::string, TagInfo> tagCounts;
  6665. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6666. for( auto const& testCase : matchedTestCases ) {
  6667. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  6668. std::string lcaseTagName = toLower( tagName );
  6669. auto countIt = tagCounts.find( lcaseTagName );
  6670. if( countIt == tagCounts.end() )
  6671. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  6672. countIt->second.add( tagName );
  6673. }
  6674. }
  6675. for( auto const& tagCount : tagCounts ) {
  6676. ReusableStringStream rss;
  6677. rss << " " << std::setw(2) << tagCount.second.count << " ";
  6678. auto str = rss.str();
  6679. auto wrapper = Column( tagCount.second.all() )
  6680. .initialIndent( 0 )
  6681. .indent( str.size() )
  6682. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  6683. Catch::cout() << str << wrapper << '\n';
  6684. }
  6685. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  6686. return tagCounts.size();
  6687. }
  6688. std::size_t listReporters( Config const& /*config*/ ) {
  6689. Catch::cout() << "Available reporters:\n";
  6690. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  6691. std::size_t maxNameLen = 0;
  6692. for( auto const& factoryKvp : factories )
  6693. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  6694. for( auto const& factoryKvp : factories ) {
  6695. Catch::cout()
  6696. << Column( factoryKvp.first + ":" )
  6697. .indent(2)
  6698. .width( 5+maxNameLen )
  6699. + Column( factoryKvp.second->getDescription() )
  6700. .initialIndent(0)
  6701. .indent(2)
  6702. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  6703. << "\n";
  6704. }
  6705. Catch::cout() << std::endl;
  6706. return factories.size();
  6707. }
  6708. Option<std::size_t> list( Config const& config ) {
  6709. Option<std::size_t> listedCount;
  6710. if( config.listTests() )
  6711. listedCount = listedCount.valueOr(0) + listTests( config );
  6712. if( config.listTestNamesOnly() )
  6713. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
  6714. if( config.listTags() )
  6715. listedCount = listedCount.valueOr(0) + listTags( config );
  6716. if( config.listReporters() )
  6717. listedCount = listedCount.valueOr(0) + listReporters( config );
  6718. return listedCount;
  6719. }
  6720. } // end namespace Catch
  6721. // end catch_list.cpp
  6722. // start catch_matchers.cpp
  6723. namespace Catch {
  6724. namespace Matchers {
  6725. namespace Impl {
  6726. std::string MatcherUntypedBase::toString() const {
  6727. if( m_cachedToString.empty() )
  6728. m_cachedToString = describe();
  6729. return m_cachedToString;
  6730. }
  6731. MatcherUntypedBase::~MatcherUntypedBase() = default;
  6732. } // namespace Impl
  6733. } // namespace Matchers
  6734. using namespace Matchers;
  6735. using Matchers::Impl::MatcherBase;
  6736. } // namespace Catch
  6737. // end catch_matchers.cpp
  6738. // start catch_matchers_floating.cpp
  6739. // start catch_to_string.hpp
  6740. #include <string>
  6741. namespace Catch {
  6742. template <typename T>
  6743. std::string to_string(T const& t) {
  6744. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  6745. return std::to_string(t);
  6746. #else
  6747. ReusableStringStream rss;
  6748. rss << t;
  6749. return rss.str();
  6750. #endif
  6751. }
  6752. } // end namespace Catch
  6753. // end catch_to_string.hpp
  6754. #include <cstdlib>
  6755. #include <cstdint>
  6756. #include <cstring>
  6757. namespace Catch {
  6758. namespace Matchers {
  6759. namespace Floating {
  6760. enum class FloatingPointKind : uint8_t {
  6761. Float,
  6762. Double
  6763. };
  6764. }
  6765. }
  6766. }
  6767. namespace {
  6768. template <typename T>
  6769. struct Converter;
  6770. template <>
  6771. struct Converter<float> {
  6772. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  6773. Converter(float f) {
  6774. std::memcpy(&i, &f, sizeof(f));
  6775. }
  6776. int32_t i;
  6777. };
  6778. template <>
  6779. struct Converter<double> {
  6780. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  6781. Converter(double d) {
  6782. std::memcpy(&i, &d, sizeof(d));
  6783. }
  6784. int64_t i;
  6785. };
  6786. template <typename T>
  6787. auto convert(T t) -> Converter<T> {
  6788. return Converter<T>(t);
  6789. }
  6790. template <typename FP>
  6791. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  6792. // Comparison with NaN should always be false.
  6793. // This way we can rule it out before getting into the ugly details
  6794. if (std::isnan(lhs) || std::isnan(rhs)) {
  6795. return false;
  6796. }
  6797. auto lc = convert(lhs);
  6798. auto rc = convert(rhs);
  6799. if ((lc.i < 0) != (rc.i < 0)) {
  6800. // Potentially we can have +0 and -0
  6801. return lhs == rhs;
  6802. }
  6803. auto ulpDiff = std::abs(lc.i - rc.i);
  6804. return ulpDiff <= maxUlpDiff;
  6805. }
  6806. }
  6807. namespace Catch {
  6808. namespace Matchers {
  6809. namespace Floating {
  6810. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  6811. :m_target{ target }, m_margin{ margin } {
  6812. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  6813. << " Margin has to be non-negative.");
  6814. }
  6815. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6816. // But without the subtraction to allow for INFINITY in comparison
  6817. bool WithinAbsMatcher::match(double const& matchee) const {
  6818. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  6819. }
  6820. std::string WithinAbsMatcher::describe() const {
  6821. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  6822. }
  6823. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  6824. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  6825. CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.'
  6826. << " ULPs have to be non-negative.");
  6827. }
  6828. #if defined(__clang__)
  6829. #pragma clang diagnostic push
  6830. // Clang <3.5 reports on the default branch in the switch below
  6831. #pragma clang diagnostic ignored "-Wunreachable-code"
  6832. #endif
  6833. bool WithinUlpsMatcher::match(double const& matchee) const {
  6834. switch (m_type) {
  6835. case FloatingPointKind::Float:
  6836. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  6837. case FloatingPointKind::Double:
  6838. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  6839. default:
  6840. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  6841. }
  6842. }
  6843. #if defined(__clang__)
  6844. #pragma clang diagnostic pop
  6845. #endif
  6846. std::string WithinUlpsMatcher::describe() const {
  6847. return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  6848. }
  6849. }// namespace Floating
  6850. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  6851. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  6852. }
  6853. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  6854. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  6855. }
  6856. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  6857. return Floating::WithinAbsMatcher(target, margin);
  6858. }
  6859. } // namespace Matchers
  6860. } // namespace Catch
  6861. // end catch_matchers_floating.cpp
  6862. // start catch_matchers_generic.cpp
  6863. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  6864. if (desc.empty()) {
  6865. return "matches undescribed predicate";
  6866. } else {
  6867. return "matches predicate: \"" + desc + '"';
  6868. }
  6869. }
  6870. // end catch_matchers_generic.cpp
  6871. // start catch_matchers_string.cpp
  6872. #include <regex>
  6873. namespace Catch {
  6874. namespace Matchers {
  6875. namespace StdString {
  6876. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  6877. : m_caseSensitivity( caseSensitivity ),
  6878. m_str( adjustString( str ) )
  6879. {}
  6880. std::string CasedString::adjustString( std::string const& str ) const {
  6881. return m_caseSensitivity == CaseSensitive::No
  6882. ? toLower( str )
  6883. : str;
  6884. }
  6885. std::string CasedString::caseSensitivitySuffix() const {
  6886. return m_caseSensitivity == CaseSensitive::No
  6887. ? " (case insensitive)"
  6888. : std::string();
  6889. }
  6890. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  6891. : m_comparator( comparator ),
  6892. m_operation( operation ) {
  6893. }
  6894. std::string StringMatcherBase::describe() const {
  6895. std::string description;
  6896. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  6897. m_comparator.caseSensitivitySuffix().size());
  6898. description += m_operation;
  6899. description += ": \"";
  6900. description += m_comparator.m_str;
  6901. description += "\"";
  6902. description += m_comparator.caseSensitivitySuffix();
  6903. return description;
  6904. }
  6905. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  6906. bool EqualsMatcher::match( std::string const& source ) const {
  6907. return m_comparator.adjustString( source ) == m_comparator.m_str;
  6908. }
  6909. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  6910. bool ContainsMatcher::match( std::string const& source ) const {
  6911. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  6912. }
  6913. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  6914. bool StartsWithMatcher::match( std::string const& source ) const {
  6915. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6916. }
  6917. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  6918. bool EndsWithMatcher::match( std::string const& source ) const {
  6919. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  6920. }
  6921. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  6922. bool RegexMatcher::match(std::string const& matchee) const {
  6923. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  6924. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  6925. flags |= std::regex::icase;
  6926. }
  6927. auto reg = std::regex(m_regex, flags);
  6928. return std::regex_match(matchee, reg);
  6929. }
  6930. std::string RegexMatcher::describe() const {
  6931. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  6932. }
  6933. } // namespace StdString
  6934. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6935. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  6936. }
  6937. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6938. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  6939. }
  6940. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6941. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  6942. }
  6943. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  6944. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  6945. }
  6946. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  6947. return StdString::RegexMatcher(regex, caseSensitivity);
  6948. }
  6949. } // namespace Matchers
  6950. } // namespace Catch
  6951. // end catch_matchers_string.cpp
  6952. // start catch_message.cpp
  6953. // start catch_uncaught_exceptions.h
  6954. namespace Catch {
  6955. bool uncaught_exceptions();
  6956. } // end namespace Catch
  6957. // end catch_uncaught_exceptions.h
  6958. #include <cassert>
  6959. namespace Catch {
  6960. MessageInfo::MessageInfo( StringRef const& _macroName,
  6961. SourceLineInfo const& _lineInfo,
  6962. ResultWas::OfType _type )
  6963. : macroName( _macroName ),
  6964. lineInfo( _lineInfo ),
  6965. type( _type ),
  6966. sequence( ++globalCount )
  6967. {}
  6968. bool MessageInfo::operator==( MessageInfo const& other ) const {
  6969. return sequence == other.sequence;
  6970. }
  6971. bool MessageInfo::operator<( MessageInfo const& other ) const {
  6972. return sequence < other.sequence;
  6973. }
  6974. // This may need protecting if threading support is added
  6975. unsigned int MessageInfo::globalCount = 0;
  6976. ////////////////////////////////////////////////////////////////////////////
  6977. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  6978. SourceLineInfo const& lineInfo,
  6979. ResultWas::OfType type )
  6980. :m_info(macroName, lineInfo, type) {}
  6981. ////////////////////////////////////////////////////////////////////////////
  6982. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  6983. : m_info( builder.m_info )
  6984. {
  6985. m_info.message = builder.m_stream.str();
  6986. getResultCapture().pushScopedMessage( m_info );
  6987. }
  6988. ScopedMessage::~ScopedMessage() {
  6989. if ( !uncaught_exceptions() ){
  6990. getResultCapture().popScopedMessage(m_info);
  6991. }
  6992. }
  6993. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  6994. auto start = std::string::npos;
  6995. for( size_t pos = 0; pos <= names.size(); ++pos ) {
  6996. char c = names[pos];
  6997. if( pos == names.size() || c == ' ' || c == '\t' || c == ',' || c == ']' ) {
  6998. if( start != std::string::npos ) {
  6999. m_messages.push_back( MessageInfo( macroName, lineInfo, resultType ) );
  7000. m_messages.back().message = names.substr( start, pos-start) + " := ";
  7001. start = std::string::npos;
  7002. }
  7003. }
  7004. else if( c != '[' && c != ']' && start == std::string::npos )
  7005. start = pos;
  7006. }
  7007. }
  7008. Capturer::~Capturer() {
  7009. if ( !uncaught_exceptions() ){
  7010. assert( m_captured == m_messages.size() );
  7011. for( size_t i = 0; i < m_captured; ++i )
  7012. m_resultCapture.popScopedMessage( m_messages[i] );
  7013. }
  7014. }
  7015. void Capturer::captureValue( size_t index, StringRef value ) {
  7016. assert( index < m_messages.size() );
  7017. m_messages[index].message += value;
  7018. m_resultCapture.pushScopedMessage( m_messages[index] );
  7019. m_captured++;
  7020. }
  7021. } // end namespace Catch
  7022. // end catch_message.cpp
  7023. // start catch_output_redirect.cpp
  7024. // start catch_output_redirect.h
  7025. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7026. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7027. #include <cstdio>
  7028. #include <iosfwd>
  7029. #include <string>
  7030. namespace Catch {
  7031. class RedirectedStream {
  7032. std::ostream& m_originalStream;
  7033. std::ostream& m_redirectionStream;
  7034. std::streambuf* m_prevBuf;
  7035. public:
  7036. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  7037. ~RedirectedStream();
  7038. };
  7039. class RedirectedStdOut {
  7040. ReusableStringStream m_rss;
  7041. RedirectedStream m_cout;
  7042. public:
  7043. RedirectedStdOut();
  7044. auto str() const -> std::string;
  7045. };
  7046. // StdErr has two constituent streams in C++, std::cerr and std::clog
  7047. // This means that we need to redirect 2 streams into 1 to keep proper
  7048. // order of writes
  7049. class RedirectedStdErr {
  7050. ReusableStringStream m_rss;
  7051. RedirectedStream m_cerr;
  7052. RedirectedStream m_clog;
  7053. public:
  7054. RedirectedStdErr();
  7055. auto str() const -> std::string;
  7056. };
  7057. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7058. // Windows's implementation of std::tmpfile is terrible (it tries
  7059. // to create a file inside system folder, thus requiring elevated
  7060. // privileges for the binary), so we have to use tmpnam(_s) and
  7061. // create the file ourselves there.
  7062. class TempFile {
  7063. public:
  7064. TempFile(TempFile const&) = delete;
  7065. TempFile& operator=(TempFile const&) = delete;
  7066. TempFile(TempFile&&) = delete;
  7067. TempFile& operator=(TempFile&&) = delete;
  7068. TempFile();
  7069. ~TempFile();
  7070. std::FILE* getFile();
  7071. std::string getContents();
  7072. private:
  7073. std::FILE* m_file = nullptr;
  7074. #if defined(_MSC_VER)
  7075. char m_buffer[L_tmpnam] = { 0 };
  7076. #endif
  7077. };
  7078. class OutputRedirect {
  7079. public:
  7080. OutputRedirect(OutputRedirect const&) = delete;
  7081. OutputRedirect& operator=(OutputRedirect const&) = delete;
  7082. OutputRedirect(OutputRedirect&&) = delete;
  7083. OutputRedirect& operator=(OutputRedirect&&) = delete;
  7084. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  7085. ~OutputRedirect();
  7086. private:
  7087. int m_originalStdout = -1;
  7088. int m_originalStderr = -1;
  7089. TempFile m_stdoutFile;
  7090. TempFile m_stderrFile;
  7091. std::string& m_stdoutDest;
  7092. std::string& m_stderrDest;
  7093. };
  7094. #endif
  7095. } // end namespace Catch
  7096. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7097. // end catch_output_redirect.h
  7098. #include <cstdio>
  7099. #include <cstring>
  7100. #include <fstream>
  7101. #include <sstream>
  7102. #include <stdexcept>
  7103. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7104. #if defined(_MSC_VER)
  7105. #include <io.h> //_dup and _dup2
  7106. #define dup _dup
  7107. #define dup2 _dup2
  7108. #define fileno _fileno
  7109. #else
  7110. #include <unistd.h> // dup and dup2
  7111. #endif
  7112. #endif
  7113. namespace Catch {
  7114. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  7115. : m_originalStream( originalStream ),
  7116. m_redirectionStream( redirectionStream ),
  7117. m_prevBuf( m_originalStream.rdbuf() )
  7118. {
  7119. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  7120. }
  7121. RedirectedStream::~RedirectedStream() {
  7122. m_originalStream.rdbuf( m_prevBuf );
  7123. }
  7124. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  7125. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  7126. RedirectedStdErr::RedirectedStdErr()
  7127. : m_cerr( Catch::cerr(), m_rss.get() ),
  7128. m_clog( Catch::clog(), m_rss.get() )
  7129. {}
  7130. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  7131. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7132. #if defined(_MSC_VER)
  7133. TempFile::TempFile() {
  7134. if (tmpnam_s(m_buffer)) {
  7135. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  7136. }
  7137. if (fopen_s(&m_file, m_buffer, "w")) {
  7138. char buffer[100];
  7139. if (strerror_s(buffer, errno)) {
  7140. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  7141. }
  7142. CATCH_RUNTIME_ERROR("Coul dnot open the temp file: '" << m_buffer << "' because: " << buffer);
  7143. }
  7144. }
  7145. #else
  7146. TempFile::TempFile() {
  7147. m_file = std::tmpfile();
  7148. if (!m_file) {
  7149. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  7150. }
  7151. }
  7152. #endif
  7153. TempFile::~TempFile() {
  7154. // TBD: What to do about errors here?
  7155. std::fclose(m_file);
  7156. // We manually create the file on Windows only, on Linux
  7157. // it will be autodeleted
  7158. #if defined(_MSC_VER)
  7159. std::remove(m_buffer);
  7160. #endif
  7161. }
  7162. FILE* TempFile::getFile() {
  7163. return m_file;
  7164. }
  7165. std::string TempFile::getContents() {
  7166. std::stringstream sstr;
  7167. char buffer[100] = {};
  7168. std::rewind(m_file);
  7169. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  7170. sstr << buffer;
  7171. }
  7172. return sstr.str();
  7173. }
  7174. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  7175. m_originalStdout(dup(1)),
  7176. m_originalStderr(dup(2)),
  7177. m_stdoutDest(stdout_dest),
  7178. m_stderrDest(stderr_dest) {
  7179. dup2(fileno(m_stdoutFile.getFile()), 1);
  7180. dup2(fileno(m_stderrFile.getFile()), 2);
  7181. }
  7182. OutputRedirect::~OutputRedirect() {
  7183. Catch::cout() << std::flush;
  7184. fflush(stdout);
  7185. // Since we support overriding these streams, we flush cerr
  7186. // even though std::cerr is unbuffered
  7187. Catch::cerr() << std::flush;
  7188. Catch::clog() << std::flush;
  7189. fflush(stderr);
  7190. dup2(m_originalStdout, 1);
  7191. dup2(m_originalStderr, 2);
  7192. m_stdoutDest += m_stdoutFile.getContents();
  7193. m_stderrDest += m_stderrFile.getContents();
  7194. }
  7195. #endif // CATCH_CONFIG_NEW_CAPTURE
  7196. } // namespace Catch
  7197. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7198. #if defined(_MSC_VER)
  7199. #undef dup
  7200. #undef dup2
  7201. #undef fileno
  7202. #endif
  7203. #endif
  7204. // end catch_output_redirect.cpp
  7205. // start catch_random_number_generator.cpp
  7206. namespace Catch {
  7207. std::mt19937& rng() {
  7208. static std::mt19937 s_rng;
  7209. return s_rng;
  7210. }
  7211. void seedRng( IConfig const& config ) {
  7212. if( config.rngSeed() != 0 ) {
  7213. std::srand( config.rngSeed() );
  7214. rng().seed( config.rngSeed() );
  7215. }
  7216. }
  7217. unsigned int rngSeed() {
  7218. return getCurrentContext().getConfig()->rngSeed();
  7219. }
  7220. }
  7221. // end catch_random_number_generator.cpp
  7222. // start catch_registry_hub.cpp
  7223. // start catch_test_case_registry_impl.h
  7224. #include <vector>
  7225. #include <set>
  7226. #include <algorithm>
  7227. #include <ios>
  7228. namespace Catch {
  7229. class TestCase;
  7230. struct IConfig;
  7231. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  7232. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  7233. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  7234. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  7235. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  7236. class TestRegistry : public ITestCaseRegistry {
  7237. public:
  7238. virtual ~TestRegistry() = default;
  7239. virtual void registerTest( TestCase const& testCase );
  7240. std::vector<TestCase> const& getAllTests() const override;
  7241. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  7242. private:
  7243. std::vector<TestCase> m_functions;
  7244. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  7245. mutable std::vector<TestCase> m_sortedFunctions;
  7246. std::size_t m_unnamedCount = 0;
  7247. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  7248. };
  7249. ///////////////////////////////////////////////////////////////////////////
  7250. class TestInvokerAsFunction : public ITestInvoker {
  7251. void(*m_testAsFunction)();
  7252. public:
  7253. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  7254. void invoke() const override;
  7255. };
  7256. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  7257. ///////////////////////////////////////////////////////////////////////////
  7258. } // end namespace Catch
  7259. // end catch_test_case_registry_impl.h
  7260. // start catch_reporter_registry.h
  7261. #include <map>
  7262. namespace Catch {
  7263. class ReporterRegistry : public IReporterRegistry {
  7264. public:
  7265. ~ReporterRegistry() override;
  7266. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  7267. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  7268. void registerListener( IReporterFactoryPtr const& factory );
  7269. FactoryMap const& getFactories() const override;
  7270. Listeners const& getListeners() const override;
  7271. private:
  7272. FactoryMap m_factories;
  7273. Listeners m_listeners;
  7274. };
  7275. }
  7276. // end catch_reporter_registry.h
  7277. // start catch_tag_alias_registry.h
  7278. // start catch_tag_alias.h
  7279. #include <string>
  7280. namespace Catch {
  7281. struct TagAlias {
  7282. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  7283. std::string tag;
  7284. SourceLineInfo lineInfo;
  7285. };
  7286. } // end namespace Catch
  7287. // end catch_tag_alias.h
  7288. #include <map>
  7289. namespace Catch {
  7290. class TagAliasRegistry : public ITagAliasRegistry {
  7291. public:
  7292. ~TagAliasRegistry() override;
  7293. TagAlias const* find( std::string const& alias ) const override;
  7294. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  7295. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  7296. private:
  7297. std::map<std::string, TagAlias> m_registry;
  7298. };
  7299. } // end namespace Catch
  7300. // end catch_tag_alias_registry.h
  7301. // start catch_startup_exception_registry.h
  7302. #include <vector>
  7303. #include <exception>
  7304. namespace Catch {
  7305. class StartupExceptionRegistry {
  7306. public:
  7307. void add(std::exception_ptr const& exception) noexcept;
  7308. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  7309. private:
  7310. std::vector<std::exception_ptr> m_exceptions;
  7311. };
  7312. } // end namespace Catch
  7313. // end catch_startup_exception_registry.h
  7314. // start catch_singletons.hpp
  7315. namespace Catch {
  7316. struct ISingleton {
  7317. virtual ~ISingleton();
  7318. };
  7319. void addSingleton( ISingleton* singleton );
  7320. void cleanupSingletons();
  7321. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  7322. class Singleton : SingletonImplT, public ISingleton {
  7323. static auto getInternal() -> Singleton* {
  7324. static Singleton* s_instance = nullptr;
  7325. if( !s_instance ) {
  7326. s_instance = new Singleton;
  7327. addSingleton( s_instance );
  7328. }
  7329. return s_instance;
  7330. }
  7331. public:
  7332. static auto get() -> InterfaceT const& {
  7333. return *getInternal();
  7334. }
  7335. static auto getMutable() -> MutableInterfaceT& {
  7336. return *getInternal();
  7337. }
  7338. };
  7339. } // namespace Catch
  7340. // end catch_singletons.hpp
  7341. namespace Catch {
  7342. namespace {
  7343. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  7344. private NonCopyable {
  7345. public: // IRegistryHub
  7346. RegistryHub() = default;
  7347. IReporterRegistry const& getReporterRegistry() const override {
  7348. return m_reporterRegistry;
  7349. }
  7350. ITestCaseRegistry const& getTestCaseRegistry() const override {
  7351. return m_testCaseRegistry;
  7352. }
  7353. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  7354. return m_exceptionTranslatorRegistry;
  7355. }
  7356. ITagAliasRegistry const& getTagAliasRegistry() const override {
  7357. return m_tagAliasRegistry;
  7358. }
  7359. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  7360. return m_exceptionRegistry;
  7361. }
  7362. public: // IMutableRegistryHub
  7363. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  7364. m_reporterRegistry.registerReporter( name, factory );
  7365. }
  7366. void registerListener( IReporterFactoryPtr const& factory ) override {
  7367. m_reporterRegistry.registerListener( factory );
  7368. }
  7369. void registerTest( TestCase const& testInfo ) override {
  7370. m_testCaseRegistry.registerTest( testInfo );
  7371. }
  7372. void registerTranslator( const IExceptionTranslator* translator ) override {
  7373. m_exceptionTranslatorRegistry.registerTranslator( translator );
  7374. }
  7375. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  7376. m_tagAliasRegistry.add( alias, tag, lineInfo );
  7377. }
  7378. void registerStartupException() noexcept override {
  7379. m_exceptionRegistry.add(std::current_exception());
  7380. }
  7381. private:
  7382. TestRegistry m_testCaseRegistry;
  7383. ReporterRegistry m_reporterRegistry;
  7384. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  7385. TagAliasRegistry m_tagAliasRegistry;
  7386. StartupExceptionRegistry m_exceptionRegistry;
  7387. };
  7388. }
  7389. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  7390. IRegistryHub const& getRegistryHub() {
  7391. return RegistryHubSingleton::get();
  7392. }
  7393. IMutableRegistryHub& getMutableRegistryHub() {
  7394. return RegistryHubSingleton::getMutable();
  7395. }
  7396. void cleanUp() {
  7397. cleanupSingletons();
  7398. cleanUpContext();
  7399. }
  7400. std::string translateActiveException() {
  7401. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  7402. }
  7403. } // end namespace Catch
  7404. // end catch_registry_hub.cpp
  7405. // start catch_reporter_registry.cpp
  7406. namespace Catch {
  7407. ReporterRegistry::~ReporterRegistry() = default;
  7408. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  7409. auto it = m_factories.find( name );
  7410. if( it == m_factories.end() )
  7411. return nullptr;
  7412. return it->second->create( ReporterConfig( config ) );
  7413. }
  7414. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  7415. m_factories.emplace(name, factory);
  7416. }
  7417. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  7418. m_listeners.push_back( factory );
  7419. }
  7420. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  7421. return m_factories;
  7422. }
  7423. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  7424. return m_listeners;
  7425. }
  7426. }
  7427. // end catch_reporter_registry.cpp
  7428. // start catch_result_type.cpp
  7429. namespace Catch {
  7430. bool isOk( ResultWas::OfType resultType ) {
  7431. return ( resultType & ResultWas::FailureBit ) == 0;
  7432. }
  7433. bool isJustInfo( int flags ) {
  7434. return flags == ResultWas::Info;
  7435. }
  7436. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  7437. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  7438. }
  7439. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  7440. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  7441. } // end namespace Catch
  7442. // end catch_result_type.cpp
  7443. // start catch_run_context.cpp
  7444. #include <cassert>
  7445. #include <algorithm>
  7446. #include <sstream>
  7447. namespace Catch {
  7448. namespace Generators {
  7449. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  7450. size_t m_index = static_cast<size_t>( -1 );
  7451. GeneratorBasePtr m_generator;
  7452. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  7453. : TrackerBase( nameAndLocation, ctx, parent )
  7454. {}
  7455. ~GeneratorTracker();
  7456. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  7457. std::shared_ptr<GeneratorTracker> tracker;
  7458. ITracker& currentTracker = ctx.currentTracker();
  7459. if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  7460. assert( childTracker );
  7461. assert( childTracker->isIndexTracker() );
  7462. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  7463. }
  7464. else {
  7465. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  7466. currentTracker.addChild( tracker );
  7467. }
  7468. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  7469. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  7470. tracker->moveNext();
  7471. tracker->open();
  7472. }
  7473. return *tracker;
  7474. }
  7475. void moveNext() {
  7476. m_index++;
  7477. m_children.clear();
  7478. }
  7479. // TrackerBase interface
  7480. bool isIndexTracker() const override { return true; }
  7481. auto hasGenerator() const -> bool override {
  7482. return !!m_generator;
  7483. }
  7484. void close() override {
  7485. TrackerBase::close();
  7486. if( m_runState == CompletedSuccessfully && m_index < m_generator->size()-1 )
  7487. m_runState = Executing;
  7488. }
  7489. // IGeneratorTracker interface
  7490. auto getGenerator() const -> GeneratorBasePtr const& override {
  7491. return m_generator;
  7492. }
  7493. void setGenerator( GeneratorBasePtr&& generator ) override {
  7494. m_generator = std::move( generator );
  7495. }
  7496. auto getIndex() const -> size_t override {
  7497. return m_index;
  7498. }
  7499. };
  7500. GeneratorTracker::~GeneratorTracker() {}
  7501. }
  7502. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  7503. : m_runInfo(_config->name()),
  7504. m_context(getCurrentMutableContext()),
  7505. m_config(_config),
  7506. m_reporter(std::move(reporter)),
  7507. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  7508. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  7509. {
  7510. m_context.setRunner(this);
  7511. m_context.setConfig(m_config);
  7512. m_context.setResultCapture(this);
  7513. m_reporter->testRunStarting(m_runInfo);
  7514. }
  7515. RunContext::~RunContext() {
  7516. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  7517. }
  7518. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  7519. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  7520. }
  7521. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  7522. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  7523. }
  7524. Totals RunContext::runTest(TestCase const& testCase) {
  7525. Totals prevTotals = m_totals;
  7526. std::string redirectedCout;
  7527. std::string redirectedCerr;
  7528. auto const& testInfo = testCase.getTestCaseInfo();
  7529. m_reporter->testCaseStarting(testInfo);
  7530. m_activeTestCase = &testCase;
  7531. ITracker& rootTracker = m_trackerContext.startRun();
  7532. assert(rootTracker.isSectionTracker());
  7533. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  7534. do {
  7535. m_trackerContext.startCycle();
  7536. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  7537. runCurrentTest(redirectedCout, redirectedCerr);
  7538. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  7539. Totals deltaTotals = m_totals.delta(prevTotals);
  7540. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  7541. deltaTotals.assertions.failed++;
  7542. deltaTotals.testCases.passed--;
  7543. deltaTotals.testCases.failed++;
  7544. }
  7545. m_totals.testCases += deltaTotals.testCases;
  7546. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  7547. deltaTotals,
  7548. redirectedCout,
  7549. redirectedCerr,
  7550. aborting()));
  7551. m_activeTestCase = nullptr;
  7552. m_testCaseTracker = nullptr;
  7553. return deltaTotals;
  7554. }
  7555. IConfigPtr RunContext::config() const {
  7556. return m_config;
  7557. }
  7558. IStreamingReporter& RunContext::reporter() const {
  7559. return *m_reporter;
  7560. }
  7561. void RunContext::assertionEnded(AssertionResult const & result) {
  7562. if (result.getResultType() == ResultWas::Ok) {
  7563. m_totals.assertions.passed++;
  7564. m_lastAssertionPassed = true;
  7565. } else if (!result.isOk()) {
  7566. m_lastAssertionPassed = false;
  7567. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  7568. m_totals.assertions.failedButOk++;
  7569. else
  7570. m_totals.assertions.failed++;
  7571. }
  7572. else {
  7573. m_lastAssertionPassed = true;
  7574. }
  7575. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  7576. // and should be let to clear themselves out.
  7577. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  7578. // Reset working state
  7579. resetAssertionInfo();
  7580. m_lastResult = result;
  7581. }
  7582. void RunContext::resetAssertionInfo() {
  7583. m_lastAssertionInfo.macroName = StringRef();
  7584. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  7585. }
  7586. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  7587. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  7588. if (!sectionTracker.isOpen())
  7589. return false;
  7590. m_activeSections.push_back(&sectionTracker);
  7591. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  7592. m_reporter->sectionStarting(sectionInfo);
  7593. assertions = m_totals.assertions;
  7594. return true;
  7595. }
  7596. auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  7597. using namespace Generators;
  7598. GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) );
  7599. assert( tracker.isOpen() );
  7600. m_lastAssertionInfo.lineInfo = lineInfo;
  7601. return tracker;
  7602. }
  7603. bool RunContext::testForMissingAssertions(Counts& assertions) {
  7604. if (assertions.total() != 0)
  7605. return false;
  7606. if (!m_config->warnAboutMissingAssertions())
  7607. return false;
  7608. if (m_trackerContext.currentTracker().hasChildren())
  7609. return false;
  7610. m_totals.assertions.failed++;
  7611. assertions.failed++;
  7612. return true;
  7613. }
  7614. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  7615. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  7616. bool missingAssertions = testForMissingAssertions(assertions);
  7617. if (!m_activeSections.empty()) {
  7618. m_activeSections.back()->close();
  7619. m_activeSections.pop_back();
  7620. }
  7621. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  7622. m_messages.clear();
  7623. }
  7624. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  7625. if (m_unfinishedSections.empty())
  7626. m_activeSections.back()->fail();
  7627. else
  7628. m_activeSections.back()->close();
  7629. m_activeSections.pop_back();
  7630. m_unfinishedSections.push_back(endInfo);
  7631. }
  7632. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  7633. m_reporter->benchmarkStarting( info );
  7634. }
  7635. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  7636. m_reporter->benchmarkEnded( stats );
  7637. }
  7638. void RunContext::pushScopedMessage(MessageInfo const & message) {
  7639. m_messages.push_back(message);
  7640. }
  7641. void RunContext::popScopedMessage(MessageInfo const & message) {
  7642. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  7643. }
  7644. std::string RunContext::getCurrentTestName() const {
  7645. return m_activeTestCase
  7646. ? m_activeTestCase->getTestCaseInfo().name
  7647. : std::string();
  7648. }
  7649. const AssertionResult * RunContext::getLastResult() const {
  7650. return &(*m_lastResult);
  7651. }
  7652. void RunContext::exceptionEarlyReported() {
  7653. m_shouldReportUnexpected = false;
  7654. }
  7655. void RunContext::handleFatalErrorCondition( StringRef message ) {
  7656. // First notify reporter that bad things happened
  7657. m_reporter->fatalErrorEncountered(message);
  7658. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  7659. // Instead, fake a result data.
  7660. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  7661. tempResult.message = message;
  7662. AssertionResult result(m_lastAssertionInfo, tempResult);
  7663. assertionEnded(result);
  7664. handleUnfinishedSections();
  7665. // Recreate section for test case (as we will lose the one that was in scope)
  7666. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  7667. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  7668. Counts assertions;
  7669. assertions.failed = 1;
  7670. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  7671. m_reporter->sectionEnded(testCaseSectionStats);
  7672. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  7673. Totals deltaTotals;
  7674. deltaTotals.testCases.failed = 1;
  7675. deltaTotals.assertions.failed = 1;
  7676. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  7677. deltaTotals,
  7678. std::string(),
  7679. std::string(),
  7680. false));
  7681. m_totals.testCases.failed++;
  7682. testGroupEnded(std::string(), m_totals, 1, 1);
  7683. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  7684. }
  7685. bool RunContext::lastAssertionPassed() {
  7686. return m_lastAssertionPassed;
  7687. }
  7688. void RunContext::assertionPassed() {
  7689. m_lastAssertionPassed = true;
  7690. ++m_totals.assertions.passed;
  7691. resetAssertionInfo();
  7692. }
  7693. bool RunContext::aborting() const {
  7694. return m_totals.assertions.failed == static_cast<std::size_t>(m_config->abortAfter());
  7695. }
  7696. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  7697. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  7698. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  7699. m_reporter->sectionStarting(testCaseSection);
  7700. Counts prevAssertions = m_totals.assertions;
  7701. double duration = 0;
  7702. m_shouldReportUnexpected = true;
  7703. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  7704. seedRng(*m_config);
  7705. Timer timer;
  7706. CATCH_TRY {
  7707. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  7708. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  7709. RedirectedStdOut redirectedStdOut;
  7710. RedirectedStdErr redirectedStdErr;
  7711. timer.start();
  7712. invokeActiveTestCase();
  7713. redirectedCout += redirectedStdOut.str();
  7714. redirectedCerr += redirectedStdErr.str();
  7715. #else
  7716. OutputRedirect r(redirectedCout, redirectedCerr);
  7717. timer.start();
  7718. invokeActiveTestCase();
  7719. #endif
  7720. } else {
  7721. timer.start();
  7722. invokeActiveTestCase();
  7723. }
  7724. duration = timer.getElapsedSeconds();
  7725. } CATCH_CATCH_ANON (TestFailureException&) {
  7726. // This just means the test was aborted due to failure
  7727. } CATCH_CATCH_ALL {
  7728. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  7729. // are reported without translation at the point of origin.
  7730. if( m_shouldReportUnexpected ) {
  7731. AssertionReaction dummyReaction;
  7732. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  7733. }
  7734. }
  7735. Counts assertions = m_totals.assertions - prevAssertions;
  7736. bool missingAssertions = testForMissingAssertions(assertions);
  7737. m_testCaseTracker->close();
  7738. handleUnfinishedSections();
  7739. m_messages.clear();
  7740. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  7741. m_reporter->sectionEnded(testCaseSectionStats);
  7742. }
  7743. void RunContext::invokeActiveTestCase() {
  7744. FatalConditionHandler fatalConditionHandler; // Handle signals
  7745. m_activeTestCase->invoke();
  7746. fatalConditionHandler.reset();
  7747. }
  7748. void RunContext::handleUnfinishedSections() {
  7749. // If sections ended prematurely due to an exception we stored their
  7750. // infos here so we can tear them down outside the unwind process.
  7751. for (auto it = m_unfinishedSections.rbegin(),
  7752. itEnd = m_unfinishedSections.rend();
  7753. it != itEnd;
  7754. ++it)
  7755. sectionEnded(*it);
  7756. m_unfinishedSections.clear();
  7757. }
  7758. void RunContext::handleExpr(
  7759. AssertionInfo const& info,
  7760. ITransientExpression const& expr,
  7761. AssertionReaction& reaction
  7762. ) {
  7763. m_reporter->assertionStarting( info );
  7764. bool negated = isFalseTest( info.resultDisposition );
  7765. bool result = expr.getResult() != negated;
  7766. if( result ) {
  7767. if (!m_includeSuccessfulResults) {
  7768. assertionPassed();
  7769. }
  7770. else {
  7771. reportExpr(info, ResultWas::Ok, &expr, negated);
  7772. }
  7773. }
  7774. else {
  7775. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  7776. populateReaction( reaction );
  7777. }
  7778. }
  7779. void RunContext::reportExpr(
  7780. AssertionInfo const &info,
  7781. ResultWas::OfType resultType,
  7782. ITransientExpression const *expr,
  7783. bool negated ) {
  7784. m_lastAssertionInfo = info;
  7785. AssertionResultData data( resultType, LazyExpression( negated ) );
  7786. AssertionResult assertionResult{ info, data };
  7787. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  7788. assertionEnded( assertionResult );
  7789. }
  7790. void RunContext::handleMessage(
  7791. AssertionInfo const& info,
  7792. ResultWas::OfType resultType,
  7793. StringRef const& message,
  7794. AssertionReaction& reaction
  7795. ) {
  7796. m_reporter->assertionStarting( info );
  7797. m_lastAssertionInfo = info;
  7798. AssertionResultData data( resultType, LazyExpression( false ) );
  7799. data.message = message;
  7800. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  7801. assertionEnded( assertionResult );
  7802. if( !assertionResult.isOk() )
  7803. populateReaction( reaction );
  7804. }
  7805. void RunContext::handleUnexpectedExceptionNotThrown(
  7806. AssertionInfo const& info,
  7807. AssertionReaction& reaction
  7808. ) {
  7809. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  7810. }
  7811. void RunContext::handleUnexpectedInflightException(
  7812. AssertionInfo const& info,
  7813. std::string const& message,
  7814. AssertionReaction& reaction
  7815. ) {
  7816. m_lastAssertionInfo = info;
  7817. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  7818. data.message = message;
  7819. AssertionResult assertionResult{ info, data };
  7820. assertionEnded( assertionResult );
  7821. populateReaction( reaction );
  7822. }
  7823. void RunContext::populateReaction( AssertionReaction& reaction ) {
  7824. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  7825. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  7826. }
  7827. void RunContext::handleIncomplete(
  7828. AssertionInfo const& info
  7829. ) {
  7830. m_lastAssertionInfo = info;
  7831. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  7832. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  7833. AssertionResult assertionResult{ info, data };
  7834. assertionEnded( assertionResult );
  7835. }
  7836. void RunContext::handleNonExpr(
  7837. AssertionInfo const &info,
  7838. ResultWas::OfType resultType,
  7839. AssertionReaction &reaction
  7840. ) {
  7841. m_lastAssertionInfo = info;
  7842. AssertionResultData data( resultType, LazyExpression( false ) );
  7843. AssertionResult assertionResult{ info, data };
  7844. assertionEnded( assertionResult );
  7845. if( !assertionResult.isOk() )
  7846. populateReaction( reaction );
  7847. }
  7848. IResultCapture& getResultCapture() {
  7849. if (auto* capture = getCurrentContext().getResultCapture())
  7850. return *capture;
  7851. else
  7852. CATCH_INTERNAL_ERROR("No result capture instance");
  7853. }
  7854. }
  7855. // end catch_run_context.cpp
  7856. // start catch_section.cpp
  7857. namespace Catch {
  7858. Section::Section( SectionInfo const& info )
  7859. : m_info( info ),
  7860. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  7861. {
  7862. m_timer.start();
  7863. }
  7864. Section::~Section() {
  7865. if( m_sectionIncluded ) {
  7866. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  7867. if( uncaught_exceptions() )
  7868. getResultCapture().sectionEndedEarly( endInfo );
  7869. else
  7870. getResultCapture().sectionEnded( endInfo );
  7871. }
  7872. }
  7873. // This indicates whether the section should be executed or not
  7874. Section::operator bool() const {
  7875. return m_sectionIncluded;
  7876. }
  7877. } // end namespace Catch
  7878. // end catch_section.cpp
  7879. // start catch_section_info.cpp
  7880. namespace Catch {
  7881. SectionInfo::SectionInfo
  7882. ( SourceLineInfo const& _lineInfo,
  7883. std::string const& _name )
  7884. : name( _name ),
  7885. lineInfo( _lineInfo )
  7886. {}
  7887. } // end namespace Catch
  7888. // end catch_section_info.cpp
  7889. // start catch_session.cpp
  7890. // start catch_session.h
  7891. #include <memory>
  7892. namespace Catch {
  7893. class Session : NonCopyable {
  7894. public:
  7895. Session();
  7896. ~Session() override;
  7897. void showHelp() const;
  7898. void libIdentify();
  7899. int applyCommandLine( int argc, char const * const * argv );
  7900. void useConfigData( ConfigData const& configData );
  7901. int run( int argc, char* argv[] );
  7902. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  7903. int run( int argc, wchar_t* const argv[] );
  7904. #endif
  7905. int run();
  7906. clara::Parser const& cli() const;
  7907. void cli( clara::Parser const& newParser );
  7908. ConfigData& configData();
  7909. Config& config();
  7910. private:
  7911. int runInternal();
  7912. clara::Parser m_cli;
  7913. ConfigData m_configData;
  7914. std::shared_ptr<Config> m_config;
  7915. bool m_startupExceptions = false;
  7916. };
  7917. } // end namespace Catch
  7918. // end catch_session.h
  7919. // start catch_version.h
  7920. #include <iosfwd>
  7921. namespace Catch {
  7922. // Versioning information
  7923. struct Version {
  7924. Version( Version const& ) = delete;
  7925. Version& operator=( Version const& ) = delete;
  7926. Version( unsigned int _majorVersion,
  7927. unsigned int _minorVersion,
  7928. unsigned int _patchNumber,
  7929. char const * const _branchName,
  7930. unsigned int _buildNumber );
  7931. unsigned int const majorVersion;
  7932. unsigned int const minorVersion;
  7933. unsigned int const patchNumber;
  7934. // buildNumber is only used if branchName is not null
  7935. char const * const branchName;
  7936. unsigned int const buildNumber;
  7937. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  7938. };
  7939. Version const& libraryVersion();
  7940. }
  7941. // end catch_version.h
  7942. #include <cstdlib>
  7943. #include <iomanip>
  7944. namespace Catch {
  7945. namespace {
  7946. const int MaxExitCode = 255;
  7947. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  7948. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  7949. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  7950. return reporter;
  7951. }
  7952. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  7953. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  7954. return createReporter(config->getReporterName(), config);
  7955. }
  7956. auto multi = std::unique_ptr<ListeningReporter>(new ListeningReporter);
  7957. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  7958. for (auto const& listener : listeners) {
  7959. multi->addListener(listener->create(Catch::ReporterConfig(config)));
  7960. }
  7961. multi->addReporter(createReporter(config->getReporterName(), config));
  7962. return std::move(multi);
  7963. }
  7964. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  7965. // FixMe: Add listeners in order first, then add reporters.
  7966. auto reporter = makeReporter(config);
  7967. RunContext context(config, std::move(reporter));
  7968. Totals totals;
  7969. context.testGroupStarting(config->name(), 1, 1);
  7970. TestSpec testSpec = config->testSpec();
  7971. auto const& allTestCases = getAllTestCasesSorted(*config);
  7972. for (auto const& testCase : allTestCases) {
  7973. if (!context.aborting() && matchTest(testCase, testSpec, *config))
  7974. totals += context.runTest(testCase);
  7975. else
  7976. context.reporter().skipTest(testCase);
  7977. }
  7978. if (config->warnAboutNoTests() && totals.testCases.total() == 0) {
  7979. ReusableStringStream testConfig;
  7980. bool first = true;
  7981. for (const auto& input : config->getTestsOrTags()) {
  7982. if (!first) { testConfig << ' '; }
  7983. first = false;
  7984. testConfig << input;
  7985. }
  7986. context.reporter().noMatchingTestCases(testConfig.str());
  7987. totals.error = -1;
  7988. }
  7989. context.testGroupEnded(config->name(), totals, 1, 1);
  7990. return totals;
  7991. }
  7992. void applyFilenamesAsTags(Catch::IConfig const& config) {
  7993. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  7994. for (auto& testCase : tests) {
  7995. auto tags = testCase.tags;
  7996. std::string filename = testCase.lineInfo.file;
  7997. auto lastSlash = filename.find_last_of("\\/");
  7998. if (lastSlash != std::string::npos) {
  7999. filename.erase(0, lastSlash);
  8000. filename[0] = '#';
  8001. }
  8002. auto lastDot = filename.find_last_of('.');
  8003. if (lastDot != std::string::npos) {
  8004. filename.erase(lastDot);
  8005. }
  8006. tags.push_back(std::move(filename));
  8007. setTags(testCase, tags);
  8008. }
  8009. }
  8010. } // anon namespace
  8011. Session::Session() {
  8012. static bool alreadyInstantiated = false;
  8013. if( alreadyInstantiated ) {
  8014. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  8015. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  8016. }
  8017. // There cannot be exceptions at startup in no-exception mode.
  8018. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8019. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  8020. if ( !exceptions.empty() ) {
  8021. m_startupExceptions = true;
  8022. Colour colourGuard( Colour::Red );
  8023. Catch::cerr() << "Errors occurred during startup!" << '\n';
  8024. // iterate over all exceptions and notify user
  8025. for ( const auto& ex_ptr : exceptions ) {
  8026. try {
  8027. std::rethrow_exception(ex_ptr);
  8028. } catch ( std::exception const& ex ) {
  8029. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  8030. }
  8031. }
  8032. }
  8033. #endif
  8034. alreadyInstantiated = true;
  8035. m_cli = makeCommandLineParser( m_configData );
  8036. }
  8037. Session::~Session() {
  8038. Catch::cleanUp();
  8039. }
  8040. void Session::showHelp() const {
  8041. Catch::cout()
  8042. << "\nCatch v" << libraryVersion() << "\n"
  8043. << m_cli << std::endl
  8044. << "For more detailed usage please see the project docs\n" << std::endl;
  8045. }
  8046. void Session::libIdentify() {
  8047. Catch::cout()
  8048. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  8049. << std::left << std::setw(16) << "category: " << "testframework\n"
  8050. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  8051. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  8052. }
  8053. int Session::applyCommandLine( int argc, char const * const * argv ) {
  8054. if( m_startupExceptions )
  8055. return 1;
  8056. auto result = m_cli.parse( clara::Args( argc, argv ) );
  8057. if( !result ) {
  8058. Catch::cerr()
  8059. << Colour( Colour::Red )
  8060. << "\nError(s) in input:\n"
  8061. << Column( result.errorMessage() ).indent( 2 )
  8062. << "\n\n";
  8063. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  8064. return MaxExitCode;
  8065. }
  8066. if( m_configData.showHelp )
  8067. showHelp();
  8068. if( m_configData.libIdentify )
  8069. libIdentify();
  8070. m_config.reset();
  8071. return 0;
  8072. }
  8073. void Session::useConfigData( ConfigData const& configData ) {
  8074. m_configData = configData;
  8075. m_config.reset();
  8076. }
  8077. int Session::run( int argc, char* argv[] ) {
  8078. if( m_startupExceptions )
  8079. return 1;
  8080. int returnCode = applyCommandLine( argc, argv );
  8081. if( returnCode == 0 )
  8082. returnCode = run();
  8083. return returnCode;
  8084. }
  8085. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  8086. int Session::run( int argc, wchar_t* const argv[] ) {
  8087. char **utf8Argv = new char *[ argc ];
  8088. for ( int i = 0; i < argc; ++i ) {
  8089. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  8090. utf8Argv[ i ] = new char[ bufSize ];
  8091. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  8092. }
  8093. int returnCode = run( argc, utf8Argv );
  8094. for ( int i = 0; i < argc; ++i )
  8095. delete [] utf8Argv[ i ];
  8096. delete [] utf8Argv;
  8097. return returnCode;
  8098. }
  8099. #endif
  8100. int Session::run() {
  8101. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  8102. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  8103. static_cast<void>(std::getchar());
  8104. }
  8105. int exitCode = runInternal();
  8106. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  8107. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  8108. static_cast<void>(std::getchar());
  8109. }
  8110. return exitCode;
  8111. }
  8112. clara::Parser const& Session::cli() const {
  8113. return m_cli;
  8114. }
  8115. void Session::cli( clara::Parser const& newParser ) {
  8116. m_cli = newParser;
  8117. }
  8118. ConfigData& Session::configData() {
  8119. return m_configData;
  8120. }
  8121. Config& Session::config() {
  8122. if( !m_config )
  8123. m_config = std::make_shared<Config>( m_configData );
  8124. return *m_config;
  8125. }
  8126. int Session::runInternal() {
  8127. if( m_startupExceptions )
  8128. return 1;
  8129. if (m_configData.showHelp || m_configData.libIdentify) {
  8130. return 0;
  8131. }
  8132. CATCH_TRY {
  8133. config(); // Force config to be constructed
  8134. seedRng( *m_config );
  8135. if( m_configData.filenamesAsTags )
  8136. applyFilenamesAsTags( *m_config );
  8137. // Handle list request
  8138. if( Option<std::size_t> listed = list( config() ) )
  8139. return static_cast<int>( *listed );
  8140. auto totals = runTests( m_config );
  8141. // Note that on unices only the lower 8 bits are usually used, clamping
  8142. // the return value to 255 prevents false negative when some multiple
  8143. // of 256 tests has failed
  8144. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  8145. }
  8146. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8147. catch( std::exception& ex ) {
  8148. Catch::cerr() << ex.what() << std::endl;
  8149. return MaxExitCode;
  8150. }
  8151. #endif
  8152. }
  8153. } // end namespace Catch
  8154. // end catch_session.cpp
  8155. // start catch_singletons.cpp
  8156. #include <vector>
  8157. namespace Catch {
  8158. namespace {
  8159. static auto getSingletons() -> std::vector<ISingleton*>*& {
  8160. static std::vector<ISingleton*>* g_singletons = nullptr;
  8161. if( !g_singletons )
  8162. g_singletons = new std::vector<ISingleton*>();
  8163. return g_singletons;
  8164. }
  8165. }
  8166. ISingleton::~ISingleton() {}
  8167. void addSingleton(ISingleton* singleton ) {
  8168. getSingletons()->push_back( singleton );
  8169. }
  8170. void cleanupSingletons() {
  8171. auto& singletons = getSingletons();
  8172. for( auto singleton : *singletons )
  8173. delete singleton;
  8174. delete singletons;
  8175. singletons = nullptr;
  8176. }
  8177. } // namespace Catch
  8178. // end catch_singletons.cpp
  8179. // start catch_startup_exception_registry.cpp
  8180. namespace Catch {
  8181. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  8182. CATCH_TRY {
  8183. m_exceptions.push_back(exception);
  8184. } CATCH_CATCH_ALL {
  8185. // If we run out of memory during start-up there's really not a lot more we can do about it
  8186. std::terminate();
  8187. }
  8188. }
  8189. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  8190. return m_exceptions;
  8191. }
  8192. } // end namespace Catch
  8193. // end catch_startup_exception_registry.cpp
  8194. // start catch_stream.cpp
  8195. #include <cstdio>
  8196. #include <iostream>
  8197. #include <fstream>
  8198. #include <sstream>
  8199. #include <vector>
  8200. #include <memory>
  8201. namespace Catch {
  8202. Catch::IStream::~IStream() = default;
  8203. namespace detail { namespace {
  8204. template<typename WriterF, std::size_t bufferSize=256>
  8205. class StreamBufImpl : public std::streambuf {
  8206. char data[bufferSize];
  8207. WriterF m_writer;
  8208. public:
  8209. StreamBufImpl() {
  8210. setp( data, data + sizeof(data) );
  8211. }
  8212. ~StreamBufImpl() noexcept {
  8213. StreamBufImpl::sync();
  8214. }
  8215. private:
  8216. int overflow( int c ) override {
  8217. sync();
  8218. if( c != EOF ) {
  8219. if( pbase() == epptr() )
  8220. m_writer( std::string( 1, static_cast<char>( c ) ) );
  8221. else
  8222. sputc( static_cast<char>( c ) );
  8223. }
  8224. return 0;
  8225. }
  8226. int sync() override {
  8227. if( pbase() != pptr() ) {
  8228. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  8229. setp( pbase(), epptr() );
  8230. }
  8231. return 0;
  8232. }
  8233. };
  8234. ///////////////////////////////////////////////////////////////////////////
  8235. struct OutputDebugWriter {
  8236. void operator()( std::string const&str ) {
  8237. writeToDebugConsole( str );
  8238. }
  8239. };
  8240. ///////////////////////////////////////////////////////////////////////////
  8241. class FileStream : public IStream {
  8242. mutable std::ofstream m_ofs;
  8243. public:
  8244. FileStream( StringRef filename ) {
  8245. m_ofs.open( filename.c_str() );
  8246. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  8247. }
  8248. ~FileStream() override = default;
  8249. public: // IStream
  8250. std::ostream& stream() const override {
  8251. return m_ofs;
  8252. }
  8253. };
  8254. ///////////////////////////////////////////////////////////////////////////
  8255. class CoutStream : public IStream {
  8256. mutable std::ostream m_os;
  8257. public:
  8258. // Store the streambuf from cout up-front because
  8259. // cout may get redirected when running tests
  8260. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  8261. ~CoutStream() override = default;
  8262. public: // IStream
  8263. std::ostream& stream() const override { return m_os; }
  8264. };
  8265. ///////////////////////////////////////////////////////////////////////////
  8266. class DebugOutStream : public IStream {
  8267. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  8268. mutable std::ostream m_os;
  8269. public:
  8270. DebugOutStream()
  8271. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  8272. m_os( m_streamBuf.get() )
  8273. {}
  8274. ~DebugOutStream() override = default;
  8275. public: // IStream
  8276. std::ostream& stream() const override { return m_os; }
  8277. };
  8278. }} // namespace anon::detail
  8279. ///////////////////////////////////////////////////////////////////////////
  8280. auto makeStream( StringRef const &filename ) -> IStream const* {
  8281. if( filename.empty() )
  8282. return new detail::CoutStream();
  8283. else if( filename[0] == '%' ) {
  8284. if( filename == "%debug" )
  8285. return new detail::DebugOutStream();
  8286. else
  8287. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  8288. }
  8289. else
  8290. return new detail::FileStream( filename );
  8291. }
  8292. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  8293. struct StringStreams {
  8294. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  8295. std::vector<std::size_t> m_unused;
  8296. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  8297. auto add() -> std::size_t {
  8298. if( m_unused.empty() ) {
  8299. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  8300. return m_streams.size()-1;
  8301. }
  8302. else {
  8303. auto index = m_unused.back();
  8304. m_unused.pop_back();
  8305. return index;
  8306. }
  8307. }
  8308. void release( std::size_t index ) {
  8309. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  8310. m_unused.push_back(index);
  8311. }
  8312. };
  8313. ReusableStringStream::ReusableStringStream()
  8314. : m_index( Singleton<StringStreams>::getMutable().add() ),
  8315. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  8316. {}
  8317. ReusableStringStream::~ReusableStringStream() {
  8318. static_cast<std::ostringstream*>( m_oss )->str("");
  8319. m_oss->clear();
  8320. Singleton<StringStreams>::getMutable().release( m_index );
  8321. }
  8322. auto ReusableStringStream::str() const -> std::string {
  8323. return static_cast<std::ostringstream*>( m_oss )->str();
  8324. }
  8325. ///////////////////////////////////////////////////////////////////////////
  8326. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  8327. std::ostream& cout() { return std::cout; }
  8328. std::ostream& cerr() { return std::cerr; }
  8329. std::ostream& clog() { return std::clog; }
  8330. #endif
  8331. }
  8332. // end catch_stream.cpp
  8333. // start catch_string_manip.cpp
  8334. #include <algorithm>
  8335. #include <ostream>
  8336. #include <cstring>
  8337. #include <cctype>
  8338. namespace Catch {
  8339. namespace {
  8340. char toLowerCh(char c) {
  8341. return static_cast<char>( std::tolower( c ) );
  8342. }
  8343. }
  8344. bool startsWith( std::string const& s, std::string const& prefix ) {
  8345. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  8346. }
  8347. bool startsWith( std::string const& s, char prefix ) {
  8348. return !s.empty() && s[0] == prefix;
  8349. }
  8350. bool endsWith( std::string const& s, std::string const& suffix ) {
  8351. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  8352. }
  8353. bool endsWith( std::string const& s, char suffix ) {
  8354. return !s.empty() && s[s.size()-1] == suffix;
  8355. }
  8356. bool contains( std::string const& s, std::string const& infix ) {
  8357. return s.find( infix ) != std::string::npos;
  8358. }
  8359. void toLowerInPlace( std::string& s ) {
  8360. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  8361. }
  8362. std::string toLower( std::string const& s ) {
  8363. std::string lc = s;
  8364. toLowerInPlace( lc );
  8365. return lc;
  8366. }
  8367. std::string trim( std::string const& str ) {
  8368. static char const* whitespaceChars = "\n\r\t ";
  8369. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  8370. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  8371. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  8372. }
  8373. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  8374. bool replaced = false;
  8375. std::size_t i = str.find( replaceThis );
  8376. while( i != std::string::npos ) {
  8377. replaced = true;
  8378. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  8379. if( i < str.size()-withThis.size() )
  8380. i = str.find( replaceThis, i+withThis.size() );
  8381. else
  8382. i = std::string::npos;
  8383. }
  8384. return replaced;
  8385. }
  8386. pluralise::pluralise( std::size_t count, std::string const& label )
  8387. : m_count( count ),
  8388. m_label( label )
  8389. {}
  8390. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  8391. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  8392. if( pluraliser.m_count != 1 )
  8393. os << 's';
  8394. return os;
  8395. }
  8396. }
  8397. // end catch_string_manip.cpp
  8398. // start catch_stringref.cpp
  8399. #if defined(__clang__)
  8400. # pragma clang diagnostic push
  8401. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8402. #endif
  8403. #include <ostream>
  8404. #include <cstring>
  8405. #include <cstdint>
  8406. namespace {
  8407. const uint32_t byte_2_lead = 0xC0;
  8408. const uint32_t byte_3_lead = 0xE0;
  8409. const uint32_t byte_4_lead = 0xF0;
  8410. }
  8411. namespace Catch {
  8412. StringRef::StringRef( char const* rawChars ) noexcept
  8413. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  8414. {}
  8415. StringRef::operator std::string() const {
  8416. return std::string( m_start, m_size );
  8417. }
  8418. void StringRef::swap( StringRef& other ) noexcept {
  8419. std::swap( m_start, other.m_start );
  8420. std::swap( m_size, other.m_size );
  8421. std::swap( m_data, other.m_data );
  8422. }
  8423. auto StringRef::c_str() const -> char const* {
  8424. if( isSubstring() )
  8425. const_cast<StringRef*>( this )->takeOwnership();
  8426. return m_start;
  8427. }
  8428. auto StringRef::currentData() const noexcept -> char const* {
  8429. return m_start;
  8430. }
  8431. auto StringRef::isOwned() const noexcept -> bool {
  8432. return m_data != nullptr;
  8433. }
  8434. auto StringRef::isSubstring() const noexcept -> bool {
  8435. return m_start[m_size] != '\0';
  8436. }
  8437. void StringRef::takeOwnership() {
  8438. if( !isOwned() ) {
  8439. m_data = new char[m_size+1];
  8440. memcpy( m_data, m_start, m_size );
  8441. m_data[m_size] = '\0';
  8442. m_start = m_data;
  8443. }
  8444. }
  8445. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  8446. if( start < m_size )
  8447. return StringRef( m_start+start, size );
  8448. else
  8449. return StringRef();
  8450. }
  8451. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  8452. return
  8453. size() == other.size() &&
  8454. (std::strncmp( m_start, other.m_start, size() ) == 0);
  8455. }
  8456. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  8457. return !operator==( other );
  8458. }
  8459. auto StringRef::operator[](size_type index) const noexcept -> char {
  8460. return m_start[index];
  8461. }
  8462. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  8463. size_type noChars = m_size;
  8464. // Make adjustments for uft encodings
  8465. for( size_type i=0; i < m_size; ++i ) {
  8466. char c = m_start[i];
  8467. if( ( c & byte_2_lead ) == byte_2_lead ) {
  8468. noChars--;
  8469. if (( c & byte_3_lead ) == byte_3_lead )
  8470. noChars--;
  8471. if( ( c & byte_4_lead ) == byte_4_lead )
  8472. noChars--;
  8473. }
  8474. }
  8475. return noChars;
  8476. }
  8477. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  8478. std::string str;
  8479. str.reserve( lhs.size() + rhs.size() );
  8480. str += lhs;
  8481. str += rhs;
  8482. return str;
  8483. }
  8484. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  8485. return std::string( lhs ) + std::string( rhs );
  8486. }
  8487. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  8488. return std::string( lhs ) + std::string( rhs );
  8489. }
  8490. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  8491. return os.write(str.currentData(), str.size());
  8492. }
  8493. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  8494. lhs.append(rhs.currentData(), rhs.size());
  8495. return lhs;
  8496. }
  8497. } // namespace Catch
  8498. #if defined(__clang__)
  8499. # pragma clang diagnostic pop
  8500. #endif
  8501. // end catch_stringref.cpp
  8502. // start catch_tag_alias.cpp
  8503. namespace Catch {
  8504. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  8505. }
  8506. // end catch_tag_alias.cpp
  8507. // start catch_tag_alias_autoregistrar.cpp
  8508. namespace Catch {
  8509. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  8510. CATCH_TRY {
  8511. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  8512. } CATCH_CATCH_ALL {
  8513. // Do not throw when constructing global objects, instead register the exception to be processed later
  8514. getMutableRegistryHub().registerStartupException();
  8515. }
  8516. }
  8517. }
  8518. // end catch_tag_alias_autoregistrar.cpp
  8519. // start catch_tag_alias_registry.cpp
  8520. #include <sstream>
  8521. namespace Catch {
  8522. TagAliasRegistry::~TagAliasRegistry() {}
  8523. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  8524. auto it = m_registry.find( alias );
  8525. if( it != m_registry.end() )
  8526. return &(it->second);
  8527. else
  8528. return nullptr;
  8529. }
  8530. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  8531. std::string expandedTestSpec = unexpandedTestSpec;
  8532. for( auto const& registryKvp : m_registry ) {
  8533. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  8534. if( pos != std::string::npos ) {
  8535. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  8536. registryKvp.second.tag +
  8537. expandedTestSpec.substr( pos + registryKvp.first.size() );
  8538. }
  8539. }
  8540. return expandedTestSpec;
  8541. }
  8542. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  8543. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  8544. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  8545. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  8546. "error: tag alias, '" << alias << "' already registered.\n"
  8547. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  8548. << "\tRedefined at: " << lineInfo );
  8549. }
  8550. ITagAliasRegistry::~ITagAliasRegistry() {}
  8551. ITagAliasRegistry const& ITagAliasRegistry::get() {
  8552. return getRegistryHub().getTagAliasRegistry();
  8553. }
  8554. } // end namespace Catch
  8555. // end catch_tag_alias_registry.cpp
  8556. // start catch_test_case_info.cpp
  8557. #include <cctype>
  8558. #include <exception>
  8559. #include <algorithm>
  8560. #include <sstream>
  8561. namespace Catch {
  8562. namespace {
  8563. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  8564. if( startsWith( tag, '.' ) ||
  8565. tag == "!hide" )
  8566. return TestCaseInfo::IsHidden;
  8567. else if( tag == "!throws" )
  8568. return TestCaseInfo::Throws;
  8569. else if( tag == "!shouldfail" )
  8570. return TestCaseInfo::ShouldFail;
  8571. else if( tag == "!mayfail" )
  8572. return TestCaseInfo::MayFail;
  8573. else if( tag == "!nonportable" )
  8574. return TestCaseInfo::NonPortable;
  8575. else if( tag == "!benchmark" )
  8576. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  8577. else
  8578. return TestCaseInfo::None;
  8579. }
  8580. bool isReservedTag( std::string const& tag ) {
  8581. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  8582. }
  8583. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  8584. CATCH_ENFORCE( !isReservedTag(tag),
  8585. "Tag name: [" << tag << "] is not allowed.\n"
  8586. << "Tag names starting with non alpha-numeric characters are reserved\n"
  8587. << _lineInfo );
  8588. }
  8589. }
  8590. TestCase makeTestCase( ITestInvoker* _testCase,
  8591. std::string const& _className,
  8592. NameAndTags const& nameAndTags,
  8593. SourceLineInfo const& _lineInfo )
  8594. {
  8595. bool isHidden = false;
  8596. // Parse out tags
  8597. std::vector<std::string> tags;
  8598. std::string desc, tag;
  8599. bool inTag = false;
  8600. std::string _descOrTags = nameAndTags.tags;
  8601. for (char c : _descOrTags) {
  8602. if( !inTag ) {
  8603. if( c == '[' )
  8604. inTag = true;
  8605. else
  8606. desc += c;
  8607. }
  8608. else {
  8609. if( c == ']' ) {
  8610. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  8611. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  8612. isHidden = true;
  8613. else if( prop == TestCaseInfo::None )
  8614. enforceNotReservedTag( tag, _lineInfo );
  8615. tags.push_back( tag );
  8616. tag.clear();
  8617. inTag = false;
  8618. }
  8619. else
  8620. tag += c;
  8621. }
  8622. }
  8623. if( isHidden ) {
  8624. tags.push_back( "." );
  8625. }
  8626. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  8627. return TestCase( _testCase, std::move(info) );
  8628. }
  8629. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  8630. std::sort(begin(tags), end(tags));
  8631. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  8632. testCaseInfo.lcaseTags.clear();
  8633. for( auto const& tag : tags ) {
  8634. std::string lcaseTag = toLower( tag );
  8635. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  8636. testCaseInfo.lcaseTags.push_back( lcaseTag );
  8637. }
  8638. testCaseInfo.tags = std::move(tags);
  8639. }
  8640. TestCaseInfo::TestCaseInfo( std::string const& _name,
  8641. std::string const& _className,
  8642. std::string const& _description,
  8643. std::vector<std::string> const& _tags,
  8644. SourceLineInfo const& _lineInfo )
  8645. : name( _name ),
  8646. className( _className ),
  8647. description( _description ),
  8648. lineInfo( _lineInfo ),
  8649. properties( None )
  8650. {
  8651. setTags( *this, _tags );
  8652. }
  8653. bool TestCaseInfo::isHidden() const {
  8654. return ( properties & IsHidden ) != 0;
  8655. }
  8656. bool TestCaseInfo::throws() const {
  8657. return ( properties & Throws ) != 0;
  8658. }
  8659. bool TestCaseInfo::okToFail() const {
  8660. return ( properties & (ShouldFail | MayFail ) ) != 0;
  8661. }
  8662. bool TestCaseInfo::expectedToFail() const {
  8663. return ( properties & (ShouldFail ) ) != 0;
  8664. }
  8665. std::string TestCaseInfo::tagsAsString() const {
  8666. std::string ret;
  8667. // '[' and ']' per tag
  8668. std::size_t full_size = 2 * tags.size();
  8669. for (const auto& tag : tags) {
  8670. full_size += tag.size();
  8671. }
  8672. ret.reserve(full_size);
  8673. for (const auto& tag : tags) {
  8674. ret.push_back('[');
  8675. ret.append(tag);
  8676. ret.push_back(']');
  8677. }
  8678. return ret;
  8679. }
  8680. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  8681. TestCase TestCase::withName( std::string const& _newName ) const {
  8682. TestCase other( *this );
  8683. other.name = _newName;
  8684. return other;
  8685. }
  8686. void TestCase::invoke() const {
  8687. test->invoke();
  8688. }
  8689. bool TestCase::operator == ( TestCase const& other ) const {
  8690. return test.get() == other.test.get() &&
  8691. name == other.name &&
  8692. className == other.className;
  8693. }
  8694. bool TestCase::operator < ( TestCase const& other ) const {
  8695. return name < other.name;
  8696. }
  8697. TestCaseInfo const& TestCase::getTestCaseInfo() const
  8698. {
  8699. return *this;
  8700. }
  8701. } // end namespace Catch
  8702. // end catch_test_case_info.cpp
  8703. // start catch_test_case_registry_impl.cpp
  8704. #include <sstream>
  8705. namespace Catch {
  8706. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  8707. std::vector<TestCase> sorted = unsortedTestCases;
  8708. switch( config.runOrder() ) {
  8709. case RunTests::InLexicographicalOrder:
  8710. std::sort( sorted.begin(), sorted.end() );
  8711. break;
  8712. case RunTests::InRandomOrder:
  8713. seedRng( config );
  8714. std::shuffle( sorted.begin(), sorted.end(), rng() );
  8715. break;
  8716. case RunTests::InDeclarationOrder:
  8717. // already in declaration order
  8718. break;
  8719. }
  8720. return sorted;
  8721. }
  8722. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  8723. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  8724. }
  8725. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  8726. std::set<TestCase> seenFunctions;
  8727. for( auto const& function : functions ) {
  8728. auto prev = seenFunctions.insert( function );
  8729. CATCH_ENFORCE( prev.second,
  8730. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  8731. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  8732. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  8733. }
  8734. }
  8735. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  8736. std::vector<TestCase> filtered;
  8737. filtered.reserve( testCases.size() );
  8738. for( auto const& testCase : testCases )
  8739. if( matchTest( testCase, testSpec, config ) )
  8740. filtered.push_back( testCase );
  8741. return filtered;
  8742. }
  8743. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  8744. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  8745. }
  8746. void TestRegistry::registerTest( TestCase const& testCase ) {
  8747. std::string name = testCase.getTestCaseInfo().name;
  8748. if( name.empty() ) {
  8749. ReusableStringStream rss;
  8750. rss << "Anonymous test case " << ++m_unnamedCount;
  8751. return registerTest( testCase.withName( rss.str() ) );
  8752. }
  8753. m_functions.push_back( testCase );
  8754. }
  8755. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  8756. return m_functions;
  8757. }
  8758. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  8759. if( m_sortedFunctions.empty() )
  8760. enforceNoDuplicateTestCases( m_functions );
  8761. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  8762. m_sortedFunctions = sortTests( config, m_functions );
  8763. m_currentSortOrder = config.runOrder();
  8764. }
  8765. return m_sortedFunctions;
  8766. }
  8767. ///////////////////////////////////////////////////////////////////////////
  8768. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  8769. void TestInvokerAsFunction::invoke() const {
  8770. m_testAsFunction();
  8771. }
  8772. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  8773. std::string className = classOrQualifiedMethodName;
  8774. if( startsWith( className, '&' ) )
  8775. {
  8776. std::size_t lastColons = className.rfind( "::" );
  8777. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  8778. if( penultimateColons == std::string::npos )
  8779. penultimateColons = 1;
  8780. className = className.substr( penultimateColons, lastColons-penultimateColons );
  8781. }
  8782. return className;
  8783. }
  8784. } // end namespace Catch
  8785. // end catch_test_case_registry_impl.cpp
  8786. // start catch_test_case_tracker.cpp
  8787. #include <algorithm>
  8788. #include <cassert>
  8789. #include <stdexcept>
  8790. #include <memory>
  8791. #include <sstream>
  8792. #if defined(__clang__)
  8793. # pragma clang diagnostic push
  8794. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8795. #endif
  8796. namespace Catch {
  8797. namespace TestCaseTracking {
  8798. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  8799. : name( _name ),
  8800. location( _location )
  8801. {}
  8802. ITracker::~ITracker() = default;
  8803. TrackerContext& TrackerContext::instance() {
  8804. static TrackerContext s_instance;
  8805. return s_instance;
  8806. }
  8807. ITracker& TrackerContext::startRun() {
  8808. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  8809. m_currentTracker = nullptr;
  8810. m_runState = Executing;
  8811. return *m_rootTracker;
  8812. }
  8813. void TrackerContext::endRun() {
  8814. m_rootTracker.reset();
  8815. m_currentTracker = nullptr;
  8816. m_runState = NotStarted;
  8817. }
  8818. void TrackerContext::startCycle() {
  8819. m_currentTracker = m_rootTracker.get();
  8820. m_runState = Executing;
  8821. }
  8822. void TrackerContext::completeCycle() {
  8823. m_runState = CompletedCycle;
  8824. }
  8825. bool TrackerContext::completedCycle() const {
  8826. return m_runState == CompletedCycle;
  8827. }
  8828. ITracker& TrackerContext::currentTracker() {
  8829. return *m_currentTracker;
  8830. }
  8831. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  8832. m_currentTracker = tracker;
  8833. }
  8834. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8835. : m_nameAndLocation( nameAndLocation ),
  8836. m_ctx( ctx ),
  8837. m_parent( parent )
  8838. {}
  8839. NameAndLocation const& TrackerBase::nameAndLocation() const {
  8840. return m_nameAndLocation;
  8841. }
  8842. bool TrackerBase::isComplete() const {
  8843. return m_runState == CompletedSuccessfully || m_runState == Failed;
  8844. }
  8845. bool TrackerBase::isSuccessfullyCompleted() const {
  8846. return m_runState == CompletedSuccessfully;
  8847. }
  8848. bool TrackerBase::isOpen() const {
  8849. return m_runState != NotStarted && !isComplete();
  8850. }
  8851. bool TrackerBase::hasChildren() const {
  8852. return !m_children.empty();
  8853. }
  8854. void TrackerBase::addChild( ITrackerPtr const& child ) {
  8855. m_children.push_back( child );
  8856. }
  8857. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  8858. auto it = std::find_if( m_children.begin(), m_children.end(),
  8859. [&nameAndLocation]( ITrackerPtr const& tracker ){
  8860. return
  8861. tracker->nameAndLocation().location == nameAndLocation.location &&
  8862. tracker->nameAndLocation().name == nameAndLocation.name;
  8863. } );
  8864. return( it != m_children.end() )
  8865. ? *it
  8866. : nullptr;
  8867. }
  8868. ITracker& TrackerBase::parent() {
  8869. assert( m_parent ); // Should always be non-null except for root
  8870. return *m_parent;
  8871. }
  8872. void TrackerBase::openChild() {
  8873. if( m_runState != ExecutingChildren ) {
  8874. m_runState = ExecutingChildren;
  8875. if( m_parent )
  8876. m_parent->openChild();
  8877. }
  8878. }
  8879. bool TrackerBase::isSectionTracker() const { return false; }
  8880. bool TrackerBase::isIndexTracker() const { return false; }
  8881. void TrackerBase::open() {
  8882. m_runState = Executing;
  8883. moveToThis();
  8884. if( m_parent )
  8885. m_parent->openChild();
  8886. }
  8887. void TrackerBase::close() {
  8888. // Close any still open children (e.g. generators)
  8889. while( &m_ctx.currentTracker() != this )
  8890. m_ctx.currentTracker().close();
  8891. switch( m_runState ) {
  8892. case NeedsAnotherRun:
  8893. break;
  8894. case Executing:
  8895. m_runState = CompletedSuccessfully;
  8896. break;
  8897. case ExecutingChildren:
  8898. if( m_children.empty() || m_children.back()->isComplete() )
  8899. m_runState = CompletedSuccessfully;
  8900. break;
  8901. case NotStarted:
  8902. case CompletedSuccessfully:
  8903. case Failed:
  8904. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  8905. default:
  8906. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  8907. }
  8908. moveToParent();
  8909. m_ctx.completeCycle();
  8910. }
  8911. void TrackerBase::fail() {
  8912. m_runState = Failed;
  8913. if( m_parent )
  8914. m_parent->markAsNeedingAnotherRun();
  8915. moveToParent();
  8916. m_ctx.completeCycle();
  8917. }
  8918. void TrackerBase::markAsNeedingAnotherRun() {
  8919. m_runState = NeedsAnotherRun;
  8920. }
  8921. void TrackerBase::moveToParent() {
  8922. assert( m_parent );
  8923. m_ctx.setCurrentTracker( m_parent );
  8924. }
  8925. void TrackerBase::moveToThis() {
  8926. m_ctx.setCurrentTracker( this );
  8927. }
  8928. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8929. : TrackerBase( nameAndLocation, ctx, parent )
  8930. {
  8931. if( parent ) {
  8932. while( !parent->isSectionTracker() )
  8933. parent = &parent->parent();
  8934. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  8935. addNextFilters( parentSection.m_filters );
  8936. }
  8937. }
  8938. bool SectionTracker::isSectionTracker() const { return true; }
  8939. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  8940. std::shared_ptr<SectionTracker> section;
  8941. ITracker& currentTracker = ctx.currentTracker();
  8942. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8943. assert( childTracker );
  8944. assert( childTracker->isSectionTracker() );
  8945. section = std::static_pointer_cast<SectionTracker>( childTracker );
  8946. }
  8947. else {
  8948. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  8949. currentTracker.addChild( section );
  8950. }
  8951. if( !ctx.completedCycle() )
  8952. section->tryOpen();
  8953. return *section;
  8954. }
  8955. void SectionTracker::tryOpen() {
  8956. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  8957. open();
  8958. }
  8959. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  8960. if( !filters.empty() ) {
  8961. m_filters.push_back(""); // Root - should never be consulted
  8962. m_filters.push_back(""); // Test Case - not a section filter
  8963. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  8964. }
  8965. }
  8966. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  8967. if( filters.size() > 1 )
  8968. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  8969. }
  8970. IndexTracker::IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size )
  8971. : TrackerBase( nameAndLocation, ctx, parent ),
  8972. m_size( size )
  8973. {}
  8974. bool IndexTracker::isIndexTracker() const { return true; }
  8975. IndexTracker& IndexTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) {
  8976. std::shared_ptr<IndexTracker> tracker;
  8977. ITracker& currentTracker = ctx.currentTracker();
  8978. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  8979. assert( childTracker );
  8980. assert( childTracker->isIndexTracker() );
  8981. tracker = std::static_pointer_cast<IndexTracker>( childTracker );
  8982. }
  8983. else {
  8984. tracker = std::make_shared<IndexTracker>( nameAndLocation, ctx, &currentTracker, size );
  8985. currentTracker.addChild( tracker );
  8986. }
  8987. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  8988. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  8989. tracker->moveNext();
  8990. tracker->open();
  8991. }
  8992. return *tracker;
  8993. }
  8994. int IndexTracker::index() const { return m_index; }
  8995. void IndexTracker::moveNext() {
  8996. m_index++;
  8997. m_children.clear();
  8998. }
  8999. void IndexTracker::close() {
  9000. TrackerBase::close();
  9001. if( m_runState == CompletedSuccessfully && m_index < m_size-1 )
  9002. m_runState = Executing;
  9003. }
  9004. } // namespace TestCaseTracking
  9005. using TestCaseTracking::ITracker;
  9006. using TestCaseTracking::TrackerContext;
  9007. using TestCaseTracking::SectionTracker;
  9008. using TestCaseTracking::IndexTracker;
  9009. } // namespace Catch
  9010. #if defined(__clang__)
  9011. # pragma clang diagnostic pop
  9012. #endif
  9013. // end catch_test_case_tracker.cpp
  9014. // start catch_test_registry.cpp
  9015. namespace Catch {
  9016. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  9017. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  9018. }
  9019. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  9020. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  9021. CATCH_TRY {
  9022. getMutableRegistryHub()
  9023. .registerTest(
  9024. makeTestCase(
  9025. invoker,
  9026. extractClassName( classOrMethod ),
  9027. nameAndTags,
  9028. lineInfo));
  9029. } CATCH_CATCH_ALL {
  9030. // Do not throw when constructing global objects, instead register the exception to be processed later
  9031. getMutableRegistryHub().registerStartupException();
  9032. }
  9033. }
  9034. AutoReg::~AutoReg() = default;
  9035. }
  9036. // end catch_test_registry.cpp
  9037. // start catch_test_spec.cpp
  9038. #include <algorithm>
  9039. #include <string>
  9040. #include <vector>
  9041. #include <memory>
  9042. namespace Catch {
  9043. TestSpec::Pattern::~Pattern() = default;
  9044. TestSpec::NamePattern::~NamePattern() = default;
  9045. TestSpec::TagPattern::~TagPattern() = default;
  9046. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  9047. TestSpec::NamePattern::NamePattern( std::string const& name )
  9048. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  9049. {}
  9050. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  9051. return m_wildcardPattern.matches( toLower( testCase.name ) );
  9052. }
  9053. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  9054. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  9055. return std::find(begin(testCase.lcaseTags),
  9056. end(testCase.lcaseTags),
  9057. m_tag) != end(testCase.lcaseTags);
  9058. }
  9059. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  9060. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  9061. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  9062. // All patterns in a filter must match for the filter to be a match
  9063. for( auto const& pattern : m_patterns ) {
  9064. if( !pattern->matches( testCase ) )
  9065. return false;
  9066. }
  9067. return true;
  9068. }
  9069. bool TestSpec::hasFilters() const {
  9070. return !m_filters.empty();
  9071. }
  9072. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  9073. // A TestSpec matches if any filter matches
  9074. for( auto const& filter : m_filters )
  9075. if( filter.matches( testCase ) )
  9076. return true;
  9077. return false;
  9078. }
  9079. }
  9080. // end catch_test_spec.cpp
  9081. // start catch_test_spec_parser.cpp
  9082. namespace Catch {
  9083. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  9084. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  9085. m_mode = None;
  9086. m_exclusion = false;
  9087. m_start = std::string::npos;
  9088. m_arg = m_tagAliases->expandAliases( arg );
  9089. m_escapeChars.clear();
  9090. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  9091. visitChar( m_arg[m_pos] );
  9092. if( m_mode == Name )
  9093. addPattern<TestSpec::NamePattern>();
  9094. return *this;
  9095. }
  9096. TestSpec TestSpecParser::testSpec() {
  9097. addFilter();
  9098. return m_testSpec;
  9099. }
  9100. void TestSpecParser::visitChar( char c ) {
  9101. if( m_mode == None ) {
  9102. switch( c ) {
  9103. case ' ': return;
  9104. case '~': m_exclusion = true; return;
  9105. case '[': return startNewMode( Tag, ++m_pos );
  9106. case '"': return startNewMode( QuotedName, ++m_pos );
  9107. case '\\': return escape();
  9108. default: startNewMode( Name, m_pos ); break;
  9109. }
  9110. }
  9111. if( m_mode == Name ) {
  9112. if( c == ',' ) {
  9113. addPattern<TestSpec::NamePattern>();
  9114. addFilter();
  9115. }
  9116. else if( c == '[' ) {
  9117. if( subString() == "exclude:" )
  9118. m_exclusion = true;
  9119. else
  9120. addPattern<TestSpec::NamePattern>();
  9121. startNewMode( Tag, ++m_pos );
  9122. }
  9123. else if( c == '\\' )
  9124. escape();
  9125. }
  9126. else if( m_mode == EscapedName )
  9127. m_mode = Name;
  9128. else if( m_mode == QuotedName && c == '"' )
  9129. addPattern<TestSpec::NamePattern>();
  9130. else if( m_mode == Tag && c == ']' )
  9131. addPattern<TestSpec::TagPattern>();
  9132. }
  9133. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  9134. m_mode = mode;
  9135. m_start = start;
  9136. }
  9137. void TestSpecParser::escape() {
  9138. if( m_mode == None )
  9139. m_start = m_pos;
  9140. m_mode = EscapedName;
  9141. m_escapeChars.push_back( m_pos );
  9142. }
  9143. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  9144. void TestSpecParser::addFilter() {
  9145. if( !m_currentFilter.m_patterns.empty() ) {
  9146. m_testSpec.m_filters.push_back( m_currentFilter );
  9147. m_currentFilter = TestSpec::Filter();
  9148. }
  9149. }
  9150. TestSpec parseTestSpec( std::string const& arg ) {
  9151. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  9152. }
  9153. } // namespace Catch
  9154. // end catch_test_spec_parser.cpp
  9155. // start catch_timer.cpp
  9156. #include <chrono>
  9157. static const uint64_t nanosecondsInSecond = 1000000000;
  9158. namespace Catch {
  9159. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  9160. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  9161. }
  9162. namespace {
  9163. auto estimateClockResolution() -> uint64_t {
  9164. uint64_t sum = 0;
  9165. static const uint64_t iterations = 1000000;
  9166. auto startTime = getCurrentNanosecondsSinceEpoch();
  9167. for( std::size_t i = 0; i < iterations; ++i ) {
  9168. uint64_t ticks;
  9169. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  9170. do {
  9171. ticks = getCurrentNanosecondsSinceEpoch();
  9172. } while( ticks == baseTicks );
  9173. auto delta = ticks - baseTicks;
  9174. sum += delta;
  9175. // If we have been calibrating for over 3 seconds -- the clock
  9176. // is terrible and we should move on.
  9177. // TBD: How to signal that the measured resolution is probably wrong?
  9178. if (ticks > startTime + 3 * nanosecondsInSecond) {
  9179. return sum / i;
  9180. }
  9181. }
  9182. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  9183. // - and potentially do more iterations if there's a high variance.
  9184. return sum/iterations;
  9185. }
  9186. }
  9187. auto getEstimatedClockResolution() -> uint64_t {
  9188. static auto s_resolution = estimateClockResolution();
  9189. return s_resolution;
  9190. }
  9191. void Timer::start() {
  9192. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  9193. }
  9194. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  9195. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  9196. }
  9197. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  9198. return getElapsedNanoseconds()/1000;
  9199. }
  9200. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  9201. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  9202. }
  9203. auto Timer::getElapsedSeconds() const -> double {
  9204. return getElapsedMicroseconds()/1000000.0;
  9205. }
  9206. } // namespace Catch
  9207. // end catch_timer.cpp
  9208. // start catch_tostring.cpp
  9209. #if defined(__clang__)
  9210. # pragma clang diagnostic push
  9211. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  9212. # pragma clang diagnostic ignored "-Wglobal-constructors"
  9213. #endif
  9214. // Enable specific decls locally
  9215. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  9216. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  9217. #endif
  9218. #include <cmath>
  9219. #include <iomanip>
  9220. namespace Catch {
  9221. namespace Detail {
  9222. const std::string unprintableString = "{?}";
  9223. namespace {
  9224. const int hexThreshold = 255;
  9225. struct Endianness {
  9226. enum Arch { Big, Little };
  9227. static Arch which() {
  9228. union _{
  9229. int asInt;
  9230. char asChar[sizeof (int)];
  9231. } u;
  9232. u.asInt = 1;
  9233. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  9234. }
  9235. };
  9236. }
  9237. std::string rawMemoryToString( const void *object, std::size_t size ) {
  9238. // Reverse order for little endian architectures
  9239. int i = 0, end = static_cast<int>( size ), inc = 1;
  9240. if( Endianness::which() == Endianness::Little ) {
  9241. i = end-1;
  9242. end = inc = -1;
  9243. }
  9244. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  9245. ReusableStringStream rss;
  9246. rss << "0x" << std::setfill('0') << std::hex;
  9247. for( ; i != end; i += inc )
  9248. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  9249. return rss.str();
  9250. }
  9251. }
  9252. template<typename T>
  9253. std::string fpToString( T value, int precision ) {
  9254. if (std::isnan(value)) {
  9255. return "nan";
  9256. }
  9257. ReusableStringStream rss;
  9258. rss << std::setprecision( precision )
  9259. << std::fixed
  9260. << value;
  9261. std::string d = rss.str();
  9262. std::size_t i = d.find_last_not_of( '0' );
  9263. if( i != std::string::npos && i != d.size()-1 ) {
  9264. if( d[i] == '.' )
  9265. i++;
  9266. d = d.substr( 0, i+1 );
  9267. }
  9268. return d;
  9269. }
  9270. //// ======================================================= ////
  9271. //
  9272. // Out-of-line defs for full specialization of StringMaker
  9273. //
  9274. //// ======================================================= ////
  9275. std::string StringMaker<std::string>::convert(const std::string& str) {
  9276. if (!getCurrentContext().getConfig()->showInvisibles()) {
  9277. return '"' + str + '"';
  9278. }
  9279. std::string s("\"");
  9280. for (char c : str) {
  9281. switch (c) {
  9282. case '\n':
  9283. s.append("\\n");
  9284. break;
  9285. case '\t':
  9286. s.append("\\t");
  9287. break;
  9288. default:
  9289. s.push_back(c);
  9290. break;
  9291. }
  9292. }
  9293. s.append("\"");
  9294. return s;
  9295. }
  9296. #ifdef CATCH_CONFIG_WCHAR
  9297. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  9298. std::string s;
  9299. s.reserve(wstr.size());
  9300. for (auto c : wstr) {
  9301. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  9302. }
  9303. return ::Catch::Detail::stringify(s);
  9304. }
  9305. #endif
  9306. std::string StringMaker<char const*>::convert(char const* str) {
  9307. if (str) {
  9308. return ::Catch::Detail::stringify(std::string{ str });
  9309. } else {
  9310. return{ "{null string}" };
  9311. }
  9312. }
  9313. std::string StringMaker<char*>::convert(char* str) {
  9314. if (str) {
  9315. return ::Catch::Detail::stringify(std::string{ str });
  9316. } else {
  9317. return{ "{null string}" };
  9318. }
  9319. }
  9320. #ifdef CATCH_CONFIG_WCHAR
  9321. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  9322. if (str) {
  9323. return ::Catch::Detail::stringify(std::wstring{ str });
  9324. } else {
  9325. return{ "{null string}" };
  9326. }
  9327. }
  9328. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  9329. if (str) {
  9330. return ::Catch::Detail::stringify(std::wstring{ str });
  9331. } else {
  9332. return{ "{null string}" };
  9333. }
  9334. }
  9335. #endif
  9336. std::string StringMaker<int>::convert(int value) {
  9337. return ::Catch::Detail::stringify(static_cast<long long>(value));
  9338. }
  9339. std::string StringMaker<long>::convert(long value) {
  9340. return ::Catch::Detail::stringify(static_cast<long long>(value));
  9341. }
  9342. std::string StringMaker<long long>::convert(long long value) {
  9343. ReusableStringStream rss;
  9344. rss << value;
  9345. if (value > Detail::hexThreshold) {
  9346. rss << " (0x" << std::hex << value << ')';
  9347. }
  9348. return rss.str();
  9349. }
  9350. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  9351. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  9352. }
  9353. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  9354. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  9355. }
  9356. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  9357. ReusableStringStream rss;
  9358. rss << value;
  9359. if (value > Detail::hexThreshold) {
  9360. rss << " (0x" << std::hex << value << ')';
  9361. }
  9362. return rss.str();
  9363. }
  9364. std::string StringMaker<bool>::convert(bool b) {
  9365. return b ? "true" : "false";
  9366. }
  9367. std::string StringMaker<char>::convert(char value) {
  9368. if (value == '\r') {
  9369. return "'\\r'";
  9370. } else if (value == '\f') {
  9371. return "'\\f'";
  9372. } else if (value == '\n') {
  9373. return "'\\n'";
  9374. } else if (value == '\t') {
  9375. return "'\\t'";
  9376. } else if ('\0' <= value && value < ' ') {
  9377. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  9378. } else {
  9379. char chstr[] = "' '";
  9380. chstr[1] = value;
  9381. return chstr;
  9382. }
  9383. }
  9384. std::string StringMaker<signed char>::convert(signed char c) {
  9385. return ::Catch::Detail::stringify(static_cast<char>(c));
  9386. }
  9387. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  9388. return ::Catch::Detail::stringify(static_cast<char>(c));
  9389. }
  9390. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  9391. return "nullptr";
  9392. }
  9393. std::string StringMaker<float>::convert(float value) {
  9394. return fpToString(value, 5) + 'f';
  9395. }
  9396. std::string StringMaker<double>::convert(double value) {
  9397. return fpToString(value, 10);
  9398. }
  9399. std::string ratio_string<std::atto>::symbol() { return "a"; }
  9400. std::string ratio_string<std::femto>::symbol() { return "f"; }
  9401. std::string ratio_string<std::pico>::symbol() { return "p"; }
  9402. std::string ratio_string<std::nano>::symbol() { return "n"; }
  9403. std::string ratio_string<std::micro>::symbol() { return "u"; }
  9404. std::string ratio_string<std::milli>::symbol() { return "m"; }
  9405. } // end namespace Catch
  9406. #if defined(__clang__)
  9407. # pragma clang diagnostic pop
  9408. #endif
  9409. // end catch_tostring.cpp
  9410. // start catch_totals.cpp
  9411. namespace Catch {
  9412. Counts Counts::operator - ( Counts const& other ) const {
  9413. Counts diff;
  9414. diff.passed = passed - other.passed;
  9415. diff.failed = failed - other.failed;
  9416. diff.failedButOk = failedButOk - other.failedButOk;
  9417. return diff;
  9418. }
  9419. Counts& Counts::operator += ( Counts const& other ) {
  9420. passed += other.passed;
  9421. failed += other.failed;
  9422. failedButOk += other.failedButOk;
  9423. return *this;
  9424. }
  9425. std::size_t Counts::total() const {
  9426. return passed + failed + failedButOk;
  9427. }
  9428. bool Counts::allPassed() const {
  9429. return failed == 0 && failedButOk == 0;
  9430. }
  9431. bool Counts::allOk() const {
  9432. return failed == 0;
  9433. }
  9434. Totals Totals::operator - ( Totals const& other ) const {
  9435. Totals diff;
  9436. diff.assertions = assertions - other.assertions;
  9437. diff.testCases = testCases - other.testCases;
  9438. return diff;
  9439. }
  9440. Totals& Totals::operator += ( Totals const& other ) {
  9441. assertions += other.assertions;
  9442. testCases += other.testCases;
  9443. return *this;
  9444. }
  9445. Totals Totals::delta( Totals const& prevTotals ) const {
  9446. Totals diff = *this - prevTotals;
  9447. if( diff.assertions.failed > 0 )
  9448. ++diff.testCases.failed;
  9449. else if( diff.assertions.failedButOk > 0 )
  9450. ++diff.testCases.failedButOk;
  9451. else
  9452. ++diff.testCases.passed;
  9453. return diff;
  9454. }
  9455. }
  9456. // end catch_totals.cpp
  9457. // start catch_uncaught_exceptions.cpp
  9458. #include <exception>
  9459. namespace Catch {
  9460. bool uncaught_exceptions() {
  9461. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  9462. return std::uncaught_exceptions() > 0;
  9463. #else
  9464. return std::uncaught_exception();
  9465. #endif
  9466. }
  9467. } // end namespace Catch
  9468. // end catch_uncaught_exceptions.cpp
  9469. // start catch_version.cpp
  9470. #include <ostream>
  9471. namespace Catch {
  9472. Version::Version
  9473. ( unsigned int _majorVersion,
  9474. unsigned int _minorVersion,
  9475. unsigned int _patchNumber,
  9476. char const * const _branchName,
  9477. unsigned int _buildNumber )
  9478. : majorVersion( _majorVersion ),
  9479. minorVersion( _minorVersion ),
  9480. patchNumber( _patchNumber ),
  9481. branchName( _branchName ),
  9482. buildNumber( _buildNumber )
  9483. {}
  9484. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  9485. os << version.majorVersion << '.'
  9486. << version.minorVersion << '.'
  9487. << version.patchNumber;
  9488. // branchName is never null -> 0th char is \0 if it is empty
  9489. if (version.branchName[0]) {
  9490. os << '-' << version.branchName
  9491. << '.' << version.buildNumber;
  9492. }
  9493. return os;
  9494. }
  9495. Version const& libraryVersion() {
  9496. static Version version( 2, 4, 0, "", 0 );
  9497. return version;
  9498. }
  9499. }
  9500. // end catch_version.cpp
  9501. // start catch_wildcard_pattern.cpp
  9502. #include <sstream>
  9503. namespace Catch {
  9504. WildcardPattern::WildcardPattern( std::string const& pattern,
  9505. CaseSensitive::Choice caseSensitivity )
  9506. : m_caseSensitivity( caseSensitivity ),
  9507. m_pattern( adjustCase( pattern ) )
  9508. {
  9509. if( startsWith( m_pattern, '*' ) ) {
  9510. m_pattern = m_pattern.substr( 1 );
  9511. m_wildcard = WildcardAtStart;
  9512. }
  9513. if( endsWith( m_pattern, '*' ) ) {
  9514. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  9515. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  9516. }
  9517. }
  9518. bool WildcardPattern::matches( std::string const& str ) const {
  9519. switch( m_wildcard ) {
  9520. case NoWildcard:
  9521. return m_pattern == adjustCase( str );
  9522. case WildcardAtStart:
  9523. return endsWith( adjustCase( str ), m_pattern );
  9524. case WildcardAtEnd:
  9525. return startsWith( adjustCase( str ), m_pattern );
  9526. case WildcardAtBothEnds:
  9527. return contains( adjustCase( str ), m_pattern );
  9528. default:
  9529. CATCH_INTERNAL_ERROR( "Unknown enum" );
  9530. }
  9531. }
  9532. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  9533. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  9534. }
  9535. }
  9536. // end catch_wildcard_pattern.cpp
  9537. // start catch_xmlwriter.cpp
  9538. #include <iomanip>
  9539. using uchar = unsigned char;
  9540. namespace Catch {
  9541. namespace {
  9542. size_t trailingBytes(unsigned char c) {
  9543. if ((c & 0xE0) == 0xC0) {
  9544. return 2;
  9545. }
  9546. if ((c & 0xF0) == 0xE0) {
  9547. return 3;
  9548. }
  9549. if ((c & 0xF8) == 0xF0) {
  9550. return 4;
  9551. }
  9552. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  9553. }
  9554. uint32_t headerValue(unsigned char c) {
  9555. if ((c & 0xE0) == 0xC0) {
  9556. return c & 0x1F;
  9557. }
  9558. if ((c & 0xF0) == 0xE0) {
  9559. return c & 0x0F;
  9560. }
  9561. if ((c & 0xF8) == 0xF0) {
  9562. return c & 0x07;
  9563. }
  9564. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  9565. }
  9566. void hexEscapeChar(std::ostream& os, unsigned char c) {
  9567. os << "\\x"
  9568. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  9569. << static_cast<int>(c);
  9570. }
  9571. } // anonymous namespace
  9572. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  9573. : m_str( str ),
  9574. m_forWhat( forWhat )
  9575. {}
  9576. void XmlEncode::encodeTo( std::ostream& os ) const {
  9577. // Apostrophe escaping not necessary if we always use " to write attributes
  9578. // (see: http://www.w3.org/TR/xml/#syntax)
  9579. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  9580. uchar c = m_str[idx];
  9581. switch (c) {
  9582. case '<': os << "&lt;"; break;
  9583. case '&': os << "&amp;"; break;
  9584. case '>':
  9585. // See: http://www.w3.org/TR/xml/#syntax
  9586. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  9587. os << "&gt;";
  9588. else
  9589. os << c;
  9590. break;
  9591. case '\"':
  9592. if (m_forWhat == ForAttributes)
  9593. os << "&quot;";
  9594. else
  9595. os << c;
  9596. break;
  9597. default:
  9598. // Check for control characters and invalid utf-8
  9599. // Escape control characters in standard ascii
  9600. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  9601. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  9602. hexEscapeChar(os, c);
  9603. break;
  9604. }
  9605. // Plain ASCII: Write it to stream
  9606. if (c < 0x7F) {
  9607. os << c;
  9608. break;
  9609. }
  9610. // UTF-8 territory
  9611. // Check if the encoding is valid and if it is not, hex escape bytes.
  9612. // Important: We do not check the exact decoded values for validity, only the encoding format
  9613. // First check that this bytes is a valid lead byte:
  9614. // This means that it is not encoded as 1111 1XXX
  9615. // Or as 10XX XXXX
  9616. if (c < 0xC0 ||
  9617. c >= 0xF8) {
  9618. hexEscapeChar(os, c);
  9619. break;
  9620. }
  9621. auto encBytes = trailingBytes(c);
  9622. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  9623. if (idx + encBytes - 1 >= m_str.size()) {
  9624. hexEscapeChar(os, c);
  9625. break;
  9626. }
  9627. // The header is valid, check data
  9628. // The next encBytes bytes must together be a valid utf-8
  9629. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  9630. bool valid = true;
  9631. uint32_t value = headerValue(c);
  9632. for (std::size_t n = 1; n < encBytes; ++n) {
  9633. uchar nc = m_str[idx + n];
  9634. valid &= ((nc & 0xC0) == 0x80);
  9635. value = (value << 6) | (nc & 0x3F);
  9636. }
  9637. if (
  9638. // Wrong bit pattern of following bytes
  9639. (!valid) ||
  9640. // Overlong encodings
  9641. (value < 0x80) ||
  9642. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  9643. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  9644. // Encoded value out of range
  9645. (value >= 0x110000)
  9646. ) {
  9647. hexEscapeChar(os, c);
  9648. break;
  9649. }
  9650. // If we got here, this is in fact a valid(ish) utf-8 sequence
  9651. for (std::size_t n = 0; n < encBytes; ++n) {
  9652. os << m_str[idx + n];
  9653. }
  9654. idx += encBytes - 1;
  9655. break;
  9656. }
  9657. }
  9658. }
  9659. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  9660. xmlEncode.encodeTo( os );
  9661. return os;
  9662. }
  9663. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  9664. : m_writer( writer )
  9665. {}
  9666. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  9667. : m_writer( other.m_writer ){
  9668. other.m_writer = nullptr;
  9669. }
  9670. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  9671. if ( m_writer ) {
  9672. m_writer->endElement();
  9673. }
  9674. m_writer = other.m_writer;
  9675. other.m_writer = nullptr;
  9676. return *this;
  9677. }
  9678. XmlWriter::ScopedElement::~ScopedElement() {
  9679. if( m_writer )
  9680. m_writer->endElement();
  9681. }
  9682. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  9683. m_writer->writeText( text, indent );
  9684. return *this;
  9685. }
  9686. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  9687. {
  9688. writeDeclaration();
  9689. }
  9690. XmlWriter::~XmlWriter() {
  9691. while( !m_tags.empty() )
  9692. endElement();
  9693. }
  9694. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  9695. ensureTagClosed();
  9696. newlineIfNecessary();
  9697. m_os << m_indent << '<' << name;
  9698. m_tags.push_back( name );
  9699. m_indent += " ";
  9700. m_tagIsOpen = true;
  9701. return *this;
  9702. }
  9703. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  9704. ScopedElement scoped( this );
  9705. startElement( name );
  9706. return scoped;
  9707. }
  9708. XmlWriter& XmlWriter::endElement() {
  9709. newlineIfNecessary();
  9710. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  9711. if( m_tagIsOpen ) {
  9712. m_os << "/>";
  9713. m_tagIsOpen = false;
  9714. }
  9715. else {
  9716. m_os << m_indent << "</" << m_tags.back() << ">";
  9717. }
  9718. m_os << std::endl;
  9719. m_tags.pop_back();
  9720. return *this;
  9721. }
  9722. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  9723. if( !name.empty() && !attribute.empty() )
  9724. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  9725. return *this;
  9726. }
  9727. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  9728. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  9729. return *this;
  9730. }
  9731. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  9732. if( !text.empty() ){
  9733. bool tagWasOpen = m_tagIsOpen;
  9734. ensureTagClosed();
  9735. if( tagWasOpen && indent )
  9736. m_os << m_indent;
  9737. m_os << XmlEncode( text );
  9738. m_needsNewline = true;
  9739. }
  9740. return *this;
  9741. }
  9742. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  9743. ensureTagClosed();
  9744. m_os << m_indent << "<!--" << text << "-->";
  9745. m_needsNewline = true;
  9746. return *this;
  9747. }
  9748. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  9749. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  9750. }
  9751. XmlWriter& XmlWriter::writeBlankLine() {
  9752. ensureTagClosed();
  9753. m_os << '\n';
  9754. return *this;
  9755. }
  9756. void XmlWriter::ensureTagClosed() {
  9757. if( m_tagIsOpen ) {
  9758. m_os << ">" << std::endl;
  9759. m_tagIsOpen = false;
  9760. }
  9761. }
  9762. void XmlWriter::writeDeclaration() {
  9763. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  9764. }
  9765. void XmlWriter::newlineIfNecessary() {
  9766. if( m_needsNewline ) {
  9767. m_os << std::endl;
  9768. m_needsNewline = false;
  9769. }
  9770. }
  9771. }
  9772. // end catch_xmlwriter.cpp
  9773. // start catch_reporter_bases.cpp
  9774. #include <cstring>
  9775. #include <cfloat>
  9776. #include <cstdio>
  9777. #include <cassert>
  9778. #include <memory>
  9779. namespace Catch {
  9780. void prepareExpandedExpression(AssertionResult& result) {
  9781. result.getExpandedExpression();
  9782. }
  9783. // Because formatting using c++ streams is stateful, drop down to C is required
  9784. // Alternatively we could use stringstream, but its performance is... not good.
  9785. std::string getFormattedDuration( double duration ) {
  9786. // Max exponent + 1 is required to represent the whole part
  9787. // + 1 for decimal point
  9788. // + 3 for the 3 decimal places
  9789. // + 1 for null terminator
  9790. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  9791. char buffer[maxDoubleSize];
  9792. // Save previous errno, to prevent sprintf from overwriting it
  9793. ErrnoGuard guard;
  9794. #ifdef _MSC_VER
  9795. sprintf_s(buffer, "%.3f", duration);
  9796. #else
  9797. sprintf(buffer, "%.3f", duration);
  9798. #endif
  9799. return std::string(buffer);
  9800. }
  9801. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  9802. :StreamingReporterBase(_config) {}
  9803. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  9804. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  9805. return false;
  9806. }
  9807. } // end namespace Catch
  9808. // end catch_reporter_bases.cpp
  9809. // start catch_reporter_compact.cpp
  9810. namespace {
  9811. #ifdef CATCH_PLATFORM_MAC
  9812. const char* failedString() { return "FAILED"; }
  9813. const char* passedString() { return "PASSED"; }
  9814. #else
  9815. const char* failedString() { return "failed"; }
  9816. const char* passedString() { return "passed"; }
  9817. #endif
  9818. // Colour::LightGrey
  9819. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  9820. std::string bothOrAll( std::size_t count ) {
  9821. return count == 1 ? std::string() :
  9822. count == 2 ? "both " : "all " ;
  9823. }
  9824. } // anon namespace
  9825. namespace Catch {
  9826. namespace {
  9827. // Colour, message variants:
  9828. // - white: No tests ran.
  9829. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  9830. // - white: Passed [both/all] N test cases (no assertions).
  9831. // - red: Failed N tests cases, failed M assertions.
  9832. // - green: Passed [both/all] N tests cases with M assertions.
  9833. void printTotals(std::ostream& out, const Totals& totals) {
  9834. if (totals.testCases.total() == 0) {
  9835. out << "No tests ran.";
  9836. } else if (totals.testCases.failed == totals.testCases.total()) {
  9837. Colour colour(Colour::ResultError);
  9838. const std::string qualify_assertions_failed =
  9839. totals.assertions.failed == totals.assertions.total() ?
  9840. bothOrAll(totals.assertions.failed) : std::string();
  9841. out <<
  9842. "Failed " << bothOrAll(totals.testCases.failed)
  9843. << pluralise(totals.testCases.failed, "test case") << ", "
  9844. "failed " << qualify_assertions_failed <<
  9845. pluralise(totals.assertions.failed, "assertion") << '.';
  9846. } else if (totals.assertions.total() == 0) {
  9847. out <<
  9848. "Passed " << bothOrAll(totals.testCases.total())
  9849. << pluralise(totals.testCases.total(), "test case")
  9850. << " (no assertions).";
  9851. } else if (totals.assertions.failed) {
  9852. Colour colour(Colour::ResultError);
  9853. out <<
  9854. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  9855. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  9856. } else {
  9857. Colour colour(Colour::ResultSuccess);
  9858. out <<
  9859. "Passed " << bothOrAll(totals.testCases.passed)
  9860. << pluralise(totals.testCases.passed, "test case") <<
  9861. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  9862. }
  9863. }
  9864. // Implementation of CompactReporter formatting
  9865. class AssertionPrinter {
  9866. public:
  9867. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  9868. AssertionPrinter(AssertionPrinter const&) = delete;
  9869. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  9870. : stream(_stream)
  9871. , result(_stats.assertionResult)
  9872. , messages(_stats.infoMessages)
  9873. , itMessage(_stats.infoMessages.begin())
  9874. , printInfoMessages(_printInfoMessages) {}
  9875. void print() {
  9876. printSourceInfo();
  9877. itMessage = messages.begin();
  9878. switch (result.getResultType()) {
  9879. case ResultWas::Ok:
  9880. printResultType(Colour::ResultSuccess, passedString());
  9881. printOriginalExpression();
  9882. printReconstructedExpression();
  9883. if (!result.hasExpression())
  9884. printRemainingMessages(Colour::None);
  9885. else
  9886. printRemainingMessages();
  9887. break;
  9888. case ResultWas::ExpressionFailed:
  9889. if (result.isOk())
  9890. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  9891. else
  9892. printResultType(Colour::Error, failedString());
  9893. printOriginalExpression();
  9894. printReconstructedExpression();
  9895. printRemainingMessages();
  9896. break;
  9897. case ResultWas::ThrewException:
  9898. printResultType(Colour::Error, failedString());
  9899. printIssue("unexpected exception with message:");
  9900. printMessage();
  9901. printExpressionWas();
  9902. printRemainingMessages();
  9903. break;
  9904. case ResultWas::FatalErrorCondition:
  9905. printResultType(Colour::Error, failedString());
  9906. printIssue("fatal error condition with message:");
  9907. printMessage();
  9908. printExpressionWas();
  9909. printRemainingMessages();
  9910. break;
  9911. case ResultWas::DidntThrowException:
  9912. printResultType(Colour::Error, failedString());
  9913. printIssue("expected exception, got none");
  9914. printExpressionWas();
  9915. printRemainingMessages();
  9916. break;
  9917. case ResultWas::Info:
  9918. printResultType(Colour::None, "info");
  9919. printMessage();
  9920. printRemainingMessages();
  9921. break;
  9922. case ResultWas::Warning:
  9923. printResultType(Colour::None, "warning");
  9924. printMessage();
  9925. printRemainingMessages();
  9926. break;
  9927. case ResultWas::ExplicitFailure:
  9928. printResultType(Colour::Error, failedString());
  9929. printIssue("explicitly");
  9930. printRemainingMessages(Colour::None);
  9931. break;
  9932. // These cases are here to prevent compiler warnings
  9933. case ResultWas::Unknown:
  9934. case ResultWas::FailureBit:
  9935. case ResultWas::Exception:
  9936. printResultType(Colour::Error, "** internal error **");
  9937. break;
  9938. }
  9939. }
  9940. private:
  9941. void printSourceInfo() const {
  9942. Colour colourGuard(Colour::FileName);
  9943. stream << result.getSourceInfo() << ':';
  9944. }
  9945. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  9946. if (!passOrFail.empty()) {
  9947. {
  9948. Colour colourGuard(colour);
  9949. stream << ' ' << passOrFail;
  9950. }
  9951. stream << ':';
  9952. }
  9953. }
  9954. void printIssue(std::string const& issue) const {
  9955. stream << ' ' << issue;
  9956. }
  9957. void printExpressionWas() {
  9958. if (result.hasExpression()) {
  9959. stream << ';';
  9960. {
  9961. Colour colour(dimColour());
  9962. stream << " expression was:";
  9963. }
  9964. printOriginalExpression();
  9965. }
  9966. }
  9967. void printOriginalExpression() const {
  9968. if (result.hasExpression()) {
  9969. stream << ' ' << result.getExpression();
  9970. }
  9971. }
  9972. void printReconstructedExpression() const {
  9973. if (result.hasExpandedExpression()) {
  9974. {
  9975. Colour colour(dimColour());
  9976. stream << " for: ";
  9977. }
  9978. stream << result.getExpandedExpression();
  9979. }
  9980. }
  9981. void printMessage() {
  9982. if (itMessage != messages.end()) {
  9983. stream << " '" << itMessage->message << '\'';
  9984. ++itMessage;
  9985. }
  9986. }
  9987. void printRemainingMessages(Colour::Code colour = dimColour()) {
  9988. if (itMessage == messages.end())
  9989. return;
  9990. // using messages.end() directly yields (or auto) compilation error:
  9991. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  9992. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  9993. {
  9994. Colour colourGuard(colour);
  9995. stream << " with " << pluralise(N, "message") << ':';
  9996. }
  9997. for (; itMessage != itEnd; ) {
  9998. // If this assertion is a warning ignore any INFO messages
  9999. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  10000. stream << " '" << itMessage->message << '\'';
  10001. if (++itMessage != itEnd) {
  10002. Colour colourGuard(dimColour());
  10003. stream << " and";
  10004. }
  10005. }
  10006. }
  10007. }
  10008. private:
  10009. std::ostream& stream;
  10010. AssertionResult const& result;
  10011. std::vector<MessageInfo> messages;
  10012. std::vector<MessageInfo>::const_iterator itMessage;
  10013. bool printInfoMessages;
  10014. };
  10015. } // anon namespace
  10016. std::string CompactReporter::getDescription() {
  10017. return "Reports test results on a single line, suitable for IDEs";
  10018. }
  10019. ReporterPreferences CompactReporter::getPreferences() const {
  10020. return m_reporterPrefs;
  10021. }
  10022. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  10023. stream << "No test cases matched '" << spec << '\'' << std::endl;
  10024. }
  10025. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  10026. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  10027. AssertionResult const& result = _assertionStats.assertionResult;
  10028. bool printInfoMessages = true;
  10029. // Drop out if result was successful and we're not printing those
  10030. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  10031. if( result.getResultType() != ResultWas::Warning )
  10032. return false;
  10033. printInfoMessages = false;
  10034. }
  10035. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  10036. printer.print();
  10037. stream << std::endl;
  10038. return true;
  10039. }
  10040. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  10041. if (m_config->showDurations() == ShowDurations::Always) {
  10042. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  10043. }
  10044. }
  10045. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  10046. printTotals( stream, _testRunStats.totals );
  10047. stream << '\n' << std::endl;
  10048. StreamingReporterBase::testRunEnded( _testRunStats );
  10049. }
  10050. CompactReporter::~CompactReporter() {}
  10051. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  10052. } // end namespace Catch
  10053. // end catch_reporter_compact.cpp
  10054. // start catch_reporter_console.cpp
  10055. #include <cfloat>
  10056. #include <cstdio>
  10057. #if defined(_MSC_VER)
  10058. #pragma warning(push)
  10059. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  10060. // Note that 4062 (not all labels are handled
  10061. // and default is missing) is enabled
  10062. #endif
  10063. namespace Catch {
  10064. namespace {
  10065. // Formatter impl for ConsoleReporter
  10066. class ConsoleAssertionPrinter {
  10067. public:
  10068. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  10069. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  10070. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  10071. : stream(_stream),
  10072. stats(_stats),
  10073. result(_stats.assertionResult),
  10074. colour(Colour::None),
  10075. message(result.getMessage()),
  10076. messages(_stats.infoMessages),
  10077. printInfoMessages(_printInfoMessages) {
  10078. switch (result.getResultType()) {
  10079. case ResultWas::Ok:
  10080. colour = Colour::Success;
  10081. passOrFail = "PASSED";
  10082. //if( result.hasMessage() )
  10083. if (_stats.infoMessages.size() == 1)
  10084. messageLabel = "with message";
  10085. if (_stats.infoMessages.size() > 1)
  10086. messageLabel = "with messages";
  10087. break;
  10088. case ResultWas::ExpressionFailed:
  10089. if (result.isOk()) {
  10090. colour = Colour::Success;
  10091. passOrFail = "FAILED - but was ok";
  10092. } else {
  10093. colour = Colour::Error;
  10094. passOrFail = "FAILED";
  10095. }
  10096. if (_stats.infoMessages.size() == 1)
  10097. messageLabel = "with message";
  10098. if (_stats.infoMessages.size() > 1)
  10099. messageLabel = "with messages";
  10100. break;
  10101. case ResultWas::ThrewException:
  10102. colour = Colour::Error;
  10103. passOrFail = "FAILED";
  10104. messageLabel = "due to unexpected exception with ";
  10105. if (_stats.infoMessages.size() == 1)
  10106. messageLabel += "message";
  10107. if (_stats.infoMessages.size() > 1)
  10108. messageLabel += "messages";
  10109. break;
  10110. case ResultWas::FatalErrorCondition:
  10111. colour = Colour::Error;
  10112. passOrFail = "FAILED";
  10113. messageLabel = "due to a fatal error condition";
  10114. break;
  10115. case ResultWas::DidntThrowException:
  10116. colour = Colour::Error;
  10117. passOrFail = "FAILED";
  10118. messageLabel = "because no exception was thrown where one was expected";
  10119. break;
  10120. case ResultWas::Info:
  10121. messageLabel = "info";
  10122. break;
  10123. case ResultWas::Warning:
  10124. messageLabel = "warning";
  10125. break;
  10126. case ResultWas::ExplicitFailure:
  10127. passOrFail = "FAILED";
  10128. colour = Colour::Error;
  10129. if (_stats.infoMessages.size() == 1)
  10130. messageLabel = "explicitly with message";
  10131. if (_stats.infoMessages.size() > 1)
  10132. messageLabel = "explicitly with messages";
  10133. break;
  10134. // These cases are here to prevent compiler warnings
  10135. case ResultWas::Unknown:
  10136. case ResultWas::FailureBit:
  10137. case ResultWas::Exception:
  10138. passOrFail = "** internal error **";
  10139. colour = Colour::Error;
  10140. break;
  10141. }
  10142. }
  10143. void print() const {
  10144. printSourceInfo();
  10145. if (stats.totals.assertions.total() > 0) {
  10146. if (result.isOk())
  10147. stream << '\n';
  10148. printResultType();
  10149. printOriginalExpression();
  10150. printReconstructedExpression();
  10151. } else {
  10152. stream << '\n';
  10153. }
  10154. printMessage();
  10155. }
  10156. private:
  10157. void printResultType() const {
  10158. if (!passOrFail.empty()) {
  10159. Colour colourGuard(colour);
  10160. stream << passOrFail << ":\n";
  10161. }
  10162. }
  10163. void printOriginalExpression() const {
  10164. if (result.hasExpression()) {
  10165. Colour colourGuard(Colour::OriginalExpression);
  10166. stream << " ";
  10167. stream << result.getExpressionInMacro();
  10168. stream << '\n';
  10169. }
  10170. }
  10171. void printReconstructedExpression() const {
  10172. if (result.hasExpandedExpression()) {
  10173. stream << "with expansion:\n";
  10174. Colour colourGuard(Colour::ReconstructedExpression);
  10175. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  10176. }
  10177. }
  10178. void printMessage() const {
  10179. if (!messageLabel.empty())
  10180. stream << messageLabel << ':' << '\n';
  10181. for (auto const& msg : messages) {
  10182. // If this assertion is a warning ignore any INFO messages
  10183. if (printInfoMessages || msg.type != ResultWas::Info)
  10184. stream << Column(msg.message).indent(2) << '\n';
  10185. }
  10186. }
  10187. void printSourceInfo() const {
  10188. Colour colourGuard(Colour::FileName);
  10189. stream << result.getSourceInfo() << ": ";
  10190. }
  10191. std::ostream& stream;
  10192. AssertionStats const& stats;
  10193. AssertionResult const& result;
  10194. Colour::Code colour;
  10195. std::string passOrFail;
  10196. std::string messageLabel;
  10197. std::string message;
  10198. std::vector<MessageInfo> messages;
  10199. bool printInfoMessages;
  10200. };
  10201. std::size_t makeRatio(std::size_t number, std::size_t total) {
  10202. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  10203. return (ratio == 0 && number > 0) ? 1 : ratio;
  10204. }
  10205. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  10206. if (i > j && i > k)
  10207. return i;
  10208. else if (j > k)
  10209. return j;
  10210. else
  10211. return k;
  10212. }
  10213. struct ColumnInfo {
  10214. enum Justification { Left, Right };
  10215. std::string name;
  10216. int width;
  10217. Justification justification;
  10218. };
  10219. struct ColumnBreak {};
  10220. struct RowBreak {};
  10221. class Duration {
  10222. enum class Unit {
  10223. Auto,
  10224. Nanoseconds,
  10225. Microseconds,
  10226. Milliseconds,
  10227. Seconds,
  10228. Minutes
  10229. };
  10230. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  10231. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  10232. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  10233. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  10234. uint64_t m_inNanoseconds;
  10235. Unit m_units;
  10236. public:
  10237. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  10238. : m_inNanoseconds(inNanoseconds),
  10239. m_units(units) {
  10240. if (m_units == Unit::Auto) {
  10241. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  10242. m_units = Unit::Nanoseconds;
  10243. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  10244. m_units = Unit::Microseconds;
  10245. else if (m_inNanoseconds < s_nanosecondsInASecond)
  10246. m_units = Unit::Milliseconds;
  10247. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  10248. m_units = Unit::Seconds;
  10249. else
  10250. m_units = Unit::Minutes;
  10251. }
  10252. }
  10253. auto value() const -> double {
  10254. switch (m_units) {
  10255. case Unit::Microseconds:
  10256. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  10257. case Unit::Milliseconds:
  10258. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  10259. case Unit::Seconds:
  10260. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  10261. case Unit::Minutes:
  10262. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  10263. default:
  10264. return static_cast<double>(m_inNanoseconds);
  10265. }
  10266. }
  10267. auto unitsAsString() const -> std::string {
  10268. switch (m_units) {
  10269. case Unit::Nanoseconds:
  10270. return "ns";
  10271. case Unit::Microseconds:
  10272. return "µs";
  10273. case Unit::Milliseconds:
  10274. return "ms";
  10275. case Unit::Seconds:
  10276. return "s";
  10277. case Unit::Minutes:
  10278. return "m";
  10279. default:
  10280. return "** internal error **";
  10281. }
  10282. }
  10283. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  10284. return os << duration.value() << " " << duration.unitsAsString();
  10285. }
  10286. };
  10287. } // end anon namespace
  10288. class TablePrinter {
  10289. std::ostream& m_os;
  10290. std::vector<ColumnInfo> m_columnInfos;
  10291. std::ostringstream m_oss;
  10292. int m_currentColumn = -1;
  10293. bool m_isOpen = false;
  10294. public:
  10295. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  10296. : m_os( os ),
  10297. m_columnInfos( std::move( columnInfos ) ) {}
  10298. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  10299. return m_columnInfos;
  10300. }
  10301. void open() {
  10302. if (!m_isOpen) {
  10303. m_isOpen = true;
  10304. *this << RowBreak();
  10305. for (auto const& info : m_columnInfos)
  10306. *this << info.name << ColumnBreak();
  10307. *this << RowBreak();
  10308. m_os << Catch::getLineOfChars<'-'>() << "\n";
  10309. }
  10310. }
  10311. void close() {
  10312. if (m_isOpen) {
  10313. *this << RowBreak();
  10314. m_os << std::endl;
  10315. m_isOpen = false;
  10316. }
  10317. }
  10318. template<typename T>
  10319. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  10320. tp.m_oss << value;
  10321. return tp;
  10322. }
  10323. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  10324. auto colStr = tp.m_oss.str();
  10325. // This takes account of utf8 encodings
  10326. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  10327. tp.m_oss.str("");
  10328. tp.open();
  10329. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  10330. tp.m_currentColumn = -1;
  10331. tp.m_os << "\n";
  10332. }
  10333. tp.m_currentColumn++;
  10334. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  10335. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  10336. ? std::string(colInfo.width - (strSize + 2), ' ')
  10337. : std::string();
  10338. if (colInfo.justification == ColumnInfo::Left)
  10339. tp.m_os << colStr << padding << " ";
  10340. else
  10341. tp.m_os << padding << colStr << " ";
  10342. return tp;
  10343. }
  10344. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  10345. if (tp.m_currentColumn > 0) {
  10346. tp.m_os << "\n";
  10347. tp.m_currentColumn = -1;
  10348. }
  10349. return tp;
  10350. }
  10351. };
  10352. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  10353. : StreamingReporterBase(config),
  10354. m_tablePrinter(new TablePrinter(config.stream(),
  10355. {
  10356. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  10357. { "iters", 8, ColumnInfo::Right },
  10358. { "elapsed ns", 14, ColumnInfo::Right },
  10359. { "average", 14, ColumnInfo::Right }
  10360. })) {}
  10361. ConsoleReporter::~ConsoleReporter() = default;
  10362. std::string ConsoleReporter::getDescription() {
  10363. return "Reports test results as plain lines of text";
  10364. }
  10365. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  10366. stream << "No test cases matched '" << spec << '\'' << std::endl;
  10367. }
  10368. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  10369. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  10370. AssertionResult const& result = _assertionStats.assertionResult;
  10371. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  10372. // Drop out if result was successful but we're not printing them.
  10373. if (!includeResults && result.getResultType() != ResultWas::Warning)
  10374. return false;
  10375. lazyPrint();
  10376. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  10377. printer.print();
  10378. stream << std::endl;
  10379. return true;
  10380. }
  10381. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  10382. m_headerPrinted = false;
  10383. StreamingReporterBase::sectionStarting(_sectionInfo);
  10384. }
  10385. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  10386. m_tablePrinter->close();
  10387. if (_sectionStats.missingAssertions) {
  10388. lazyPrint();
  10389. Colour colour(Colour::ResultError);
  10390. if (m_sectionStack.size() > 1)
  10391. stream << "\nNo assertions in section";
  10392. else
  10393. stream << "\nNo assertions in test case";
  10394. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  10395. }
  10396. if (m_config->showDurations() == ShowDurations::Always) {
  10397. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  10398. }
  10399. if (m_headerPrinted) {
  10400. m_headerPrinted = false;
  10401. }
  10402. StreamingReporterBase::sectionEnded(_sectionStats);
  10403. }
  10404. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  10405. lazyPrintWithoutClosingBenchmarkTable();
  10406. auto nameCol = Column( info.name ).width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) );
  10407. bool firstLine = true;
  10408. for (auto line : nameCol) {
  10409. if (!firstLine)
  10410. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  10411. else
  10412. firstLine = false;
  10413. (*m_tablePrinter) << line << ColumnBreak();
  10414. }
  10415. }
  10416. void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) {
  10417. Duration average(stats.elapsedTimeInNanoseconds / stats.iterations);
  10418. (*m_tablePrinter)
  10419. << stats.iterations << ColumnBreak()
  10420. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  10421. << average << ColumnBreak();
  10422. }
  10423. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  10424. m_tablePrinter->close();
  10425. StreamingReporterBase::testCaseEnded(_testCaseStats);
  10426. m_headerPrinted = false;
  10427. }
  10428. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  10429. if (currentGroupInfo.used) {
  10430. printSummaryDivider();
  10431. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  10432. printTotals(_testGroupStats.totals);
  10433. stream << '\n' << std::endl;
  10434. }
  10435. StreamingReporterBase::testGroupEnded(_testGroupStats);
  10436. }
  10437. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  10438. printTotalsDivider(_testRunStats.totals);
  10439. printTotals(_testRunStats.totals);
  10440. stream << std::endl;
  10441. StreamingReporterBase::testRunEnded(_testRunStats);
  10442. }
  10443. void ConsoleReporter::lazyPrint() {
  10444. m_tablePrinter->close();
  10445. lazyPrintWithoutClosingBenchmarkTable();
  10446. }
  10447. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  10448. if (!currentTestRunInfo.used)
  10449. lazyPrintRunInfo();
  10450. if (!currentGroupInfo.used)
  10451. lazyPrintGroupInfo();
  10452. if (!m_headerPrinted) {
  10453. printTestCaseAndSectionHeader();
  10454. m_headerPrinted = true;
  10455. }
  10456. }
  10457. void ConsoleReporter::lazyPrintRunInfo() {
  10458. stream << '\n' << getLineOfChars<'~'>() << '\n';
  10459. Colour colour(Colour::SecondaryText);
  10460. stream << currentTestRunInfo->name
  10461. << " is a Catch v" << libraryVersion() << " host application.\n"
  10462. << "Run with -? for options\n\n";
  10463. if (m_config->rngSeed() != 0)
  10464. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  10465. currentTestRunInfo.used = true;
  10466. }
  10467. void ConsoleReporter::lazyPrintGroupInfo() {
  10468. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  10469. printClosedHeader("Group: " + currentGroupInfo->name);
  10470. currentGroupInfo.used = true;
  10471. }
  10472. }
  10473. void ConsoleReporter::printTestCaseAndSectionHeader() {
  10474. assert(!m_sectionStack.empty());
  10475. printOpenHeader(currentTestCaseInfo->name);
  10476. if (m_sectionStack.size() > 1) {
  10477. Colour colourGuard(Colour::Headers);
  10478. auto
  10479. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  10480. itEnd = m_sectionStack.end();
  10481. for (; it != itEnd; ++it)
  10482. printHeaderString(it->name, 2);
  10483. }
  10484. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  10485. if (!lineInfo.empty()) {
  10486. stream << getLineOfChars<'-'>() << '\n';
  10487. Colour colourGuard(Colour::FileName);
  10488. stream << lineInfo << '\n';
  10489. }
  10490. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  10491. }
  10492. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  10493. printOpenHeader(_name);
  10494. stream << getLineOfChars<'.'>() << '\n';
  10495. }
  10496. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  10497. stream << getLineOfChars<'-'>() << '\n';
  10498. {
  10499. Colour colourGuard(Colour::Headers);
  10500. printHeaderString(_name);
  10501. }
  10502. }
  10503. // if string has a : in first line will set indent to follow it on
  10504. // subsequent lines
  10505. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  10506. std::size_t i = _string.find(": ");
  10507. if (i != std::string::npos)
  10508. i += 2;
  10509. else
  10510. i = 0;
  10511. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  10512. }
  10513. struct SummaryColumn {
  10514. SummaryColumn( std::string _label, Colour::Code _colour )
  10515. : label( std::move( _label ) ),
  10516. colour( _colour ) {}
  10517. SummaryColumn addRow( std::size_t count ) {
  10518. ReusableStringStream rss;
  10519. rss << count;
  10520. std::string row = rss.str();
  10521. for (auto& oldRow : rows) {
  10522. while (oldRow.size() < row.size())
  10523. oldRow = ' ' + oldRow;
  10524. while (oldRow.size() > row.size())
  10525. row = ' ' + row;
  10526. }
  10527. rows.push_back(row);
  10528. return *this;
  10529. }
  10530. std::string label;
  10531. Colour::Code colour;
  10532. std::vector<std::string> rows;
  10533. };
  10534. void ConsoleReporter::printTotals( Totals const& totals ) {
  10535. if (totals.testCases.total() == 0) {
  10536. stream << Colour(Colour::Warning) << "No tests ran\n";
  10537. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  10538. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  10539. stream << " ("
  10540. << pluralise(totals.assertions.passed, "assertion") << " in "
  10541. << pluralise(totals.testCases.passed, "test case") << ')'
  10542. << '\n';
  10543. } else {
  10544. std::vector<SummaryColumn> columns;
  10545. columns.push_back(SummaryColumn("", Colour::None)
  10546. .addRow(totals.testCases.total())
  10547. .addRow(totals.assertions.total()));
  10548. columns.push_back(SummaryColumn("passed", Colour::Success)
  10549. .addRow(totals.testCases.passed)
  10550. .addRow(totals.assertions.passed));
  10551. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  10552. .addRow(totals.testCases.failed)
  10553. .addRow(totals.assertions.failed));
  10554. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  10555. .addRow(totals.testCases.failedButOk)
  10556. .addRow(totals.assertions.failedButOk));
  10557. printSummaryRow("test cases", columns, 0);
  10558. printSummaryRow("assertions", columns, 1);
  10559. }
  10560. }
  10561. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  10562. for (auto col : cols) {
  10563. std::string value = col.rows[row];
  10564. if (col.label.empty()) {
  10565. stream << label << ": ";
  10566. if (value != "0")
  10567. stream << value;
  10568. else
  10569. stream << Colour(Colour::Warning) << "- none -";
  10570. } else if (value != "0") {
  10571. stream << Colour(Colour::LightGrey) << " | ";
  10572. stream << Colour(col.colour)
  10573. << value << ' ' << col.label;
  10574. }
  10575. }
  10576. stream << '\n';
  10577. }
  10578. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  10579. if (totals.testCases.total() > 0) {
  10580. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  10581. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  10582. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  10583. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  10584. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  10585. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  10586. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  10587. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  10588. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  10589. if (totals.testCases.allPassed())
  10590. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  10591. else
  10592. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  10593. } else {
  10594. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  10595. }
  10596. stream << '\n';
  10597. }
  10598. void ConsoleReporter::printSummaryDivider() {
  10599. stream << getLineOfChars<'-'>() << '\n';
  10600. }
  10601. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  10602. } // end namespace Catch
  10603. #if defined(_MSC_VER)
  10604. #pragma warning(pop)
  10605. #endif
  10606. // end catch_reporter_console.cpp
  10607. // start catch_reporter_junit.cpp
  10608. #include <cassert>
  10609. #include <sstream>
  10610. #include <ctime>
  10611. #include <algorithm>
  10612. namespace Catch {
  10613. namespace {
  10614. std::string getCurrentTimestamp() {
  10615. // Beware, this is not reentrant because of backward compatibility issues
  10616. // Also, UTC only, again because of backward compatibility (%z is C++11)
  10617. time_t rawtime;
  10618. std::time(&rawtime);
  10619. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  10620. #ifdef _MSC_VER
  10621. std::tm timeInfo = {};
  10622. gmtime_s(&timeInfo, &rawtime);
  10623. #else
  10624. std::tm* timeInfo;
  10625. timeInfo = std::gmtime(&rawtime);
  10626. #endif
  10627. char timeStamp[timeStampSize];
  10628. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  10629. #ifdef _MSC_VER
  10630. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  10631. #else
  10632. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  10633. #endif
  10634. return std::string(timeStamp);
  10635. }
  10636. std::string fileNameTag(const std::vector<std::string> &tags) {
  10637. auto it = std::find_if(begin(tags),
  10638. end(tags),
  10639. [] (std::string const& tag) {return tag.front() == '#'; });
  10640. if (it != tags.end())
  10641. return it->substr(1);
  10642. return std::string();
  10643. }
  10644. } // anonymous namespace
  10645. JunitReporter::JunitReporter( ReporterConfig const& _config )
  10646. : CumulativeReporterBase( _config ),
  10647. xml( _config.stream() )
  10648. {
  10649. m_reporterPrefs.shouldRedirectStdOut = true;
  10650. m_reporterPrefs.shouldReportAllAssertions = true;
  10651. }
  10652. JunitReporter::~JunitReporter() {}
  10653. std::string JunitReporter::getDescription() {
  10654. return "Reports test results in an XML format that looks like Ant's junitreport target";
  10655. }
  10656. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  10657. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  10658. CumulativeReporterBase::testRunStarting( runInfo );
  10659. xml.startElement( "testsuites" );
  10660. }
  10661. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  10662. suiteTimer.start();
  10663. stdOutForSuite.clear();
  10664. stdErrForSuite.clear();
  10665. unexpectedExceptions = 0;
  10666. CumulativeReporterBase::testGroupStarting( groupInfo );
  10667. }
  10668. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  10669. m_okToFail = testCaseInfo.okToFail();
  10670. }
  10671. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10672. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  10673. unexpectedExceptions++;
  10674. return CumulativeReporterBase::assertionEnded( assertionStats );
  10675. }
  10676. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10677. stdOutForSuite += testCaseStats.stdOut;
  10678. stdErrForSuite += testCaseStats.stdErr;
  10679. CumulativeReporterBase::testCaseEnded( testCaseStats );
  10680. }
  10681. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10682. double suiteTime = suiteTimer.getElapsedSeconds();
  10683. CumulativeReporterBase::testGroupEnded( testGroupStats );
  10684. writeGroup( *m_testGroups.back(), suiteTime );
  10685. }
  10686. void JunitReporter::testRunEndedCumulative() {
  10687. xml.endElement();
  10688. }
  10689. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  10690. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  10691. TestGroupStats const& stats = groupNode.value;
  10692. xml.writeAttribute( "name", stats.groupInfo.name );
  10693. xml.writeAttribute( "errors", unexpectedExceptions );
  10694. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  10695. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  10696. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  10697. if( m_config->showDurations() == ShowDurations::Never )
  10698. xml.writeAttribute( "time", "" );
  10699. else
  10700. xml.writeAttribute( "time", suiteTime );
  10701. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  10702. // Write test cases
  10703. for( auto const& child : groupNode.children )
  10704. writeTestCase( *child );
  10705. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  10706. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  10707. }
  10708. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  10709. TestCaseStats const& stats = testCaseNode.value;
  10710. // All test cases have exactly one section - which represents the
  10711. // test case itself. That section may have 0-n nested sections
  10712. assert( testCaseNode.children.size() == 1 );
  10713. SectionNode const& rootSection = *testCaseNode.children.front();
  10714. std::string className = stats.testInfo.className;
  10715. if( className.empty() ) {
  10716. className = fileNameTag(stats.testInfo.tags);
  10717. if ( className.empty() )
  10718. className = "global";
  10719. }
  10720. if ( !m_config->name().empty() )
  10721. className = m_config->name() + "." + className;
  10722. writeSection( className, "", rootSection );
  10723. }
  10724. void JunitReporter::writeSection( std::string const& className,
  10725. std::string const& rootName,
  10726. SectionNode const& sectionNode ) {
  10727. std::string name = trim( sectionNode.stats.sectionInfo.name );
  10728. if( !rootName.empty() )
  10729. name = rootName + '/' + name;
  10730. if( !sectionNode.assertions.empty() ||
  10731. !sectionNode.stdOut.empty() ||
  10732. !sectionNode.stdErr.empty() ) {
  10733. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  10734. if( className.empty() ) {
  10735. xml.writeAttribute( "classname", name );
  10736. xml.writeAttribute( "name", "root" );
  10737. }
  10738. else {
  10739. xml.writeAttribute( "classname", className );
  10740. xml.writeAttribute( "name", name );
  10741. }
  10742. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  10743. writeAssertions( sectionNode );
  10744. if( !sectionNode.stdOut.empty() )
  10745. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  10746. if( !sectionNode.stdErr.empty() )
  10747. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  10748. }
  10749. for( auto const& childNode : sectionNode.childSections )
  10750. if( className.empty() )
  10751. writeSection( name, "", *childNode );
  10752. else
  10753. writeSection( className, name, *childNode );
  10754. }
  10755. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  10756. for( auto const& assertion : sectionNode.assertions )
  10757. writeAssertion( assertion );
  10758. }
  10759. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  10760. AssertionResult const& result = stats.assertionResult;
  10761. if( !result.isOk() ) {
  10762. std::string elementName;
  10763. switch( result.getResultType() ) {
  10764. case ResultWas::ThrewException:
  10765. case ResultWas::FatalErrorCondition:
  10766. elementName = "error";
  10767. break;
  10768. case ResultWas::ExplicitFailure:
  10769. elementName = "failure";
  10770. break;
  10771. case ResultWas::ExpressionFailed:
  10772. elementName = "failure";
  10773. break;
  10774. case ResultWas::DidntThrowException:
  10775. elementName = "failure";
  10776. break;
  10777. // We should never see these here:
  10778. case ResultWas::Info:
  10779. case ResultWas::Warning:
  10780. case ResultWas::Ok:
  10781. case ResultWas::Unknown:
  10782. case ResultWas::FailureBit:
  10783. case ResultWas::Exception:
  10784. elementName = "internalError";
  10785. break;
  10786. }
  10787. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  10788. xml.writeAttribute( "message", result.getExpandedExpression() );
  10789. xml.writeAttribute( "type", result.getTestMacroName() );
  10790. ReusableStringStream rss;
  10791. if( !result.getMessage().empty() )
  10792. rss << result.getMessage() << '\n';
  10793. for( auto const& msg : stats.infoMessages )
  10794. if( msg.type == ResultWas::Info )
  10795. rss << msg.message << '\n';
  10796. rss << "at " << result.getSourceInfo();
  10797. xml.writeText( rss.str(), false );
  10798. }
  10799. }
  10800. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  10801. } // end namespace Catch
  10802. // end catch_reporter_junit.cpp
  10803. // start catch_reporter_listening.cpp
  10804. #include <cassert>
  10805. namespace Catch {
  10806. ListeningReporter::ListeningReporter() {
  10807. // We will assume that listeners will always want all assertions
  10808. m_preferences.shouldReportAllAssertions = true;
  10809. }
  10810. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  10811. m_listeners.push_back( std::move( listener ) );
  10812. }
  10813. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  10814. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  10815. m_reporter = std::move( reporter );
  10816. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  10817. }
  10818. ReporterPreferences ListeningReporter::getPreferences() const {
  10819. return m_preferences;
  10820. }
  10821. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  10822. return std::set<Verbosity>{ };
  10823. }
  10824. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  10825. for ( auto const& listener : m_listeners ) {
  10826. listener->noMatchingTestCases( spec );
  10827. }
  10828. m_reporter->noMatchingTestCases( spec );
  10829. }
  10830. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  10831. for ( auto const& listener : m_listeners ) {
  10832. listener->benchmarkStarting( benchmarkInfo );
  10833. }
  10834. m_reporter->benchmarkStarting( benchmarkInfo );
  10835. }
  10836. void ListeningReporter::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
  10837. for ( auto const& listener : m_listeners ) {
  10838. listener->benchmarkEnded( benchmarkStats );
  10839. }
  10840. m_reporter->benchmarkEnded( benchmarkStats );
  10841. }
  10842. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  10843. for ( auto const& listener : m_listeners ) {
  10844. listener->testRunStarting( testRunInfo );
  10845. }
  10846. m_reporter->testRunStarting( testRunInfo );
  10847. }
  10848. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  10849. for ( auto const& listener : m_listeners ) {
  10850. listener->testGroupStarting( groupInfo );
  10851. }
  10852. m_reporter->testGroupStarting( groupInfo );
  10853. }
  10854. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  10855. for ( auto const& listener : m_listeners ) {
  10856. listener->testCaseStarting( testInfo );
  10857. }
  10858. m_reporter->testCaseStarting( testInfo );
  10859. }
  10860. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  10861. for ( auto const& listener : m_listeners ) {
  10862. listener->sectionStarting( sectionInfo );
  10863. }
  10864. m_reporter->sectionStarting( sectionInfo );
  10865. }
  10866. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  10867. for ( auto const& listener : m_listeners ) {
  10868. listener->assertionStarting( assertionInfo );
  10869. }
  10870. m_reporter->assertionStarting( assertionInfo );
  10871. }
  10872. // The return value indicates if the messages buffer should be cleared:
  10873. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10874. for( auto const& listener : m_listeners ) {
  10875. static_cast<void>( listener->assertionEnded( assertionStats ) );
  10876. }
  10877. return m_reporter->assertionEnded( assertionStats );
  10878. }
  10879. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  10880. for ( auto const& listener : m_listeners ) {
  10881. listener->sectionEnded( sectionStats );
  10882. }
  10883. m_reporter->sectionEnded( sectionStats );
  10884. }
  10885. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10886. for ( auto const& listener : m_listeners ) {
  10887. listener->testCaseEnded( testCaseStats );
  10888. }
  10889. m_reporter->testCaseEnded( testCaseStats );
  10890. }
  10891. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10892. for ( auto const& listener : m_listeners ) {
  10893. listener->testGroupEnded( testGroupStats );
  10894. }
  10895. m_reporter->testGroupEnded( testGroupStats );
  10896. }
  10897. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  10898. for ( auto const& listener : m_listeners ) {
  10899. listener->testRunEnded( testRunStats );
  10900. }
  10901. m_reporter->testRunEnded( testRunStats );
  10902. }
  10903. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  10904. for ( auto const& listener : m_listeners ) {
  10905. listener->skipTest( testInfo );
  10906. }
  10907. m_reporter->skipTest( testInfo );
  10908. }
  10909. bool ListeningReporter::isMulti() const {
  10910. return true;
  10911. }
  10912. } // end namespace Catch
  10913. // end catch_reporter_listening.cpp
  10914. // start catch_reporter_xml.cpp
  10915. #if defined(_MSC_VER)
  10916. #pragma warning(push)
  10917. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  10918. // Note that 4062 (not all labels are handled
  10919. // and default is missing) is enabled
  10920. #endif
  10921. namespace Catch {
  10922. XmlReporter::XmlReporter( ReporterConfig const& _config )
  10923. : StreamingReporterBase( _config ),
  10924. m_xml(_config.stream())
  10925. {
  10926. m_reporterPrefs.shouldRedirectStdOut = true;
  10927. m_reporterPrefs.shouldReportAllAssertions = true;
  10928. }
  10929. XmlReporter::~XmlReporter() = default;
  10930. std::string XmlReporter::getDescription() {
  10931. return "Reports test results as an XML document";
  10932. }
  10933. std::string XmlReporter::getStylesheetRef() const {
  10934. return std::string();
  10935. }
  10936. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  10937. m_xml
  10938. .writeAttribute( "filename", sourceInfo.file )
  10939. .writeAttribute( "line", sourceInfo.line );
  10940. }
  10941. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  10942. StreamingReporterBase::noMatchingTestCases( s );
  10943. }
  10944. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  10945. StreamingReporterBase::testRunStarting( testInfo );
  10946. std::string stylesheetRef = getStylesheetRef();
  10947. if( !stylesheetRef.empty() )
  10948. m_xml.writeStylesheetRef( stylesheetRef );
  10949. m_xml.startElement( "Catch" );
  10950. if( !m_config->name().empty() )
  10951. m_xml.writeAttribute( "name", m_config->name() );
  10952. }
  10953. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  10954. StreamingReporterBase::testGroupStarting( groupInfo );
  10955. m_xml.startElement( "Group" )
  10956. .writeAttribute( "name", groupInfo.name );
  10957. }
  10958. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  10959. StreamingReporterBase::testCaseStarting(testInfo);
  10960. m_xml.startElement( "TestCase" )
  10961. .writeAttribute( "name", trim( testInfo.name ) )
  10962. .writeAttribute( "description", testInfo.description )
  10963. .writeAttribute( "tags", testInfo.tagsAsString() );
  10964. writeSourceInfo( testInfo.lineInfo );
  10965. if ( m_config->showDurations() == ShowDurations::Always )
  10966. m_testCaseTimer.start();
  10967. m_xml.ensureTagClosed();
  10968. }
  10969. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  10970. StreamingReporterBase::sectionStarting( sectionInfo );
  10971. if( m_sectionDepth++ > 0 ) {
  10972. m_xml.startElement( "Section" )
  10973. .writeAttribute( "name", trim( sectionInfo.name ) );
  10974. writeSourceInfo( sectionInfo.lineInfo );
  10975. m_xml.ensureTagClosed();
  10976. }
  10977. }
  10978. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  10979. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10980. AssertionResult const& result = assertionStats.assertionResult;
  10981. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  10982. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  10983. // Print any info messages in <Info> tags.
  10984. for( auto const& msg : assertionStats.infoMessages ) {
  10985. if( msg.type == ResultWas::Info && includeResults ) {
  10986. m_xml.scopedElement( "Info" )
  10987. .writeText( msg.message );
  10988. } else if ( msg.type == ResultWas::Warning ) {
  10989. m_xml.scopedElement( "Warning" )
  10990. .writeText( msg.message );
  10991. }
  10992. }
  10993. }
  10994. // Drop out if result was successful but we're not printing them.
  10995. if( !includeResults && result.getResultType() != ResultWas::Warning )
  10996. return true;
  10997. // Print the expression if there is one.
  10998. if( result.hasExpression() ) {
  10999. m_xml.startElement( "Expression" )
  11000. .writeAttribute( "success", result.succeeded() )
  11001. .writeAttribute( "type", result.getTestMacroName() );
  11002. writeSourceInfo( result.getSourceInfo() );
  11003. m_xml.scopedElement( "Original" )
  11004. .writeText( result.getExpression() );
  11005. m_xml.scopedElement( "Expanded" )
  11006. .writeText( result.getExpandedExpression() );
  11007. }
  11008. // And... Print a result applicable to each result type.
  11009. switch( result.getResultType() ) {
  11010. case ResultWas::ThrewException:
  11011. m_xml.startElement( "Exception" );
  11012. writeSourceInfo( result.getSourceInfo() );
  11013. m_xml.writeText( result.getMessage() );
  11014. m_xml.endElement();
  11015. break;
  11016. case ResultWas::FatalErrorCondition:
  11017. m_xml.startElement( "FatalErrorCondition" );
  11018. writeSourceInfo( result.getSourceInfo() );
  11019. m_xml.writeText( result.getMessage() );
  11020. m_xml.endElement();
  11021. break;
  11022. case ResultWas::Info:
  11023. m_xml.scopedElement( "Info" )
  11024. .writeText( result.getMessage() );
  11025. break;
  11026. case ResultWas::Warning:
  11027. // Warning will already have been written
  11028. break;
  11029. case ResultWas::ExplicitFailure:
  11030. m_xml.startElement( "Failure" );
  11031. writeSourceInfo( result.getSourceInfo() );
  11032. m_xml.writeText( result.getMessage() );
  11033. m_xml.endElement();
  11034. break;
  11035. default:
  11036. break;
  11037. }
  11038. if( result.hasExpression() )
  11039. m_xml.endElement();
  11040. return true;
  11041. }
  11042. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  11043. StreamingReporterBase::sectionEnded( sectionStats );
  11044. if( --m_sectionDepth > 0 ) {
  11045. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  11046. e.writeAttribute( "successes", sectionStats.assertions.passed );
  11047. e.writeAttribute( "failures", sectionStats.assertions.failed );
  11048. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  11049. if ( m_config->showDurations() == ShowDurations::Always )
  11050. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  11051. m_xml.endElement();
  11052. }
  11053. }
  11054. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11055. StreamingReporterBase::testCaseEnded( testCaseStats );
  11056. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  11057. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  11058. if ( m_config->showDurations() == ShowDurations::Always )
  11059. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  11060. if( !testCaseStats.stdOut.empty() )
  11061. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  11062. if( !testCaseStats.stdErr.empty() )
  11063. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  11064. m_xml.endElement();
  11065. }
  11066. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11067. StreamingReporterBase::testGroupEnded( testGroupStats );
  11068. // TODO: Check testGroupStats.aborting and act accordingly.
  11069. m_xml.scopedElement( "OverallResults" )
  11070. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  11071. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  11072. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  11073. m_xml.endElement();
  11074. }
  11075. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  11076. StreamingReporterBase::testRunEnded( testRunStats );
  11077. m_xml.scopedElement( "OverallResults" )
  11078. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  11079. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  11080. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  11081. m_xml.endElement();
  11082. }
  11083. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  11084. } // end namespace Catch
  11085. #if defined(_MSC_VER)
  11086. #pragma warning(pop)
  11087. #endif
  11088. // end catch_reporter_xml.cpp
  11089. namespace Catch {
  11090. LeakDetector leakDetector;
  11091. }
  11092. #ifdef __clang__
  11093. #pragma clang diagnostic pop
  11094. #endif
  11095. // end catch_impl.hpp
  11096. #endif
  11097. #ifdef CATCH_CONFIG_MAIN
  11098. // start catch_default_main.hpp
  11099. #ifndef __OBJC__
  11100. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  11101. // Standard C/C++ Win32 Unicode wmain entry point
  11102. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  11103. #else
  11104. // Standard C/C++ main entry point
  11105. int main (int argc, char * argv[]) {
  11106. #endif
  11107. return Catch::Session().run( argc, argv );
  11108. }
  11109. #else // __OBJC__
  11110. // Objective-C entry point
  11111. int main (int argc, char * const argv[]) {
  11112. #if !CATCH_ARC_ENABLED
  11113. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  11114. #endif
  11115. Catch::registerTestMethods();
  11116. int result = Catch::Session().run( argc, (char**)argv );
  11117. #if !CATCH_ARC_ENABLED
  11118. [pool drain];
  11119. #endif
  11120. return result;
  11121. }
  11122. #endif // __OBJC__
  11123. // end catch_default_main.hpp
  11124. #endif
  11125. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  11126. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  11127. # undef CLARA_CONFIG_MAIN
  11128. #endif
  11129. #if !defined(CATCH_CONFIG_DISABLE)
  11130. //////
  11131. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  11132. #ifdef CATCH_CONFIG_PREFIX_ALL
  11133. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11134. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11135. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", __VA_ARGS__ )
  11136. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  11137. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  11138. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11139. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  11140. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  11141. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11142. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11143. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11144. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11145. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11146. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  11147. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", __VA_ARGS__ )
  11148. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  11149. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11150. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11151. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11152. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11153. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11154. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11155. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  11156. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  11157. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11158. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  11159. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  11160. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  11161. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  11162. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11163. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  11164. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  11165. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  11166. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  11167. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11168. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11169. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11170. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  11171. // "BDD-style" convenience wrappers
  11172. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  11173. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  11174. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  11175. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  11176. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  11177. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  11178. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  11179. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  11180. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  11181. #else
  11182. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11183. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11184. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11185. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  11186. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  11187. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11188. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  11189. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11190. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11191. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11192. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11193. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11194. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11195. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  11196. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11197. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  11198. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11199. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11200. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11201. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11202. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11203. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11204. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  11205. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  11206. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11207. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  11208. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  11209. #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  11210. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  11211. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11212. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  11213. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  11214. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  11215. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  11216. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11217. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11218. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11219. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  11220. #endif
  11221. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  11222. // "BDD-style" convenience wrappers
  11223. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  11224. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  11225. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  11226. #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  11227. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  11228. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  11229. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  11230. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  11231. using Catch::Detail::Approx;
  11232. #else // CATCH_CONFIG_DISABLE
  11233. //////
  11234. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  11235. #ifdef CATCH_CONFIG_PREFIX_ALL
  11236. #define CATCH_REQUIRE( ... ) (void)(0)
  11237. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  11238. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  11239. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  11240. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  11241. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11242. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11243. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  11244. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  11245. #define CATCH_CHECK( ... ) (void)(0)
  11246. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  11247. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  11248. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  11249. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  11250. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  11251. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  11252. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  11253. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11254. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11255. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11256. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  11257. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11258. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  11259. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  11260. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11261. #define CATCH_INFO( msg ) (void)(0)
  11262. #define CATCH_WARN( msg ) (void)(0)
  11263. #define CATCH_CAPTURE( msg ) (void)(0)
  11264. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11265. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11266. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  11267. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  11268. #define CATCH_SECTION( ... )
  11269. #define CATCH_DYNAMIC_SECTION( ... )
  11270. #define CATCH_FAIL( ... ) (void)(0)
  11271. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  11272. #define CATCH_SUCCEED( ... ) (void)(0)
  11273. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11274. // "BDD-style" convenience wrappers
  11275. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11276. #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 )
  11277. #define CATCH_GIVEN( desc )
  11278. #define CATCH_AND_GIVEN( desc )
  11279. #define CATCH_WHEN( desc )
  11280. #define CATCH_AND_WHEN( desc )
  11281. #define CATCH_THEN( desc )
  11282. #define CATCH_AND_THEN( desc )
  11283. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  11284. #else
  11285. #define REQUIRE( ... ) (void)(0)
  11286. #define REQUIRE_FALSE( ... ) (void)(0)
  11287. #define REQUIRE_THROWS( ... ) (void)(0)
  11288. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  11289. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  11290. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11291. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11292. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11293. #define REQUIRE_NOTHROW( ... ) (void)(0)
  11294. #define CHECK( ... ) (void)(0)
  11295. #define CHECK_FALSE( ... ) (void)(0)
  11296. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  11297. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  11298. #define CHECK_NOFAIL( ... ) (void)(0)
  11299. #define CHECK_THROWS( ... ) (void)(0)
  11300. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  11301. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  11302. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11303. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11304. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11305. #define CHECK_NOTHROW( ... ) (void)(0)
  11306. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11307. #define CHECK_THAT( arg, matcher ) (void)(0)
  11308. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  11309. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11310. #define INFO( msg ) (void)(0)
  11311. #define WARN( msg ) (void)(0)
  11312. #define CAPTURE( msg ) (void)(0)
  11313. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11314. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11315. #define METHOD_AS_TEST_CASE( method, ... )
  11316. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  11317. #define SECTION( ... )
  11318. #define DYNAMIC_SECTION( ... )
  11319. #define FAIL( ... ) (void)(0)
  11320. #define FAIL_CHECK( ... ) (void)(0)
  11321. #define SUCCEED( ... ) (void)(0)
  11322. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11323. #endif
  11324. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  11325. // "BDD-style" convenience wrappers
  11326. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  11327. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  11328. #define GIVEN( desc )
  11329. #define AND_GIVEN( desc )
  11330. #define WHEN( desc )
  11331. #define AND_WHEN( desc )
  11332. #define THEN( desc )
  11333. #define AND_THEN( desc )
  11334. using Catch::Detail::Approx;
  11335. #endif
  11336. #endif // ! CATCH_CONFIG_IMPL_ONLY
  11337. // start catch_reenable_warnings.h
  11338. #ifdef __clang__
  11339. # ifdef __ICC // icpc defines the __clang__ macro
  11340. # pragma warning(pop)
  11341. # else
  11342. # pragma clang diagnostic pop
  11343. # endif
  11344. #elif defined __GNUC__
  11345. # pragma GCC diagnostic pop
  11346. #endif
  11347. // end catch_reenable_warnings.h
  11348. // end catch.hpp
  11349. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED