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

14076 lines
465KB

  1. /*
  2. * Catch v2.4.2
  3. * Generated: 2018-10-26 21:12:29.223927
  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 2
  17. #ifdef __clang__
  18. # pragma clang system_header
  19. #elif defined __GNUC__
  20. # pragma GCC system_header
  21. #endif
  22. // start catch_suppress_warnings.h
  23. #ifdef __clang__
  24. # ifdef __ICC // icpc defines the __clang__ macro
  25. # pragma warning(push)
  26. # pragma warning(disable: 161 1682)
  27. # else // __ICC
  28. # pragma clang diagnostic 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) || (defined(_MSVC_LANG) && _MSVC_LANG >= 201402L)
  104. # define CATCH_CPP14_OR_GREATER
  105. # endif
  106. # if (__cplusplus >= 201703L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 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. // some versions of cygwin (most) do not support std::to_string. Use the libstd check.
  167. // https://gcc.gnu.org/onlinedocs/gcc-4.8.2/libstdc++/api/a01053_source.html line 2812-2813
  168. # if !((__cplusplus >= 201103L) && defined(_GLIBCXX_USE_C99) \
  169. && !defined(_GLIBCXX_HAVE_BROKEN_VSWPRINTF))
  170. # define CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING
  171. # endif
  172. #endif // __CYGWIN__
  173. ////////////////////////////////////////////////////////////////////////////////
  174. // Visual C++
  175. #ifdef _MSC_VER
  176. # if _MSC_VER >= 1900 // Visual Studio 2015 or newer
  177. # define CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  178. # endif
  179. // Universal Windows platform does not support SEH
  180. // Or console colours (or console at all...)
  181. # if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP)
  182. # define CATCH_CONFIG_COLOUR_NONE
  183. # else
  184. # define CATCH_INTERNAL_CONFIG_WINDOWS_SEH
  185. # endif
  186. #endif // _MSC_VER
  187. ////////////////////////////////////////////////////////////////////////////////
  188. // Check if we are compiled with -fno-exceptions or equivalent
  189. #if defined(__EXCEPTIONS) || defined(__cpp_exceptions) || defined(_CPPUNWIND)
  190. # define CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED
  191. #endif
  192. ////////////////////////////////////////////////////////////////////////////////
  193. // DJGPP
  194. #ifdef __DJGPP__
  195. # define CATCH_INTERNAL_CONFIG_NO_WCHAR
  196. #endif // __DJGPP__
  197. ////////////////////////////////////////////////////////////////////////////////
  198. // Use of __COUNTER__ is suppressed during code analysis in
  199. // CLion/AppCode 2017.2.x and former, because __COUNTER__ is not properly
  200. // handled by it.
  201. // Otherwise all supported compilers support COUNTER macro,
  202. // but user still might want to turn it off
  203. #if ( !defined(__JETBRAINS_IDE__) || __JETBRAINS_IDE__ >= 20170300L )
  204. #define CATCH_INTERNAL_CONFIG_COUNTER
  205. #endif
  206. ////////////////////////////////////////////////////////////////////////////////
  207. // Check if string_view is available and usable
  208. // The check is split apart to work around v140 (VS2015) preprocessor issue...
  209. #if defined(__has_include)
  210. #if __has_include(<string_view>) && defined(CATCH_CPP17_OR_GREATER)
  211. # define CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW
  212. #endif
  213. #endif
  214. ////////////////////////////////////////////////////////////////////////////////
  215. // Check if variant is available and usable
  216. #if defined(__has_include)
  217. # if __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  218. # if defined(__clang__) && (__clang_major__ < 8)
  219. // work around clang bug with libstdc++ https://bugs.llvm.org/show_bug.cgi?id=31852
  220. // fix should be in clang 8, workaround in libstdc++ 8.2
  221. # include <ciso646>
  222. # if defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  223. # define CATCH_CONFIG_NO_CPP17_VARIANT
  224. # else
  225. # define CATCH_INTERNAL_CONFIG_CPP17_VARIANT
  226. # endif // defined(__GLIBCXX__) && defined(_GLIBCXX_RELEASE) && (_GLIBCXX_RELEASE < 9)
  227. # endif // defined(__clang__) && (__clang_major__ < 8)
  228. # endif // __has_include(<variant>) && defined(CATCH_CPP17_OR_GREATER)
  229. #endif // __has_include
  230. #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER)
  231. # define CATCH_CONFIG_COUNTER
  232. #endif
  233. #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)
  234. # define CATCH_CONFIG_WINDOWS_SEH
  235. #endif
  236. // This is set by default, because we assume that unix compilers are posix-signal-compatible by default.
  237. #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)
  238. # define CATCH_CONFIG_POSIX_SIGNALS
  239. #endif
  240. // This is set by default, because we assume that compilers with no wchar_t support are just rare exceptions.
  241. #if !defined(CATCH_INTERNAL_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_NO_WCHAR) && !defined(CATCH_CONFIG_WCHAR)
  242. # define CATCH_CONFIG_WCHAR
  243. #endif
  244. #if !defined(CATCH_INTERNAL_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_NO_CPP11_TO_STRING) && !defined(CATCH_CONFIG_CPP11_TO_STRING)
  245. # define CATCH_CONFIG_CPP11_TO_STRING
  246. #endif
  247. #if defined(CATCH_INTERNAL_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_NO_CPP17_UNCAUGHT_EXCEPTIONS) && !defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  248. # define CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS
  249. #endif
  250. #if defined(CATCH_INTERNAL_CONFIG_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_NO_CPP17_STRING_VIEW) && !defined(CATCH_CONFIG_CPP17_STRING_VIEW)
  251. # define CATCH_CONFIG_CPP17_STRING_VIEW
  252. #endif
  253. #if defined(CATCH_INTERNAL_CONFIG_CPP17_VARIANT) && !defined(CATCH_CONFIG_NO_CPP17_VARIANT) && !defined(CATCH_CONFIG_CPP17_VARIANT)
  254. # define CATCH_CONFIG_CPP17_VARIANT
  255. #endif
  256. #if defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  257. # define CATCH_INTERNAL_CONFIG_NEW_CAPTURE
  258. #endif
  259. #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)
  260. # define CATCH_CONFIG_NEW_CAPTURE
  261. #endif
  262. #if !defined(CATCH_INTERNAL_CONFIG_EXCEPTIONS_ENABLED) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  263. # define CATCH_CONFIG_DISABLE_EXCEPTIONS
  264. #endif
  265. #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS)
  266. # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS
  267. # define CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS
  268. #endif
  269. #if !defined(CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS)
  270. # define CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  271. # define CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  272. #endif
  273. #if !defined(CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS)
  274. # define CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS
  275. # define CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  276. #endif
  277. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  278. #define CATCH_TRY if ((true))
  279. #define CATCH_CATCH_ALL if ((false))
  280. #define CATCH_CATCH_ANON(type) if ((false))
  281. #else
  282. #define CATCH_TRY try
  283. #define CATCH_CATCH_ALL catch (...)
  284. #define CATCH_CATCH_ANON(type) catch (type)
  285. #endif
  286. // end catch_compiler_capabilities.h
  287. #define INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line ) name##line
  288. #define INTERNAL_CATCH_UNIQUE_NAME_LINE( name, line ) INTERNAL_CATCH_UNIQUE_NAME_LINE2( name, line )
  289. #ifdef CATCH_CONFIG_COUNTER
  290. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __COUNTER__ )
  291. #else
  292. # define INTERNAL_CATCH_UNIQUE_NAME( name ) INTERNAL_CATCH_UNIQUE_NAME_LINE( name, __LINE__ )
  293. #endif
  294. #include <iosfwd>
  295. #include <string>
  296. #include <cstdint>
  297. // We need a dummy global operator<< so we can bring it into Catch namespace later
  298. struct Catch_global_namespace_dummy {};
  299. std::ostream& operator<<(std::ostream&, Catch_global_namespace_dummy);
  300. namespace Catch {
  301. struct CaseSensitive { enum Choice {
  302. Yes,
  303. No
  304. }; };
  305. class NonCopyable {
  306. NonCopyable( NonCopyable const& ) = delete;
  307. NonCopyable( NonCopyable && ) = delete;
  308. NonCopyable& operator = ( NonCopyable const& ) = delete;
  309. NonCopyable& operator = ( NonCopyable && ) = delete;
  310. protected:
  311. NonCopyable();
  312. virtual ~NonCopyable();
  313. };
  314. struct SourceLineInfo {
  315. SourceLineInfo() = delete;
  316. SourceLineInfo( char const* _file, std::size_t _line ) noexcept
  317. : file( _file ),
  318. line( _line )
  319. {}
  320. SourceLineInfo( SourceLineInfo const& other ) = default;
  321. SourceLineInfo( SourceLineInfo && ) = default;
  322. SourceLineInfo& operator = ( SourceLineInfo const& ) = default;
  323. SourceLineInfo& operator = ( SourceLineInfo && ) = default;
  324. bool empty() const noexcept;
  325. bool operator == ( SourceLineInfo const& other ) const noexcept;
  326. bool operator < ( SourceLineInfo const& other ) const noexcept;
  327. char const* file;
  328. std::size_t line;
  329. };
  330. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info );
  331. // Bring in operator<< from global namespace into Catch namespace
  332. // This is necessary because the overload of operator<< above makes
  333. // lookup stop at namespace Catch
  334. using ::operator<<;
  335. // Use this in variadic streaming macros to allow
  336. // >> +StreamEndStop
  337. // as well as
  338. // >> stuff +StreamEndStop
  339. struct StreamEndStop {
  340. std::string operator+() const;
  341. };
  342. template<typename T>
  343. T const& operator + ( T const& value, StreamEndStop ) {
  344. return value;
  345. }
  346. }
  347. #define CATCH_INTERNAL_LINEINFO \
  348. ::Catch::SourceLineInfo( __FILE__, static_cast<std::size_t>( __LINE__ ) )
  349. // end catch_common.h
  350. namespace Catch {
  351. struct RegistrarForTagAliases {
  352. RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo );
  353. };
  354. } // end namespace Catch
  355. #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) \
  356. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  357. namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } \
  358. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  359. // end catch_tag_alias_autoregistrar.h
  360. // start catch_test_registry.h
  361. // start catch_interfaces_testcase.h
  362. #include <vector>
  363. #include <memory>
  364. namespace Catch {
  365. class TestSpec;
  366. struct ITestInvoker {
  367. virtual void invoke () const = 0;
  368. virtual ~ITestInvoker();
  369. };
  370. using ITestCasePtr = std::shared_ptr<ITestInvoker>;
  371. class TestCase;
  372. struct IConfig;
  373. struct ITestCaseRegistry {
  374. virtual ~ITestCaseRegistry();
  375. virtual std::vector<TestCase> const& getAllTests() const = 0;
  376. virtual std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const = 0;
  377. };
  378. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  379. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  380. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  381. }
  382. // end catch_interfaces_testcase.h
  383. // start catch_stringref.h
  384. #include <cstddef>
  385. #include <string>
  386. #include <iosfwd>
  387. namespace Catch {
  388. class StringData;
  389. /// A non-owning string class (similar to the forthcoming std::string_view)
  390. /// Note that, because a StringRef may be a substring of another string,
  391. /// it may not be null terminated. c_str() must return a null terminated
  392. /// string, however, and so the StringRef will internally take ownership
  393. /// (taking a copy), if necessary. In theory this ownership is not externally
  394. /// visible - but it does mean (substring) StringRefs should not be shared between
  395. /// threads.
  396. class StringRef {
  397. public:
  398. using size_type = std::size_t;
  399. private:
  400. friend struct StringRefTestAccess;
  401. char const* m_start;
  402. size_type m_size;
  403. char* m_data = nullptr;
  404. void takeOwnership();
  405. static constexpr char const* const s_empty = "";
  406. public: // construction/ assignment
  407. StringRef() noexcept
  408. : StringRef( s_empty, 0 )
  409. {}
  410. StringRef( StringRef const& other ) noexcept
  411. : m_start( other.m_start ),
  412. m_size( other.m_size )
  413. {}
  414. StringRef( StringRef&& other ) noexcept
  415. : m_start( other.m_start ),
  416. m_size( other.m_size ),
  417. m_data( other.m_data )
  418. {
  419. other.m_data = nullptr;
  420. }
  421. StringRef( char const* rawChars ) noexcept;
  422. StringRef( char const* rawChars, size_type size ) noexcept
  423. : m_start( rawChars ),
  424. m_size( size )
  425. {}
  426. StringRef( std::string const& stdString ) noexcept
  427. : m_start( stdString.c_str() ),
  428. m_size( stdString.size() )
  429. {}
  430. ~StringRef() noexcept {
  431. delete[] m_data;
  432. }
  433. auto operator = ( StringRef const &other ) noexcept -> StringRef& {
  434. delete[] m_data;
  435. m_data = nullptr;
  436. m_start = other.m_start;
  437. m_size = other.m_size;
  438. return *this;
  439. }
  440. operator std::string() const;
  441. void swap( StringRef& other ) noexcept;
  442. public: // operators
  443. auto operator == ( StringRef const& other ) const noexcept -> bool;
  444. auto operator != ( StringRef const& other ) const noexcept -> bool;
  445. auto operator[] ( size_type index ) const noexcept -> char;
  446. public: // named queries
  447. auto empty() const noexcept -> bool {
  448. return m_size == 0;
  449. }
  450. auto size() const noexcept -> size_type {
  451. return m_size;
  452. }
  453. auto numberOfCharacters() const noexcept -> size_type;
  454. auto c_str() const -> char const*;
  455. public: // substrings and searches
  456. auto substr( size_type start, size_type size ) const noexcept -> StringRef;
  457. // Returns the current start pointer.
  458. // Note that the pointer can change when if the StringRef is a substring
  459. auto currentData() const noexcept -> char const*;
  460. private: // ownership queries - may not be consistent between calls
  461. auto isOwned() const noexcept -> bool;
  462. auto isSubstring() const noexcept -> bool;
  463. };
  464. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string;
  465. auto operator + ( StringRef const& lhs, char const* rhs ) -> std::string;
  466. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string;
  467. auto operator += ( std::string& lhs, StringRef const& sr ) -> std::string&;
  468. auto operator << ( std::ostream& os, StringRef const& sr ) -> std::ostream&;
  469. inline auto operator "" _sr( char const* rawChars, std::size_t size ) noexcept -> StringRef {
  470. return StringRef( rawChars, size );
  471. }
  472. } // namespace Catch
  473. inline auto operator "" _catch_sr( char const* rawChars, std::size_t size ) noexcept -> Catch::StringRef {
  474. return Catch::StringRef( rawChars, size );
  475. }
  476. // end catch_stringref.h
  477. namespace Catch {
  478. template<typename C>
  479. class TestInvokerAsMethod : public ITestInvoker {
  480. void (C::*m_testAsMethod)();
  481. public:
  482. TestInvokerAsMethod( void (C::*testAsMethod)() ) noexcept : m_testAsMethod( testAsMethod ) {}
  483. void invoke() const override {
  484. C obj;
  485. (obj.*m_testAsMethod)();
  486. }
  487. };
  488. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker*;
  489. template<typename C>
  490. auto makeTestInvoker( void (C::*testAsMethod)() ) noexcept -> ITestInvoker* {
  491. return new(std::nothrow) TestInvokerAsMethod<C>( testAsMethod );
  492. }
  493. struct NameAndTags {
  494. NameAndTags( StringRef const& name_ = StringRef(), StringRef const& tags_ = StringRef() ) noexcept;
  495. StringRef name;
  496. StringRef tags;
  497. };
  498. struct AutoReg : NonCopyable {
  499. AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept;
  500. ~AutoReg();
  501. };
  502. } // end namespace Catch
  503. #define INTERNAL_CATCH_EXPAND1(param) INTERNAL_CATCH_EXPAND2(param)
  504. #define INTERNAL_CATCH_EXPAND2(...) INTERNAL_CATCH_NO## __VA_ARGS__
  505. #define INTERNAL_CATCH_DEF(...) INTERNAL_CATCH_DEF __VA_ARGS__
  506. #define INTERNAL_CATCH_NOINTERNAL_CATCH_DEF
  507. #if defined(CATCH_CONFIG_DISABLE)
  508. #define INTERNAL_CATCH_TESTCASE_NO_REGISTRATION( TestName, ... ) \
  509. static void TestName()
  510. #define INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION( TestName, ClassName, ... ) \
  511. namespace{ \
  512. struct TestName : INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF ClassName) { \
  513. void test(); \
  514. }; \
  515. } \
  516. void TestName::test()
  517. #endif
  518. ///////////////////////////////////////////////////////////////////////////////
  519. #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \
  520. static void TestName(); \
  521. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  522. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &TestName ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  523. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  524. static void TestName()
  525. #define INTERNAL_CATCH_TESTCASE( ... ) \
  526. INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ )
  527. ///////////////////////////////////////////////////////////////////////////////
  528. #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \
  529. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  530. namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( &QualifiedMethod ), CATCH_INTERNAL_LINEINFO, "&" #QualifiedMethod, Catch::NameAndTags{ __VA_ARGS__ } ); } /* NOLINT */ \
  531. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  532. ///////////////////////////////////////////////////////////////////////////////
  533. #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\
  534. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  535. namespace{ \
  536. struct TestName : INTERNAL_CATCH_EXPAND1(INTERNAL_CATCH_DEF ClassName) { \
  537. void test(); \
  538. }; \
  539. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( Catch::makeTestInvoker( &TestName::test ), CATCH_INTERNAL_LINEINFO, #ClassName, Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  540. } \
  541. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  542. void TestName::test()
  543. #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \
  544. INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ )
  545. ///////////////////////////////////////////////////////////////////////////////
  546. #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \
  547. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  548. Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( Catch::makeTestInvoker( Function ), CATCH_INTERNAL_LINEINFO, Catch::StringRef(), Catch::NameAndTags{ __VA_ARGS__ } ); /* NOLINT */ \
  549. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  550. // end catch_test_registry.h
  551. // start catch_capture.hpp
  552. // start catch_assertionhandler.h
  553. // start catch_assertioninfo.h
  554. // start catch_result_type.h
  555. namespace Catch {
  556. // ResultWas::OfType enum
  557. struct ResultWas { enum OfType {
  558. Unknown = -1,
  559. Ok = 0,
  560. Info = 1,
  561. Warning = 2,
  562. FailureBit = 0x10,
  563. ExpressionFailed = FailureBit | 1,
  564. ExplicitFailure = FailureBit | 2,
  565. Exception = 0x100 | FailureBit,
  566. ThrewException = Exception | 1,
  567. DidntThrowException = Exception | 2,
  568. FatalErrorCondition = 0x200 | FailureBit
  569. }; };
  570. bool isOk( ResultWas::OfType resultType );
  571. bool isJustInfo( int flags );
  572. // ResultDisposition::Flags enum
  573. struct ResultDisposition { enum Flags {
  574. Normal = 0x01,
  575. ContinueOnFailure = 0x02, // Failures fail test, but execution continues
  576. FalseTest = 0x04, // Prefix expression with !
  577. SuppressFail = 0x08 // Failures are reported but do not fail the test
  578. }; };
  579. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs );
  580. bool shouldContinueOnFailure( int flags );
  581. inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; }
  582. bool shouldSuppressFailure( int flags );
  583. } // end namespace Catch
  584. // end catch_result_type.h
  585. namespace Catch {
  586. struct AssertionInfo
  587. {
  588. StringRef macroName;
  589. SourceLineInfo lineInfo;
  590. StringRef capturedExpression;
  591. ResultDisposition::Flags resultDisposition;
  592. // We want to delete this constructor but a compiler bug in 4.8 means
  593. // the struct is then treated as non-aggregate
  594. //AssertionInfo() = delete;
  595. };
  596. } // end namespace Catch
  597. // end catch_assertioninfo.h
  598. // start catch_decomposer.h
  599. // start catch_tostring.h
  600. #include <vector>
  601. #include <cstddef>
  602. #include <type_traits>
  603. #include <string>
  604. // start catch_stream.h
  605. #include <iosfwd>
  606. #include <cstddef>
  607. #include <ostream>
  608. namespace Catch {
  609. std::ostream& cout();
  610. std::ostream& cerr();
  611. std::ostream& clog();
  612. class StringRef;
  613. struct IStream {
  614. virtual ~IStream();
  615. virtual std::ostream& stream() const = 0;
  616. };
  617. auto makeStream( StringRef const &filename ) -> IStream const*;
  618. class ReusableStringStream {
  619. std::size_t m_index;
  620. std::ostream* m_oss;
  621. public:
  622. ReusableStringStream();
  623. ~ReusableStringStream();
  624. auto str() const -> std::string;
  625. template<typename T>
  626. auto operator << ( T const& value ) -> ReusableStringStream& {
  627. *m_oss << value;
  628. return *this;
  629. }
  630. auto get() -> std::ostream& { return *m_oss; }
  631. };
  632. }
  633. // end catch_stream.h
  634. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  635. #include <string_view>
  636. #endif
  637. #ifdef __OBJC__
  638. // start catch_objc_arc.hpp
  639. #import <Foundation/Foundation.h>
  640. #ifdef __has_feature
  641. #define CATCH_ARC_ENABLED __has_feature(objc_arc)
  642. #else
  643. #define CATCH_ARC_ENABLED 0
  644. #endif
  645. void arcSafeRelease( NSObject* obj );
  646. id performOptionalSelector( id obj, SEL sel );
  647. #if !CATCH_ARC_ENABLED
  648. inline void arcSafeRelease( NSObject* obj ) {
  649. [obj release];
  650. }
  651. inline id performOptionalSelector( id obj, SEL sel ) {
  652. if( [obj respondsToSelector: sel] )
  653. return [obj performSelector: sel];
  654. return nil;
  655. }
  656. #define CATCH_UNSAFE_UNRETAINED
  657. #define CATCH_ARC_STRONG
  658. #else
  659. inline void arcSafeRelease( NSObject* ){}
  660. inline id performOptionalSelector( id obj, SEL sel ) {
  661. #ifdef __clang__
  662. #pragma clang diagnostic push
  663. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  664. #endif
  665. if( [obj respondsToSelector: sel] )
  666. return [obj performSelector: sel];
  667. #ifdef __clang__
  668. #pragma clang diagnostic pop
  669. #endif
  670. return nil;
  671. }
  672. #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained
  673. #define CATCH_ARC_STRONG __strong
  674. #endif
  675. // end catch_objc_arc.hpp
  676. #endif
  677. #ifdef _MSC_VER
  678. #pragma warning(push)
  679. #pragma warning(disable:4180) // We attempt to stream a function (address) by const&, which MSVC complains about but is harmless
  680. #endif
  681. namespace Catch {
  682. namespace Detail {
  683. extern const std::string unprintableString;
  684. std::string rawMemoryToString( const void *object, std::size_t size );
  685. template<typename T>
  686. std::string rawMemoryToString( const T& object ) {
  687. return rawMemoryToString( &object, sizeof(object) );
  688. }
  689. template<typename T>
  690. class IsStreamInsertable {
  691. template<typename SS, typename TT>
  692. static auto test(int)
  693. -> decltype(std::declval<SS&>() << std::declval<TT>(), std::true_type());
  694. template<typename, typename>
  695. static auto test(...)->std::false_type;
  696. public:
  697. static const bool value = decltype(test<std::ostream, const T&>(0))::value;
  698. };
  699. template<typename E>
  700. std::string convertUnknownEnumToString( E e );
  701. template<typename T>
  702. typename std::enable_if<
  703. !std::is_enum<T>::value && !std::is_base_of<std::exception, T>::value,
  704. std::string>::type convertUnstreamable( T const& ) {
  705. return Detail::unprintableString;
  706. }
  707. template<typename T>
  708. typename std::enable_if<
  709. !std::is_enum<T>::value && std::is_base_of<std::exception, T>::value,
  710. std::string>::type convertUnstreamable(T const& ex) {
  711. return ex.what();
  712. }
  713. template<typename T>
  714. typename std::enable_if<
  715. std::is_enum<T>::value
  716. , std::string>::type convertUnstreamable( T const& value ) {
  717. return convertUnknownEnumToString( value );
  718. }
  719. #if defined(_MANAGED)
  720. //! Convert a CLR string to a utf8 std::string
  721. template<typename T>
  722. std::string clrReferenceToString( T^ ref ) {
  723. if (ref == nullptr)
  724. return std::string("null");
  725. auto bytes = System::Text::Encoding::UTF8->GetBytes(ref->ToString());
  726. cli::pin_ptr<System::Byte> p = &bytes[0];
  727. return std::string(reinterpret_cast<char const *>(p), bytes->Length);
  728. }
  729. #endif
  730. } // namespace Detail
  731. // If we decide for C++14, change these to enable_if_ts
  732. template <typename T, typename = void>
  733. struct StringMaker {
  734. template <typename Fake = T>
  735. static
  736. typename std::enable_if<::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  737. convert(const Fake& value) {
  738. ReusableStringStream rss;
  739. // NB: call using the function-like syntax to avoid ambiguity with
  740. // user-defined templated operator<< under clang.
  741. rss.operator<<(value);
  742. return rss.str();
  743. }
  744. template <typename Fake = T>
  745. static
  746. typename std::enable_if<!::Catch::Detail::IsStreamInsertable<Fake>::value, std::string>::type
  747. convert( const Fake& value ) {
  748. #if !defined(CATCH_CONFIG_FALLBACK_STRINGIFIER)
  749. return Detail::convertUnstreamable(value);
  750. #else
  751. return CATCH_CONFIG_FALLBACK_STRINGIFIER(value);
  752. #endif
  753. }
  754. };
  755. namespace Detail {
  756. // This function dispatches all stringification requests inside of Catch.
  757. // Should be preferably called fully qualified, like ::Catch::Detail::stringify
  758. template <typename T>
  759. std::string stringify(const T& e) {
  760. return ::Catch::StringMaker<typename std::remove_cv<typename std::remove_reference<T>::type>::type>::convert(e);
  761. }
  762. template<typename E>
  763. std::string convertUnknownEnumToString( E e ) {
  764. return ::Catch::Detail::stringify(static_cast<typename std::underlying_type<E>::type>(e));
  765. }
  766. #if defined(_MANAGED)
  767. template <typename T>
  768. std::string stringify( T^ e ) {
  769. return ::Catch::StringMaker<T^>::convert(e);
  770. }
  771. #endif
  772. } // namespace Detail
  773. // Some predefined specializations
  774. template<>
  775. struct StringMaker<std::string> {
  776. static std::string convert(const std::string& str);
  777. };
  778. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  779. template<>
  780. struct StringMaker<std::string_view> {
  781. static std::string convert(std::string_view str);
  782. };
  783. #endif
  784. template<>
  785. struct StringMaker<char const *> {
  786. static std::string convert(char const * str);
  787. };
  788. template<>
  789. struct StringMaker<char *> {
  790. static std::string convert(char * str);
  791. };
  792. #ifdef CATCH_CONFIG_WCHAR
  793. template<>
  794. struct StringMaker<std::wstring> {
  795. static std::string convert(const std::wstring& wstr);
  796. };
  797. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  798. template<>
  799. struct StringMaker<std::wstring_view> {
  800. static std::string convert(std::wstring_view str);
  801. };
  802. # endif
  803. template<>
  804. struct StringMaker<wchar_t const *> {
  805. static std::string convert(wchar_t const * str);
  806. };
  807. template<>
  808. struct StringMaker<wchar_t *> {
  809. static std::string convert(wchar_t * str);
  810. };
  811. #endif
  812. // TBD: Should we use `strnlen` to ensure that we don't go out of the buffer,
  813. // while keeping string semantics?
  814. template<int SZ>
  815. struct StringMaker<char[SZ]> {
  816. static std::string convert(char const* str) {
  817. return ::Catch::Detail::stringify(std::string{ str });
  818. }
  819. };
  820. template<int SZ>
  821. struct StringMaker<signed char[SZ]> {
  822. static std::string convert(signed char const* str) {
  823. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  824. }
  825. };
  826. template<int SZ>
  827. struct StringMaker<unsigned char[SZ]> {
  828. static std::string convert(unsigned char const* str) {
  829. return ::Catch::Detail::stringify(std::string{ reinterpret_cast<char const *>(str) });
  830. }
  831. };
  832. template<>
  833. struct StringMaker<int> {
  834. static std::string convert(int value);
  835. };
  836. template<>
  837. struct StringMaker<long> {
  838. static std::string convert(long value);
  839. };
  840. template<>
  841. struct StringMaker<long long> {
  842. static std::string convert(long long value);
  843. };
  844. template<>
  845. struct StringMaker<unsigned int> {
  846. static std::string convert(unsigned int value);
  847. };
  848. template<>
  849. struct StringMaker<unsigned long> {
  850. static std::string convert(unsigned long value);
  851. };
  852. template<>
  853. struct StringMaker<unsigned long long> {
  854. static std::string convert(unsigned long long value);
  855. };
  856. template<>
  857. struct StringMaker<bool> {
  858. static std::string convert(bool b);
  859. };
  860. template<>
  861. struct StringMaker<char> {
  862. static std::string convert(char c);
  863. };
  864. template<>
  865. struct StringMaker<signed char> {
  866. static std::string convert(signed char c);
  867. };
  868. template<>
  869. struct StringMaker<unsigned char> {
  870. static std::string convert(unsigned char c);
  871. };
  872. template<>
  873. struct StringMaker<std::nullptr_t> {
  874. static std::string convert(std::nullptr_t);
  875. };
  876. template<>
  877. struct StringMaker<float> {
  878. static std::string convert(float value);
  879. };
  880. template<>
  881. struct StringMaker<double> {
  882. static std::string convert(double value);
  883. };
  884. template <typename T>
  885. struct StringMaker<T*> {
  886. template <typename U>
  887. static std::string convert(U* p) {
  888. if (p) {
  889. return ::Catch::Detail::rawMemoryToString(p);
  890. } else {
  891. return "nullptr";
  892. }
  893. }
  894. };
  895. template <typename R, typename C>
  896. struct StringMaker<R C::*> {
  897. static std::string convert(R C::* p) {
  898. if (p) {
  899. return ::Catch::Detail::rawMemoryToString(p);
  900. } else {
  901. return "nullptr";
  902. }
  903. }
  904. };
  905. #if defined(_MANAGED)
  906. template <typename T>
  907. struct StringMaker<T^> {
  908. static std::string convert( T^ ref ) {
  909. return ::Catch::Detail::clrReferenceToString(ref);
  910. }
  911. };
  912. #endif
  913. namespace Detail {
  914. template<typename InputIterator>
  915. std::string rangeToString(InputIterator first, InputIterator last) {
  916. ReusableStringStream rss;
  917. rss << "{ ";
  918. if (first != last) {
  919. rss << ::Catch::Detail::stringify(*first);
  920. for (++first; first != last; ++first)
  921. rss << ", " << ::Catch::Detail::stringify(*first);
  922. }
  923. rss << " }";
  924. return rss.str();
  925. }
  926. }
  927. #ifdef __OBJC__
  928. template<>
  929. struct StringMaker<NSString*> {
  930. static std::string convert(NSString * nsstring) {
  931. if (!nsstring)
  932. return "nil";
  933. return std::string("@") + [nsstring UTF8String];
  934. }
  935. };
  936. template<>
  937. struct StringMaker<NSObject*> {
  938. static std::string convert(NSObject* nsObject) {
  939. return ::Catch::Detail::stringify([nsObject description]);
  940. }
  941. };
  942. namespace Detail {
  943. inline std::string stringify( NSString* nsstring ) {
  944. return StringMaker<NSString*>::convert( nsstring );
  945. }
  946. } // namespace Detail
  947. #endif // __OBJC__
  948. } // namespace Catch
  949. //////////////////////////////////////////////////////
  950. // Separate std-lib types stringification, so it can be selectively enabled
  951. // This means that we do not bring in
  952. #if defined(CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS)
  953. # define CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  954. # define CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  955. # define CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  956. # define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  957. #endif
  958. // Separate std::pair specialization
  959. #if defined(CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER)
  960. #include <utility>
  961. namespace Catch {
  962. template<typename T1, typename T2>
  963. struct StringMaker<std::pair<T1, T2> > {
  964. static std::string convert(const std::pair<T1, T2>& pair) {
  965. ReusableStringStream rss;
  966. rss << "{ "
  967. << ::Catch::Detail::stringify(pair.first)
  968. << ", "
  969. << ::Catch::Detail::stringify(pair.second)
  970. << " }";
  971. return rss.str();
  972. }
  973. };
  974. }
  975. #endif // CATCH_CONFIG_ENABLE_PAIR_STRINGMAKER
  976. // Separate std::tuple specialization
  977. #if defined(CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER)
  978. #include <tuple>
  979. namespace Catch {
  980. namespace Detail {
  981. template<
  982. typename Tuple,
  983. std::size_t N = 0,
  984. bool = (N < std::tuple_size<Tuple>::value)
  985. >
  986. struct TupleElementPrinter {
  987. static void print(const Tuple& tuple, std::ostream& os) {
  988. os << (N ? ", " : " ")
  989. << ::Catch::Detail::stringify(std::get<N>(tuple));
  990. TupleElementPrinter<Tuple, N + 1>::print(tuple, os);
  991. }
  992. };
  993. template<
  994. typename Tuple,
  995. std::size_t N
  996. >
  997. struct TupleElementPrinter<Tuple, N, false> {
  998. static void print(const Tuple&, std::ostream&) {}
  999. };
  1000. }
  1001. template<typename ...Types>
  1002. struct StringMaker<std::tuple<Types...>> {
  1003. static std::string convert(const std::tuple<Types...>& tuple) {
  1004. ReusableStringStream rss;
  1005. rss << '{';
  1006. Detail::TupleElementPrinter<std::tuple<Types...>>::print(tuple, rss.get());
  1007. rss << " }";
  1008. return rss.str();
  1009. }
  1010. };
  1011. }
  1012. #endif // CATCH_CONFIG_ENABLE_TUPLE_STRINGMAKER
  1013. #if defined(CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER) && defined(CATCH_CONFIG_CPP17_VARIANT)
  1014. #include <variant>
  1015. namespace Catch {
  1016. template<>
  1017. struct StringMaker<std::monostate> {
  1018. static std::string convert(const std::monostate&) {
  1019. return "{ }";
  1020. }
  1021. };
  1022. template<typename... Elements>
  1023. struct StringMaker<std::variant<Elements...>> {
  1024. static std::string convert(const std::variant<Elements...>& variant) {
  1025. if (variant.valueless_by_exception()) {
  1026. return "{valueless variant}";
  1027. } else {
  1028. return std::visit(
  1029. [](const auto& value) {
  1030. return ::Catch::Detail::stringify(value);
  1031. },
  1032. variant
  1033. );
  1034. }
  1035. }
  1036. };
  1037. }
  1038. #endif // CATCH_CONFIG_ENABLE_VARIANT_STRINGMAKER
  1039. namespace Catch {
  1040. struct not_this_one {}; // Tag type for detecting which begin/ end are being selected
  1041. // Import begin/ end from std here so they are considered alongside the fallback (...) overloads in this namespace
  1042. using std::begin;
  1043. using std::end;
  1044. not_this_one begin( ... );
  1045. not_this_one end( ... );
  1046. template <typename T>
  1047. struct is_range {
  1048. static const bool value =
  1049. !std::is_same<decltype(begin(std::declval<T>())), not_this_one>::value &&
  1050. !std::is_same<decltype(end(std::declval<T>())), not_this_one>::value;
  1051. };
  1052. #if defined(_MANAGED) // Managed types are never ranges
  1053. template <typename T>
  1054. struct is_range<T^> {
  1055. static const bool value = false;
  1056. };
  1057. #endif
  1058. template<typename Range>
  1059. std::string rangeToString( Range const& range ) {
  1060. return ::Catch::Detail::rangeToString( begin( range ), end( range ) );
  1061. }
  1062. // Handle vector<bool> specially
  1063. template<typename Allocator>
  1064. std::string rangeToString( std::vector<bool, Allocator> const& v ) {
  1065. ReusableStringStream rss;
  1066. rss << "{ ";
  1067. bool first = true;
  1068. for( bool b : v ) {
  1069. if( first )
  1070. first = false;
  1071. else
  1072. rss << ", ";
  1073. rss << ::Catch::Detail::stringify( b );
  1074. }
  1075. rss << " }";
  1076. return rss.str();
  1077. }
  1078. template<typename R>
  1079. struct StringMaker<R, typename std::enable_if<is_range<R>::value && !::Catch::Detail::IsStreamInsertable<R>::value>::type> {
  1080. static std::string convert( R const& range ) {
  1081. return rangeToString( range );
  1082. }
  1083. };
  1084. template <typename T, int SZ>
  1085. struct StringMaker<T[SZ]> {
  1086. static std::string convert(T const(&arr)[SZ]) {
  1087. return rangeToString(arr);
  1088. }
  1089. };
  1090. } // namespace Catch
  1091. // Separate std::chrono::duration specialization
  1092. #if defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  1093. #include <ctime>
  1094. #include <ratio>
  1095. #include <chrono>
  1096. namespace Catch {
  1097. template <class Ratio>
  1098. struct ratio_string {
  1099. static std::string symbol();
  1100. };
  1101. template <class Ratio>
  1102. std::string ratio_string<Ratio>::symbol() {
  1103. Catch::ReusableStringStream rss;
  1104. rss << '[' << Ratio::num << '/'
  1105. << Ratio::den << ']';
  1106. return rss.str();
  1107. }
  1108. template <>
  1109. struct ratio_string<std::atto> {
  1110. static std::string symbol();
  1111. };
  1112. template <>
  1113. struct ratio_string<std::femto> {
  1114. static std::string symbol();
  1115. };
  1116. template <>
  1117. struct ratio_string<std::pico> {
  1118. static std::string symbol();
  1119. };
  1120. template <>
  1121. struct ratio_string<std::nano> {
  1122. static std::string symbol();
  1123. };
  1124. template <>
  1125. struct ratio_string<std::micro> {
  1126. static std::string symbol();
  1127. };
  1128. template <>
  1129. struct ratio_string<std::milli> {
  1130. static std::string symbol();
  1131. };
  1132. ////////////
  1133. // std::chrono::duration specializations
  1134. template<typename Value, typename Ratio>
  1135. struct StringMaker<std::chrono::duration<Value, Ratio>> {
  1136. static std::string convert(std::chrono::duration<Value, Ratio> const& duration) {
  1137. ReusableStringStream rss;
  1138. rss << duration.count() << ' ' << ratio_string<Ratio>::symbol() << 's';
  1139. return rss.str();
  1140. }
  1141. };
  1142. template<typename Value>
  1143. struct StringMaker<std::chrono::duration<Value, std::ratio<1>>> {
  1144. static std::string convert(std::chrono::duration<Value, std::ratio<1>> const& duration) {
  1145. ReusableStringStream rss;
  1146. rss << duration.count() << " s";
  1147. return rss.str();
  1148. }
  1149. };
  1150. template<typename Value>
  1151. struct StringMaker<std::chrono::duration<Value, std::ratio<60>>> {
  1152. static std::string convert(std::chrono::duration<Value, std::ratio<60>> const& duration) {
  1153. ReusableStringStream rss;
  1154. rss << duration.count() << " m";
  1155. return rss.str();
  1156. }
  1157. };
  1158. template<typename Value>
  1159. struct StringMaker<std::chrono::duration<Value, std::ratio<3600>>> {
  1160. static std::string convert(std::chrono::duration<Value, std::ratio<3600>> const& duration) {
  1161. ReusableStringStream rss;
  1162. rss << duration.count() << " h";
  1163. return rss.str();
  1164. }
  1165. };
  1166. ////////////
  1167. // std::chrono::time_point specialization
  1168. // Generic time_point cannot be specialized, only std::chrono::time_point<system_clock>
  1169. template<typename Clock, typename Duration>
  1170. struct StringMaker<std::chrono::time_point<Clock, Duration>> {
  1171. static std::string convert(std::chrono::time_point<Clock, Duration> const& time_point) {
  1172. return ::Catch::Detail::stringify(time_point.time_since_epoch()) + " since epoch";
  1173. }
  1174. };
  1175. // std::chrono::time_point<system_clock> specialization
  1176. template<typename Duration>
  1177. struct StringMaker<std::chrono::time_point<std::chrono::system_clock, Duration>> {
  1178. static std::string convert(std::chrono::time_point<std::chrono::system_clock, Duration> const& time_point) {
  1179. auto converted = std::chrono::system_clock::to_time_t(time_point);
  1180. #ifdef _MSC_VER
  1181. std::tm timeInfo = {};
  1182. gmtime_s(&timeInfo, &converted);
  1183. #else
  1184. std::tm* timeInfo = std::gmtime(&converted);
  1185. #endif
  1186. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  1187. char timeStamp[timeStampSize];
  1188. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  1189. #ifdef _MSC_VER
  1190. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  1191. #else
  1192. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  1193. #endif
  1194. return std::string(timeStamp);
  1195. }
  1196. };
  1197. }
  1198. #endif // CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  1199. #ifdef _MSC_VER
  1200. #pragma warning(pop)
  1201. #endif
  1202. // end catch_tostring.h
  1203. #include <iosfwd>
  1204. #ifdef _MSC_VER
  1205. #pragma warning(push)
  1206. #pragma warning(disable:4389) // '==' : signed/unsigned mismatch
  1207. #pragma warning(disable:4018) // more "signed/unsigned mismatch"
  1208. #pragma warning(disable:4312) // Converting int to T* using reinterpret_cast (issue on x64 platform)
  1209. #pragma warning(disable:4180) // qualifier applied to function type has no meaning
  1210. #endif
  1211. namespace Catch {
  1212. struct ITransientExpression {
  1213. auto isBinaryExpression() const -> bool { return m_isBinaryExpression; }
  1214. auto getResult() const -> bool { return m_result; }
  1215. virtual void streamReconstructedExpression( std::ostream &os ) const = 0;
  1216. ITransientExpression( bool isBinaryExpression, bool result )
  1217. : m_isBinaryExpression( isBinaryExpression ),
  1218. m_result( result )
  1219. {}
  1220. // We don't actually need a virtual destructor, but many static analysers
  1221. // complain if it's not here :-(
  1222. virtual ~ITransientExpression();
  1223. bool m_isBinaryExpression;
  1224. bool m_result;
  1225. };
  1226. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs );
  1227. template<typename LhsT, typename RhsT>
  1228. class BinaryExpr : public ITransientExpression {
  1229. LhsT m_lhs;
  1230. StringRef m_op;
  1231. RhsT m_rhs;
  1232. void streamReconstructedExpression( std::ostream &os ) const override {
  1233. formatReconstructedExpression
  1234. ( os, Catch::Detail::stringify( m_lhs ), m_op, Catch::Detail::stringify( m_rhs ) );
  1235. }
  1236. public:
  1237. BinaryExpr( bool comparisonResult, LhsT lhs, StringRef op, RhsT rhs )
  1238. : ITransientExpression{ true, comparisonResult },
  1239. m_lhs( lhs ),
  1240. m_op( op ),
  1241. m_rhs( rhs )
  1242. {}
  1243. };
  1244. template<typename LhsT>
  1245. class UnaryExpr : public ITransientExpression {
  1246. LhsT m_lhs;
  1247. void streamReconstructedExpression( std::ostream &os ) const override {
  1248. os << Catch::Detail::stringify( m_lhs );
  1249. }
  1250. public:
  1251. explicit UnaryExpr( LhsT lhs )
  1252. : ITransientExpression{ false, lhs ? true : false },
  1253. m_lhs( lhs )
  1254. {}
  1255. };
  1256. // Specialised comparison functions to handle equality comparisons between ints and pointers (NULL deduces as an int)
  1257. template<typename LhsT, typename RhsT>
  1258. auto compareEqual( LhsT const& lhs, RhsT const& rhs ) -> bool { return static_cast<bool>(lhs == rhs); }
  1259. template<typename T>
  1260. auto compareEqual( T* const& lhs, int rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1261. template<typename T>
  1262. auto compareEqual( T* const& lhs, long rhs ) -> bool { return lhs == reinterpret_cast<void const*>( rhs ); }
  1263. template<typename T>
  1264. auto compareEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1265. template<typename T>
  1266. auto compareEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) == rhs; }
  1267. template<typename LhsT, typename RhsT>
  1268. auto compareNotEqual( LhsT const& lhs, RhsT&& rhs ) -> bool { return static_cast<bool>(lhs != rhs); }
  1269. template<typename T>
  1270. auto compareNotEqual( T* const& lhs, int rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1271. template<typename T>
  1272. auto compareNotEqual( T* const& lhs, long rhs ) -> bool { return lhs != reinterpret_cast<void const*>( rhs ); }
  1273. template<typename T>
  1274. auto compareNotEqual( int lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1275. template<typename T>
  1276. auto compareNotEqual( long lhs, T* const& rhs ) -> bool { return reinterpret_cast<void const*>( lhs ) != rhs; }
  1277. template<typename LhsT>
  1278. class ExprLhs {
  1279. LhsT m_lhs;
  1280. public:
  1281. explicit ExprLhs( LhsT lhs ) : m_lhs( lhs ) {}
  1282. template<typename RhsT>
  1283. auto operator == ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1284. return { compareEqual( m_lhs, rhs ), m_lhs, "==", rhs };
  1285. }
  1286. auto operator == ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1287. return { m_lhs == rhs, m_lhs, "==", rhs };
  1288. }
  1289. template<typename RhsT>
  1290. auto operator != ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1291. return { compareNotEqual( m_lhs, rhs ), m_lhs, "!=", rhs };
  1292. }
  1293. auto operator != ( bool rhs ) -> BinaryExpr<LhsT, bool> const {
  1294. return { m_lhs != rhs, m_lhs, "!=", rhs };
  1295. }
  1296. template<typename RhsT>
  1297. auto operator > ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1298. return { static_cast<bool>(m_lhs > rhs), m_lhs, ">", rhs };
  1299. }
  1300. template<typename RhsT>
  1301. auto operator < ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1302. return { static_cast<bool>(m_lhs < rhs), m_lhs, "<", rhs };
  1303. }
  1304. template<typename RhsT>
  1305. auto operator >= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1306. return { static_cast<bool>(m_lhs >= rhs), m_lhs, ">=", rhs };
  1307. }
  1308. template<typename RhsT>
  1309. auto operator <= ( RhsT const& rhs ) -> BinaryExpr<LhsT, RhsT const&> const {
  1310. return { static_cast<bool>(m_lhs <= rhs), m_lhs, "<=", rhs };
  1311. }
  1312. auto makeUnaryExpr() const -> UnaryExpr<LhsT> {
  1313. return UnaryExpr<LhsT>{ m_lhs };
  1314. }
  1315. };
  1316. void handleExpression( ITransientExpression const& expr );
  1317. template<typename T>
  1318. void handleExpression( ExprLhs<T> const& expr ) {
  1319. handleExpression( expr.makeUnaryExpr() );
  1320. }
  1321. struct Decomposer {
  1322. template<typename T>
  1323. auto operator <= ( T const& lhs ) -> ExprLhs<T const&> {
  1324. return ExprLhs<T const&>{ lhs };
  1325. }
  1326. auto operator <=( bool value ) -> ExprLhs<bool> {
  1327. return ExprLhs<bool>{ value };
  1328. }
  1329. };
  1330. } // end namespace Catch
  1331. #ifdef _MSC_VER
  1332. #pragma warning(pop)
  1333. #endif
  1334. // end catch_decomposer.h
  1335. // start catch_interfaces_capture.h
  1336. #include <string>
  1337. namespace Catch {
  1338. class AssertionResult;
  1339. struct AssertionInfo;
  1340. struct SectionInfo;
  1341. struct SectionEndInfo;
  1342. struct MessageInfo;
  1343. struct Counts;
  1344. struct BenchmarkInfo;
  1345. struct BenchmarkStats;
  1346. struct AssertionReaction;
  1347. struct SourceLineInfo;
  1348. struct ITransientExpression;
  1349. struct IGeneratorTracker;
  1350. struct IResultCapture {
  1351. virtual ~IResultCapture();
  1352. virtual bool sectionStarted( SectionInfo const& sectionInfo,
  1353. Counts& assertions ) = 0;
  1354. virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0;
  1355. virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0;
  1356. virtual auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& = 0;
  1357. virtual void benchmarkStarting( BenchmarkInfo const& info ) = 0;
  1358. virtual void benchmarkEnded( BenchmarkStats const& stats ) = 0;
  1359. virtual void pushScopedMessage( MessageInfo const& message ) = 0;
  1360. virtual void popScopedMessage( MessageInfo const& message ) = 0;
  1361. virtual void handleFatalErrorCondition( StringRef message ) = 0;
  1362. virtual void handleExpr
  1363. ( AssertionInfo const& info,
  1364. ITransientExpression const& expr,
  1365. AssertionReaction& reaction ) = 0;
  1366. virtual void handleMessage
  1367. ( AssertionInfo const& info,
  1368. ResultWas::OfType resultType,
  1369. StringRef const& message,
  1370. AssertionReaction& reaction ) = 0;
  1371. virtual void handleUnexpectedExceptionNotThrown
  1372. ( AssertionInfo const& info,
  1373. AssertionReaction& reaction ) = 0;
  1374. virtual void handleUnexpectedInflightException
  1375. ( AssertionInfo const& info,
  1376. std::string const& message,
  1377. AssertionReaction& reaction ) = 0;
  1378. virtual void handleIncomplete
  1379. ( AssertionInfo const& info ) = 0;
  1380. virtual void handleNonExpr
  1381. ( AssertionInfo const &info,
  1382. ResultWas::OfType resultType,
  1383. AssertionReaction &reaction ) = 0;
  1384. virtual bool lastAssertionPassed() = 0;
  1385. virtual void assertionPassed() = 0;
  1386. // Deprecated, do not use:
  1387. virtual std::string getCurrentTestName() const = 0;
  1388. virtual const AssertionResult* getLastResult() const = 0;
  1389. virtual void exceptionEarlyReported() = 0;
  1390. };
  1391. IResultCapture& getResultCapture();
  1392. }
  1393. // end catch_interfaces_capture.h
  1394. namespace Catch {
  1395. struct TestFailureException{};
  1396. struct AssertionResultData;
  1397. struct IResultCapture;
  1398. class RunContext;
  1399. class LazyExpression {
  1400. friend class AssertionHandler;
  1401. friend struct AssertionStats;
  1402. friend class RunContext;
  1403. ITransientExpression const* m_transientExpression = nullptr;
  1404. bool m_isNegated;
  1405. public:
  1406. LazyExpression( bool isNegated );
  1407. LazyExpression( LazyExpression const& other );
  1408. LazyExpression& operator = ( LazyExpression const& ) = delete;
  1409. explicit operator bool() const;
  1410. friend auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream&;
  1411. };
  1412. struct AssertionReaction {
  1413. bool shouldDebugBreak = false;
  1414. bool shouldThrow = false;
  1415. };
  1416. class AssertionHandler {
  1417. AssertionInfo m_assertionInfo;
  1418. AssertionReaction m_reaction;
  1419. bool m_completed = false;
  1420. IResultCapture& m_resultCapture;
  1421. public:
  1422. AssertionHandler
  1423. ( StringRef const& macroName,
  1424. SourceLineInfo const& lineInfo,
  1425. StringRef capturedExpression,
  1426. ResultDisposition::Flags resultDisposition );
  1427. ~AssertionHandler() {
  1428. if ( !m_completed ) {
  1429. m_resultCapture.handleIncomplete( m_assertionInfo );
  1430. }
  1431. }
  1432. template<typename T>
  1433. void handleExpr( ExprLhs<T> const& expr ) {
  1434. handleExpr( expr.makeUnaryExpr() );
  1435. }
  1436. void handleExpr( ITransientExpression const& expr );
  1437. void handleMessage(ResultWas::OfType resultType, StringRef const& message);
  1438. void handleExceptionThrownAsExpected();
  1439. void handleUnexpectedExceptionNotThrown();
  1440. void handleExceptionNotThrownAsExpected();
  1441. void handleThrowingCallSkipped();
  1442. void handleUnexpectedInflightException();
  1443. void complete();
  1444. void setCompleted();
  1445. // query
  1446. auto allowThrows() const -> bool;
  1447. };
  1448. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString );
  1449. } // namespace Catch
  1450. // end catch_assertionhandler.h
  1451. // start catch_message.h
  1452. #include <string>
  1453. #include <vector>
  1454. namespace Catch {
  1455. struct MessageInfo {
  1456. MessageInfo( StringRef const& _macroName,
  1457. SourceLineInfo const& _lineInfo,
  1458. ResultWas::OfType _type );
  1459. StringRef macroName;
  1460. std::string message;
  1461. SourceLineInfo lineInfo;
  1462. ResultWas::OfType type;
  1463. unsigned int sequence;
  1464. bool operator == ( MessageInfo const& other ) const;
  1465. bool operator < ( MessageInfo const& other ) const;
  1466. private:
  1467. static unsigned int globalCount;
  1468. };
  1469. struct MessageStream {
  1470. template<typename T>
  1471. MessageStream& operator << ( T const& value ) {
  1472. m_stream << value;
  1473. return *this;
  1474. }
  1475. ReusableStringStream m_stream;
  1476. };
  1477. struct MessageBuilder : MessageStream {
  1478. MessageBuilder( StringRef const& macroName,
  1479. SourceLineInfo const& lineInfo,
  1480. ResultWas::OfType type );
  1481. template<typename T>
  1482. MessageBuilder& operator << ( T const& value ) {
  1483. m_stream << value;
  1484. return *this;
  1485. }
  1486. MessageInfo m_info;
  1487. };
  1488. class ScopedMessage {
  1489. public:
  1490. explicit ScopedMessage( MessageBuilder const& builder );
  1491. ~ScopedMessage();
  1492. MessageInfo m_info;
  1493. };
  1494. class Capturer {
  1495. std::vector<MessageInfo> m_messages;
  1496. IResultCapture& m_resultCapture = getResultCapture();
  1497. size_t m_captured = 0;
  1498. public:
  1499. Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names );
  1500. ~Capturer();
  1501. void captureValue( size_t index, StringRef value );
  1502. template<typename T>
  1503. void captureValues( size_t index, T&& value ) {
  1504. captureValue( index, Catch::Detail::stringify( value ) );
  1505. }
  1506. template<typename T, typename... Ts>
  1507. void captureValues( size_t index, T&& value, Ts&&... values ) {
  1508. captureValues( index, value );
  1509. captureValues( index+1, values... );
  1510. }
  1511. };
  1512. } // end namespace Catch
  1513. // end catch_message.h
  1514. #if !defined(CATCH_CONFIG_DISABLE)
  1515. #if !defined(CATCH_CONFIG_DISABLE_STRINGIFICATION)
  1516. #define CATCH_INTERNAL_STRINGIFY(...) #__VA_ARGS__
  1517. #else
  1518. #define CATCH_INTERNAL_STRINGIFY(...) "Disabled by CATCH_CONFIG_DISABLE_STRINGIFICATION"
  1519. #endif
  1520. #if defined(CATCH_CONFIG_FAST_COMPILE) || defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  1521. ///////////////////////////////////////////////////////////////////////////////
  1522. // Another way to speed-up compilation is to omit local try-catch for REQUIRE*
  1523. // macros.
  1524. #define INTERNAL_CATCH_TRY
  1525. #define INTERNAL_CATCH_CATCH( capturer )
  1526. #else // CATCH_CONFIG_FAST_COMPILE
  1527. #define INTERNAL_CATCH_TRY try
  1528. #define INTERNAL_CATCH_CATCH( handler ) catch(...) { handler.handleUnexpectedInflightException(); }
  1529. #endif
  1530. #define INTERNAL_CATCH_REACT( handler ) handler.complete();
  1531. ///////////////////////////////////////////////////////////////////////////////
  1532. #define INTERNAL_CATCH_TEST( macroName, resultDisposition, ... ) \
  1533. do { \
  1534. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1535. INTERNAL_CATCH_TRY { \
  1536. CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \
  1537. catchAssertionHandler.handleExpr( Catch::Decomposer() <= __VA_ARGS__ ); \
  1538. CATCH_INTERNAL_UNSUPPRESS_PARENTHESES_WARNINGS \
  1539. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  1540. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1541. } 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
  1542. // The double negation silences MSVC's C4800 warning, the static_cast forces short-circuit evaluation if the type has overloaded &&.
  1543. ///////////////////////////////////////////////////////////////////////////////
  1544. #define INTERNAL_CATCH_IF( macroName, resultDisposition, ... ) \
  1545. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1546. if( Catch::getResultCapture().lastAssertionPassed() )
  1547. ///////////////////////////////////////////////////////////////////////////////
  1548. #define INTERNAL_CATCH_ELSE( macroName, resultDisposition, ... ) \
  1549. INTERNAL_CATCH_TEST( macroName, resultDisposition, __VA_ARGS__ ); \
  1550. if( !Catch::getResultCapture().lastAssertionPassed() )
  1551. ///////////////////////////////////////////////////////////////////////////////
  1552. #define INTERNAL_CATCH_NO_THROW( macroName, resultDisposition, ... ) \
  1553. do { \
  1554. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition ); \
  1555. try { \
  1556. static_cast<void>(__VA_ARGS__); \
  1557. catchAssertionHandler.handleExceptionNotThrownAsExpected(); \
  1558. } \
  1559. catch( ... ) { \
  1560. catchAssertionHandler.handleUnexpectedInflightException(); \
  1561. } \
  1562. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1563. } while( false )
  1564. ///////////////////////////////////////////////////////////////////////////////
  1565. #define INTERNAL_CATCH_THROWS( macroName, resultDisposition, ... ) \
  1566. do { \
  1567. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__), resultDisposition); \
  1568. if( catchAssertionHandler.allowThrows() ) \
  1569. try { \
  1570. static_cast<void>(__VA_ARGS__); \
  1571. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1572. } \
  1573. catch( ... ) { \
  1574. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1575. } \
  1576. else \
  1577. catchAssertionHandler.handleThrowingCallSkipped(); \
  1578. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1579. } while( false )
  1580. ///////////////////////////////////////////////////////////////////////////////
  1581. #define INTERNAL_CATCH_THROWS_AS( macroName, exceptionType, resultDisposition, expr ) \
  1582. do { \
  1583. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(expr) ", " CATCH_INTERNAL_STRINGIFY(exceptionType), resultDisposition ); \
  1584. if( catchAssertionHandler.allowThrows() ) \
  1585. try { \
  1586. static_cast<void>(expr); \
  1587. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1588. } \
  1589. catch( exceptionType const& ) { \
  1590. catchAssertionHandler.handleExceptionThrownAsExpected(); \
  1591. } \
  1592. catch( ... ) { \
  1593. catchAssertionHandler.handleUnexpectedInflightException(); \
  1594. } \
  1595. else \
  1596. catchAssertionHandler.handleThrowingCallSkipped(); \
  1597. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1598. } while( false )
  1599. ///////////////////////////////////////////////////////////////////////////////
  1600. #define INTERNAL_CATCH_MSG( macroName, messageType, resultDisposition, ... ) \
  1601. do { \
  1602. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::StringRef(), resultDisposition ); \
  1603. catchAssertionHandler.handleMessage( messageType, ( Catch::MessageStream() << __VA_ARGS__ + ::Catch::StreamEndStop() ).m_stream.str() ); \
  1604. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1605. } while( false )
  1606. ///////////////////////////////////////////////////////////////////////////////
  1607. #define INTERNAL_CATCH_CAPTURE( varName, macroName, ... ) \
  1608. auto varName = Catch::Capturer( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info, #__VA_ARGS__ ); \
  1609. varName.captureValues( 0, __VA_ARGS__ )
  1610. ///////////////////////////////////////////////////////////////////////////////
  1611. #define INTERNAL_CATCH_INFO( macroName, log ) \
  1612. Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage )( Catch::MessageBuilder( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log );
  1613. ///////////////////////////////////////////////////////////////////////////////
  1614. // Although this is matcher-based, it can be used with just a string
  1615. #define INTERNAL_CATCH_THROWS_STR_MATCHES( macroName, resultDisposition, matcher, ... ) \
  1616. do { \
  1617. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  1618. if( catchAssertionHandler.allowThrows() ) \
  1619. try { \
  1620. static_cast<void>(__VA_ARGS__); \
  1621. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  1622. } \
  1623. catch( ... ) { \
  1624. Catch::handleExceptionMatchExpr( catchAssertionHandler, matcher, #matcher##_catch_sr ); \
  1625. } \
  1626. else \
  1627. catchAssertionHandler.handleThrowingCallSkipped(); \
  1628. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  1629. } while( false )
  1630. #endif // CATCH_CONFIG_DISABLE
  1631. // end catch_capture.hpp
  1632. // start catch_section.h
  1633. // start catch_section_info.h
  1634. // start catch_totals.h
  1635. #include <cstddef>
  1636. namespace Catch {
  1637. struct Counts {
  1638. Counts operator - ( Counts const& other ) const;
  1639. Counts& operator += ( Counts const& other );
  1640. std::size_t total() const;
  1641. bool allPassed() const;
  1642. bool allOk() const;
  1643. std::size_t passed = 0;
  1644. std::size_t failed = 0;
  1645. std::size_t failedButOk = 0;
  1646. };
  1647. struct Totals {
  1648. Totals operator - ( Totals const& other ) const;
  1649. Totals& operator += ( Totals const& other );
  1650. Totals delta( Totals const& prevTotals ) const;
  1651. int error = 0;
  1652. Counts assertions;
  1653. Counts testCases;
  1654. };
  1655. }
  1656. // end catch_totals.h
  1657. #include <string>
  1658. namespace Catch {
  1659. struct SectionInfo {
  1660. SectionInfo
  1661. ( SourceLineInfo const& _lineInfo,
  1662. std::string const& _name );
  1663. // Deprecated
  1664. SectionInfo
  1665. ( SourceLineInfo const& _lineInfo,
  1666. std::string const& _name,
  1667. std::string const& ) : SectionInfo( _lineInfo, _name ) {}
  1668. std::string name;
  1669. std::string description; // !Deprecated: this will always be empty
  1670. SourceLineInfo lineInfo;
  1671. };
  1672. struct SectionEndInfo {
  1673. SectionInfo sectionInfo;
  1674. Counts prevAssertions;
  1675. double durationInSeconds;
  1676. };
  1677. } // end namespace Catch
  1678. // end catch_section_info.h
  1679. // start catch_timer.h
  1680. #include <cstdint>
  1681. namespace Catch {
  1682. auto getCurrentNanosecondsSinceEpoch() -> uint64_t;
  1683. auto getEstimatedClockResolution() -> uint64_t;
  1684. class Timer {
  1685. uint64_t m_nanoseconds = 0;
  1686. public:
  1687. void start();
  1688. auto getElapsedNanoseconds() const -> uint64_t;
  1689. auto getElapsedMicroseconds() const -> uint64_t;
  1690. auto getElapsedMilliseconds() const -> unsigned int;
  1691. auto getElapsedSeconds() const -> double;
  1692. };
  1693. } // namespace Catch
  1694. // end catch_timer.h
  1695. #include <string>
  1696. namespace Catch {
  1697. class Section : NonCopyable {
  1698. public:
  1699. Section( SectionInfo const& info );
  1700. ~Section();
  1701. // This indicates whether the section should be executed or not
  1702. explicit operator bool() const;
  1703. private:
  1704. SectionInfo m_info;
  1705. std::string m_name;
  1706. Counts m_assertions;
  1707. bool m_sectionIncluded;
  1708. Timer m_timer;
  1709. };
  1710. } // end namespace Catch
  1711. #define INTERNAL_CATCH_SECTION( ... ) \
  1712. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  1713. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) \
  1714. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  1715. #define INTERNAL_CATCH_DYNAMIC_SECTION( ... ) \
  1716. CATCH_INTERNAL_SUPPRESS_UNUSED_WARNINGS \
  1717. if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, (Catch::ReusableStringStream() << __VA_ARGS__).str() ) ) \
  1718. CATCH_INTERNAL_UNSUPPRESS_UNUSED_WARNINGS
  1719. // end catch_section.h
  1720. // start catch_benchmark.h
  1721. #include <cstdint>
  1722. #include <string>
  1723. namespace Catch {
  1724. class BenchmarkLooper {
  1725. std::string m_name;
  1726. std::size_t m_count = 0;
  1727. std::size_t m_iterationsToRun = 1;
  1728. uint64_t m_resolution;
  1729. Timer m_timer;
  1730. static auto getResolution() -> uint64_t;
  1731. public:
  1732. // Keep most of this inline as it's on the code path that is being timed
  1733. BenchmarkLooper( StringRef name )
  1734. : m_name( name ),
  1735. m_resolution( getResolution() )
  1736. {
  1737. reportStart();
  1738. m_timer.start();
  1739. }
  1740. explicit operator bool() {
  1741. if( m_count < m_iterationsToRun )
  1742. return true;
  1743. return needsMoreIterations();
  1744. }
  1745. void increment() {
  1746. ++m_count;
  1747. }
  1748. void reportStart();
  1749. auto needsMoreIterations() -> bool;
  1750. };
  1751. } // end namespace Catch
  1752. #define BENCHMARK( name ) \
  1753. for( Catch::BenchmarkLooper looper( name ); looper; looper.increment() )
  1754. // end catch_benchmark.h
  1755. // start catch_interfaces_exception.h
  1756. // start catch_interfaces_registry_hub.h
  1757. #include <string>
  1758. #include <memory>
  1759. namespace Catch {
  1760. class TestCase;
  1761. struct ITestCaseRegistry;
  1762. struct IExceptionTranslatorRegistry;
  1763. struct IExceptionTranslator;
  1764. struct IReporterRegistry;
  1765. struct IReporterFactory;
  1766. struct ITagAliasRegistry;
  1767. class StartupExceptionRegistry;
  1768. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  1769. struct IRegistryHub {
  1770. virtual ~IRegistryHub();
  1771. virtual IReporterRegistry const& getReporterRegistry() const = 0;
  1772. virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0;
  1773. virtual ITagAliasRegistry const& getTagAliasRegistry() const = 0;
  1774. virtual IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const = 0;
  1775. virtual StartupExceptionRegistry const& getStartupExceptionRegistry() const = 0;
  1776. };
  1777. struct IMutableRegistryHub {
  1778. virtual ~IMutableRegistryHub();
  1779. virtual void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) = 0;
  1780. virtual void registerListener( IReporterFactoryPtr const& factory ) = 0;
  1781. virtual void registerTest( TestCase const& testInfo ) = 0;
  1782. virtual void registerTranslator( const IExceptionTranslator* translator ) = 0;
  1783. virtual void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) = 0;
  1784. virtual void registerStartupException() noexcept = 0;
  1785. };
  1786. IRegistryHub const& getRegistryHub();
  1787. IMutableRegistryHub& getMutableRegistryHub();
  1788. void cleanUp();
  1789. std::string translateActiveException();
  1790. }
  1791. // end catch_interfaces_registry_hub.h
  1792. #if defined(CATCH_CONFIG_DISABLE)
  1793. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( translatorName, signature) \
  1794. static std::string translatorName( signature )
  1795. #endif
  1796. #include <exception>
  1797. #include <string>
  1798. #include <vector>
  1799. namespace Catch {
  1800. using exceptionTranslateFunction = std::string(*)();
  1801. struct IExceptionTranslator;
  1802. using ExceptionTranslators = std::vector<std::unique_ptr<IExceptionTranslator const>>;
  1803. struct IExceptionTranslator {
  1804. virtual ~IExceptionTranslator();
  1805. virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0;
  1806. };
  1807. struct IExceptionTranslatorRegistry {
  1808. virtual ~IExceptionTranslatorRegistry();
  1809. virtual std::string translateActiveException() const = 0;
  1810. };
  1811. class ExceptionTranslatorRegistrar {
  1812. template<typename T>
  1813. class ExceptionTranslator : public IExceptionTranslator {
  1814. public:
  1815. ExceptionTranslator( std::string(*translateFunction)( T& ) )
  1816. : m_translateFunction( translateFunction )
  1817. {}
  1818. std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const override {
  1819. try {
  1820. if( it == itEnd )
  1821. std::rethrow_exception(std::current_exception());
  1822. else
  1823. return (*it)->translate( it+1, itEnd );
  1824. }
  1825. catch( T& ex ) {
  1826. return m_translateFunction( ex );
  1827. }
  1828. }
  1829. protected:
  1830. std::string(*m_translateFunction)( T& );
  1831. };
  1832. public:
  1833. template<typename T>
  1834. ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) {
  1835. getMutableRegistryHub().registerTranslator
  1836. ( new ExceptionTranslator<T>( translateFunction ) );
  1837. }
  1838. };
  1839. }
  1840. ///////////////////////////////////////////////////////////////////////////////
  1841. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \
  1842. static std::string translatorName( signature ); \
  1843. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  1844. namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); } \
  1845. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS \
  1846. static std::string translatorName( signature )
  1847. #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  1848. // end catch_interfaces_exception.h
  1849. // start catch_approx.h
  1850. #include <type_traits>
  1851. namespace Catch {
  1852. namespace Detail {
  1853. class Approx {
  1854. private:
  1855. bool equalityComparisonImpl(double other) const;
  1856. // Validates the new margin (margin >= 0)
  1857. // out-of-line to avoid including stdexcept in the header
  1858. void setMargin(double margin);
  1859. // Validates the new epsilon (0 < epsilon < 1)
  1860. // out-of-line to avoid including stdexcept in the header
  1861. void setEpsilon(double epsilon);
  1862. public:
  1863. explicit Approx ( double value );
  1864. static Approx custom();
  1865. Approx operator-() const;
  1866. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1867. Approx operator()( T const& value ) {
  1868. Approx approx( static_cast<double>(value) );
  1869. approx.m_epsilon = m_epsilon;
  1870. approx.m_margin = m_margin;
  1871. approx.m_scale = m_scale;
  1872. return approx;
  1873. }
  1874. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1875. explicit Approx( T const& value ): Approx(static_cast<double>(value))
  1876. {}
  1877. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1878. friend bool operator == ( const T& lhs, Approx const& rhs ) {
  1879. auto lhs_v = static_cast<double>(lhs);
  1880. return rhs.equalityComparisonImpl(lhs_v);
  1881. }
  1882. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1883. friend bool operator == ( Approx const& lhs, const T& rhs ) {
  1884. return operator==( rhs, lhs );
  1885. }
  1886. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1887. friend bool operator != ( T const& lhs, Approx const& rhs ) {
  1888. return !operator==( lhs, rhs );
  1889. }
  1890. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1891. friend bool operator != ( Approx const& lhs, T const& rhs ) {
  1892. return !operator==( rhs, lhs );
  1893. }
  1894. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1895. friend bool operator <= ( T const& lhs, Approx const& rhs ) {
  1896. return static_cast<double>(lhs) < rhs.m_value || lhs == rhs;
  1897. }
  1898. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1899. friend bool operator <= ( Approx const& lhs, T const& rhs ) {
  1900. return lhs.m_value < static_cast<double>(rhs) || lhs == rhs;
  1901. }
  1902. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1903. friend bool operator >= ( T const& lhs, Approx const& rhs ) {
  1904. return static_cast<double>(lhs) > rhs.m_value || lhs == rhs;
  1905. }
  1906. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1907. friend bool operator >= ( Approx const& lhs, T const& rhs ) {
  1908. return lhs.m_value > static_cast<double>(rhs) || lhs == rhs;
  1909. }
  1910. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1911. Approx& epsilon( T const& newEpsilon ) {
  1912. double epsilonAsDouble = static_cast<double>(newEpsilon);
  1913. setEpsilon(epsilonAsDouble);
  1914. return *this;
  1915. }
  1916. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1917. Approx& margin( T const& newMargin ) {
  1918. double marginAsDouble = static_cast<double>(newMargin);
  1919. setMargin(marginAsDouble);
  1920. return *this;
  1921. }
  1922. template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
  1923. Approx& scale( T const& newScale ) {
  1924. m_scale = static_cast<double>(newScale);
  1925. return *this;
  1926. }
  1927. std::string toString() const;
  1928. private:
  1929. double m_epsilon;
  1930. double m_margin;
  1931. double m_scale;
  1932. double m_value;
  1933. };
  1934. } // end namespace Detail
  1935. namespace literals {
  1936. Detail::Approx operator "" _a(long double val);
  1937. Detail::Approx operator "" _a(unsigned long long val);
  1938. } // end namespace literals
  1939. template<>
  1940. struct StringMaker<Catch::Detail::Approx> {
  1941. static std::string convert(Catch::Detail::Approx const& value);
  1942. };
  1943. } // end namespace Catch
  1944. // end catch_approx.h
  1945. // start catch_string_manip.h
  1946. #include <string>
  1947. #include <iosfwd>
  1948. namespace Catch {
  1949. bool startsWith( std::string const& s, std::string const& prefix );
  1950. bool startsWith( std::string const& s, char prefix );
  1951. bool endsWith( std::string const& s, std::string const& suffix );
  1952. bool endsWith( std::string const& s, char suffix );
  1953. bool contains( std::string const& s, std::string const& infix );
  1954. void toLowerInPlace( std::string& s );
  1955. std::string toLower( std::string const& s );
  1956. std::string trim( std::string const& str );
  1957. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis );
  1958. struct pluralise {
  1959. pluralise( std::size_t count, std::string const& label );
  1960. friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser );
  1961. std::size_t m_count;
  1962. std::string m_label;
  1963. };
  1964. }
  1965. // end catch_string_manip.h
  1966. #ifndef CATCH_CONFIG_DISABLE_MATCHERS
  1967. // start catch_capture_matchers.h
  1968. // start catch_matchers.h
  1969. #include <string>
  1970. #include <vector>
  1971. namespace Catch {
  1972. namespace Matchers {
  1973. namespace Impl {
  1974. template<typename ArgT> struct MatchAllOf;
  1975. template<typename ArgT> struct MatchAnyOf;
  1976. template<typename ArgT> struct MatchNotOf;
  1977. class MatcherUntypedBase {
  1978. public:
  1979. MatcherUntypedBase() = default;
  1980. MatcherUntypedBase ( MatcherUntypedBase const& ) = default;
  1981. MatcherUntypedBase& operator = ( MatcherUntypedBase const& ) = delete;
  1982. std::string toString() const;
  1983. protected:
  1984. virtual ~MatcherUntypedBase();
  1985. virtual std::string describe() const = 0;
  1986. mutable std::string m_cachedToString;
  1987. };
  1988. #ifdef __clang__
  1989. # pragma clang diagnostic push
  1990. # pragma clang diagnostic ignored "-Wnon-virtual-dtor"
  1991. #endif
  1992. template<typename ObjectT>
  1993. struct MatcherMethod {
  1994. virtual bool match( ObjectT const& arg ) const = 0;
  1995. };
  1996. template<typename PtrT>
  1997. struct MatcherMethod<PtrT*> {
  1998. virtual bool match( PtrT* arg ) const = 0;
  1999. };
  2000. #ifdef __clang__
  2001. # pragma clang diagnostic pop
  2002. #endif
  2003. template<typename T>
  2004. struct MatcherBase : MatcherUntypedBase, MatcherMethod<T> {
  2005. MatchAllOf<T> operator && ( MatcherBase const& other ) const;
  2006. MatchAnyOf<T> operator || ( MatcherBase const& other ) const;
  2007. MatchNotOf<T> operator ! () const;
  2008. };
  2009. template<typename ArgT>
  2010. struct MatchAllOf : MatcherBase<ArgT> {
  2011. bool match( ArgT const& arg ) const override {
  2012. for( auto matcher : m_matchers ) {
  2013. if (!matcher->match(arg))
  2014. return false;
  2015. }
  2016. return true;
  2017. }
  2018. std::string describe() const override {
  2019. std::string description;
  2020. description.reserve( 4 + m_matchers.size()*32 );
  2021. description += "( ";
  2022. bool first = true;
  2023. for( auto matcher : m_matchers ) {
  2024. if( first )
  2025. first = false;
  2026. else
  2027. description += " and ";
  2028. description += matcher->toString();
  2029. }
  2030. description += " )";
  2031. return description;
  2032. }
  2033. MatchAllOf<ArgT>& operator && ( MatcherBase<ArgT> const& other ) {
  2034. m_matchers.push_back( &other );
  2035. return *this;
  2036. }
  2037. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2038. };
  2039. template<typename ArgT>
  2040. struct MatchAnyOf : MatcherBase<ArgT> {
  2041. bool match( ArgT const& arg ) const override {
  2042. for( auto matcher : m_matchers ) {
  2043. if (matcher->match(arg))
  2044. return true;
  2045. }
  2046. return false;
  2047. }
  2048. std::string describe() const override {
  2049. std::string description;
  2050. description.reserve( 4 + m_matchers.size()*32 );
  2051. description += "( ";
  2052. bool first = true;
  2053. for( auto matcher : m_matchers ) {
  2054. if( first )
  2055. first = false;
  2056. else
  2057. description += " or ";
  2058. description += matcher->toString();
  2059. }
  2060. description += " )";
  2061. return description;
  2062. }
  2063. MatchAnyOf<ArgT>& operator || ( MatcherBase<ArgT> const& other ) {
  2064. m_matchers.push_back( &other );
  2065. return *this;
  2066. }
  2067. std::vector<MatcherBase<ArgT> const*> m_matchers;
  2068. };
  2069. template<typename ArgT>
  2070. struct MatchNotOf : MatcherBase<ArgT> {
  2071. MatchNotOf( MatcherBase<ArgT> const& underlyingMatcher ) : m_underlyingMatcher( underlyingMatcher ) {}
  2072. bool match( ArgT const& arg ) const override {
  2073. return !m_underlyingMatcher.match( arg );
  2074. }
  2075. std::string describe() const override {
  2076. return "not " + m_underlyingMatcher.toString();
  2077. }
  2078. MatcherBase<ArgT> const& m_underlyingMatcher;
  2079. };
  2080. template<typename T>
  2081. MatchAllOf<T> MatcherBase<T>::operator && ( MatcherBase const& other ) const {
  2082. return MatchAllOf<T>() && *this && other;
  2083. }
  2084. template<typename T>
  2085. MatchAnyOf<T> MatcherBase<T>::operator || ( MatcherBase const& other ) const {
  2086. return MatchAnyOf<T>() || *this || other;
  2087. }
  2088. template<typename T>
  2089. MatchNotOf<T> MatcherBase<T>::operator ! () const {
  2090. return MatchNotOf<T>( *this );
  2091. }
  2092. } // namespace Impl
  2093. } // namespace Matchers
  2094. using namespace Matchers;
  2095. using Matchers::Impl::MatcherBase;
  2096. } // namespace Catch
  2097. // end catch_matchers.h
  2098. // start catch_matchers_floating.h
  2099. #include <type_traits>
  2100. #include <cmath>
  2101. namespace Catch {
  2102. namespace Matchers {
  2103. namespace Floating {
  2104. enum class FloatingPointKind : uint8_t;
  2105. struct WithinAbsMatcher : MatcherBase<double> {
  2106. WithinAbsMatcher(double target, double margin);
  2107. bool match(double const& matchee) const override;
  2108. std::string describe() const override;
  2109. private:
  2110. double m_target;
  2111. double m_margin;
  2112. };
  2113. struct WithinUlpsMatcher : MatcherBase<double> {
  2114. WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType);
  2115. bool match(double const& matchee) const override;
  2116. std::string describe() const override;
  2117. private:
  2118. double m_target;
  2119. int m_ulps;
  2120. FloatingPointKind m_type;
  2121. };
  2122. } // namespace Floating
  2123. // The following functions create the actual matcher objects.
  2124. // This allows the types to be inferred
  2125. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff);
  2126. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff);
  2127. Floating::WithinAbsMatcher WithinAbs(double target, double margin);
  2128. } // namespace Matchers
  2129. } // namespace Catch
  2130. // end catch_matchers_floating.h
  2131. // start catch_matchers_generic.hpp
  2132. #include <functional>
  2133. #include <string>
  2134. namespace Catch {
  2135. namespace Matchers {
  2136. namespace Generic {
  2137. namespace Detail {
  2138. std::string finalizeDescription(const std::string& desc);
  2139. }
  2140. template <typename T>
  2141. class PredicateMatcher : public MatcherBase<T> {
  2142. std::function<bool(T const&)> m_predicate;
  2143. std::string m_description;
  2144. public:
  2145. PredicateMatcher(std::function<bool(T const&)> const& elem, std::string const& descr)
  2146. :m_predicate(std::move(elem)),
  2147. m_description(Detail::finalizeDescription(descr))
  2148. {}
  2149. bool match( T const& item ) const override {
  2150. return m_predicate(item);
  2151. }
  2152. std::string describe() const override {
  2153. return m_description;
  2154. }
  2155. };
  2156. } // namespace Generic
  2157. // The following functions create the actual matcher objects.
  2158. // The user has to explicitly specify type to the function, because
  2159. // infering std::function<bool(T const&)> is hard (but possible) and
  2160. // requires a lot of TMP.
  2161. template<typename T>
  2162. Generic::PredicateMatcher<T> Predicate(std::function<bool(T const&)> const& predicate, std::string const& description = "") {
  2163. return Generic::PredicateMatcher<T>(predicate, description);
  2164. }
  2165. } // namespace Matchers
  2166. } // namespace Catch
  2167. // end catch_matchers_generic.hpp
  2168. // start catch_matchers_string.h
  2169. #include <string>
  2170. namespace Catch {
  2171. namespace Matchers {
  2172. namespace StdString {
  2173. struct CasedString
  2174. {
  2175. CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity );
  2176. std::string adjustString( std::string const& str ) const;
  2177. std::string caseSensitivitySuffix() const;
  2178. CaseSensitive::Choice m_caseSensitivity;
  2179. std::string m_str;
  2180. };
  2181. struct StringMatcherBase : MatcherBase<std::string> {
  2182. StringMatcherBase( std::string const& operation, CasedString const& comparator );
  2183. std::string describe() const override;
  2184. CasedString m_comparator;
  2185. std::string m_operation;
  2186. };
  2187. struct EqualsMatcher : StringMatcherBase {
  2188. EqualsMatcher( CasedString const& comparator );
  2189. bool match( std::string const& source ) const override;
  2190. };
  2191. struct ContainsMatcher : StringMatcherBase {
  2192. ContainsMatcher( CasedString const& comparator );
  2193. bool match( std::string const& source ) const override;
  2194. };
  2195. struct StartsWithMatcher : StringMatcherBase {
  2196. StartsWithMatcher( CasedString const& comparator );
  2197. bool match( std::string const& source ) const override;
  2198. };
  2199. struct EndsWithMatcher : StringMatcherBase {
  2200. EndsWithMatcher( CasedString const& comparator );
  2201. bool match( std::string const& source ) const override;
  2202. };
  2203. struct RegexMatcher : MatcherBase<std::string> {
  2204. RegexMatcher( std::string regex, CaseSensitive::Choice caseSensitivity );
  2205. bool match( std::string const& matchee ) const override;
  2206. std::string describe() const override;
  2207. private:
  2208. std::string m_regex;
  2209. CaseSensitive::Choice m_caseSensitivity;
  2210. };
  2211. } // namespace StdString
  2212. // The following functions create the actual matcher objects.
  2213. // This allows the types to be inferred
  2214. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2215. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2216. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2217. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2218. StdString::RegexMatcher Matches( std::string const& regex, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes );
  2219. } // namespace Matchers
  2220. } // namespace Catch
  2221. // end catch_matchers_string.h
  2222. // start catch_matchers_vector.h
  2223. #include <algorithm>
  2224. namespace Catch {
  2225. namespace Matchers {
  2226. namespace Vector {
  2227. namespace Detail {
  2228. template <typename InputIterator, typename T>
  2229. size_t count(InputIterator first, InputIterator last, T const& item) {
  2230. size_t cnt = 0;
  2231. for (; first != last; ++first) {
  2232. if (*first == item) {
  2233. ++cnt;
  2234. }
  2235. }
  2236. return cnt;
  2237. }
  2238. template <typename InputIterator, typename T>
  2239. bool contains(InputIterator first, InputIterator last, T const& item) {
  2240. for (; first != last; ++first) {
  2241. if (*first == item) {
  2242. return true;
  2243. }
  2244. }
  2245. return false;
  2246. }
  2247. }
  2248. template<typename T>
  2249. struct ContainsElementMatcher : MatcherBase<std::vector<T>> {
  2250. ContainsElementMatcher(T const &comparator) : m_comparator( comparator) {}
  2251. bool match(std::vector<T> const &v) const override {
  2252. for (auto const& el : v) {
  2253. if (el == m_comparator) {
  2254. return true;
  2255. }
  2256. }
  2257. return false;
  2258. }
  2259. std::string describe() const override {
  2260. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2261. }
  2262. T const& m_comparator;
  2263. };
  2264. template<typename T>
  2265. struct ContainsMatcher : MatcherBase<std::vector<T>> {
  2266. ContainsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2267. bool match(std::vector<T> const &v) const override {
  2268. // !TBD: see note in EqualsMatcher
  2269. if (m_comparator.size() > v.size())
  2270. return false;
  2271. for (auto const& comparator : m_comparator) {
  2272. auto present = false;
  2273. for (const auto& el : v) {
  2274. if (el == comparator) {
  2275. present = true;
  2276. break;
  2277. }
  2278. }
  2279. if (!present) {
  2280. return false;
  2281. }
  2282. }
  2283. return true;
  2284. }
  2285. std::string describe() const override {
  2286. return "Contains: " + ::Catch::Detail::stringify( m_comparator );
  2287. }
  2288. std::vector<T> const& m_comparator;
  2289. };
  2290. template<typename T>
  2291. struct EqualsMatcher : MatcherBase<std::vector<T>> {
  2292. EqualsMatcher(std::vector<T> const &comparator) : m_comparator( comparator ) {}
  2293. bool match(std::vector<T> const &v) const override {
  2294. // !TBD: This currently works if all elements can be compared using !=
  2295. // - a more general approach would be via a compare template that defaults
  2296. // to using !=. but could be specialised for, e.g. std::vector<T> etc
  2297. // - then just call that directly
  2298. if (m_comparator.size() != v.size())
  2299. return false;
  2300. for (std::size_t i = 0; i < v.size(); ++i)
  2301. if (m_comparator[i] != v[i])
  2302. return false;
  2303. return true;
  2304. }
  2305. std::string describe() const override {
  2306. return "Equals: " + ::Catch::Detail::stringify( m_comparator );
  2307. }
  2308. std::vector<T> const& m_comparator;
  2309. };
  2310. template<typename T>
  2311. struct UnorderedEqualsMatcher : MatcherBase<std::vector<T>> {
  2312. UnorderedEqualsMatcher(std::vector<T> const& target) : m_target(target) {}
  2313. bool match(std::vector<T> const& vec) const override {
  2314. // Note: This is a reimplementation of std::is_permutation,
  2315. // because I don't want to include <algorithm> inside the common path
  2316. if (m_target.size() != vec.size()) {
  2317. return false;
  2318. }
  2319. auto lfirst = m_target.begin(), llast = m_target.end();
  2320. auto rfirst = vec.begin(), rlast = vec.end();
  2321. // Cut common prefix to optimize checking of permuted parts
  2322. while (lfirst != llast && *lfirst == *rfirst) {
  2323. ++lfirst; ++rfirst;
  2324. }
  2325. if (lfirst == llast) {
  2326. return true;
  2327. }
  2328. for (auto mid = lfirst; mid != llast; ++mid) {
  2329. // Skip already counted items
  2330. if (Detail::contains(lfirst, mid, *mid)) {
  2331. continue;
  2332. }
  2333. size_t num_vec = Detail::count(rfirst, rlast, *mid);
  2334. if (num_vec == 0 || Detail::count(lfirst, llast, *mid) != num_vec) {
  2335. return false;
  2336. }
  2337. }
  2338. return true;
  2339. }
  2340. std::string describe() const override {
  2341. return "UnorderedEquals: " + ::Catch::Detail::stringify(m_target);
  2342. }
  2343. private:
  2344. std::vector<T> const& m_target;
  2345. };
  2346. } // namespace Vector
  2347. // The following functions create the actual matcher objects.
  2348. // This allows the types to be inferred
  2349. template<typename T>
  2350. Vector::ContainsMatcher<T> Contains( std::vector<T> const& comparator ) {
  2351. return Vector::ContainsMatcher<T>( comparator );
  2352. }
  2353. template<typename T>
  2354. Vector::ContainsElementMatcher<T> VectorContains( T const& comparator ) {
  2355. return Vector::ContainsElementMatcher<T>( comparator );
  2356. }
  2357. template<typename T>
  2358. Vector::EqualsMatcher<T> Equals( std::vector<T> const& comparator ) {
  2359. return Vector::EqualsMatcher<T>( comparator );
  2360. }
  2361. template<typename T>
  2362. Vector::UnorderedEqualsMatcher<T> UnorderedEquals(std::vector<T> const& target) {
  2363. return Vector::UnorderedEqualsMatcher<T>(target);
  2364. }
  2365. } // namespace Matchers
  2366. } // namespace Catch
  2367. // end catch_matchers_vector.h
  2368. namespace Catch {
  2369. template<typename ArgT, typename MatcherT>
  2370. class MatchExpr : public ITransientExpression {
  2371. ArgT const& m_arg;
  2372. MatcherT m_matcher;
  2373. StringRef m_matcherString;
  2374. public:
  2375. MatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString )
  2376. : ITransientExpression{ true, matcher.match( arg ) },
  2377. m_arg( arg ),
  2378. m_matcher( matcher ),
  2379. m_matcherString( matcherString )
  2380. {}
  2381. void streamReconstructedExpression( std::ostream &os ) const override {
  2382. auto matcherAsString = m_matcher.toString();
  2383. os << Catch::Detail::stringify( m_arg ) << ' ';
  2384. if( matcherAsString == Detail::unprintableString )
  2385. os << m_matcherString;
  2386. else
  2387. os << matcherAsString;
  2388. }
  2389. };
  2390. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  2391. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString );
  2392. template<typename ArgT, typename MatcherT>
  2393. auto makeMatchExpr( ArgT const& arg, MatcherT const& matcher, StringRef const& matcherString ) -> MatchExpr<ArgT, MatcherT> {
  2394. return MatchExpr<ArgT, MatcherT>( arg, matcher, matcherString );
  2395. }
  2396. } // namespace Catch
  2397. ///////////////////////////////////////////////////////////////////////////////
  2398. #define INTERNAL_CHECK_THAT( macroName, matcher, resultDisposition, arg ) \
  2399. do { \
  2400. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(arg) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2401. INTERNAL_CATCH_TRY { \
  2402. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( arg, matcher, #matcher##_catch_sr ) ); \
  2403. } INTERNAL_CATCH_CATCH( catchAssertionHandler ) \
  2404. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2405. } while( false )
  2406. ///////////////////////////////////////////////////////////////////////////////
  2407. #define INTERNAL_CATCH_THROWS_MATCHES( macroName, exceptionType, resultDisposition, matcher, ... ) \
  2408. do { \
  2409. Catch::AssertionHandler catchAssertionHandler( macroName##_catch_sr, CATCH_INTERNAL_LINEINFO, CATCH_INTERNAL_STRINGIFY(__VA_ARGS__) ", " CATCH_INTERNAL_STRINGIFY(exceptionType) ", " CATCH_INTERNAL_STRINGIFY(matcher), resultDisposition ); \
  2410. if( catchAssertionHandler.allowThrows() ) \
  2411. try { \
  2412. static_cast<void>(__VA_ARGS__ ); \
  2413. catchAssertionHandler.handleUnexpectedExceptionNotThrown(); \
  2414. } \
  2415. catch( exceptionType const& ex ) { \
  2416. catchAssertionHandler.handleExpr( Catch::makeMatchExpr( ex, matcher, #matcher##_catch_sr ) ); \
  2417. } \
  2418. catch( ... ) { \
  2419. catchAssertionHandler.handleUnexpectedInflightException(); \
  2420. } \
  2421. else \
  2422. catchAssertionHandler.handleThrowingCallSkipped(); \
  2423. INTERNAL_CATCH_REACT( catchAssertionHandler ) \
  2424. } while( false )
  2425. // end catch_capture_matchers.h
  2426. #endif
  2427. // start catch_generators.hpp
  2428. // start catch_interfaces_generatortracker.h
  2429. #include <memory>
  2430. namespace Catch {
  2431. namespace Generators {
  2432. class GeneratorBase {
  2433. protected:
  2434. size_t m_size = 0;
  2435. public:
  2436. GeneratorBase( size_t size ) : m_size( size ) {}
  2437. virtual ~GeneratorBase();
  2438. auto size() const -> size_t { return m_size; }
  2439. };
  2440. using GeneratorBasePtr = std::unique_ptr<GeneratorBase>;
  2441. } // namespace Generators
  2442. struct IGeneratorTracker {
  2443. virtual ~IGeneratorTracker();
  2444. virtual auto hasGenerator() const -> bool = 0;
  2445. virtual auto getGenerator() const -> Generators::GeneratorBasePtr const& = 0;
  2446. virtual void setGenerator( Generators::GeneratorBasePtr&& generator ) = 0;
  2447. virtual auto getIndex() const -> std::size_t = 0;
  2448. };
  2449. } // namespace Catch
  2450. // end catch_interfaces_generatortracker.h
  2451. // start catch_enforce.h
  2452. #include <stdexcept>
  2453. namespace Catch {
  2454. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  2455. template <typename Ex>
  2456. [[noreturn]]
  2457. void throw_exception(Ex const& e) {
  2458. throw e;
  2459. }
  2460. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  2461. [[noreturn]]
  2462. void throw_exception(std::exception const& e);
  2463. #endif
  2464. } // namespace Catch;
  2465. #define CATCH_PREPARE_EXCEPTION( type, msg ) \
  2466. type( ( Catch::ReusableStringStream() << msg ).str() )
  2467. #define CATCH_INTERNAL_ERROR( msg ) \
  2468. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::logic_error, CATCH_INTERNAL_LINEINFO << ": Internal Catch error: " << msg))
  2469. #define CATCH_ERROR( msg ) \
  2470. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::domain_error, msg ))
  2471. #define CATCH_RUNTIME_ERROR( msg ) \
  2472. Catch::throw_exception(CATCH_PREPARE_EXCEPTION( std::runtime_error, msg ))
  2473. #define CATCH_ENFORCE( condition, msg ) \
  2474. do{ if( !(condition) ) CATCH_ERROR( msg ); } while(false)
  2475. // end catch_enforce.h
  2476. #include <memory>
  2477. #include <vector>
  2478. #include <cassert>
  2479. #include <utility>
  2480. namespace Catch {
  2481. namespace Generators {
  2482. // !TBD move this into its own location?
  2483. namespace pf{
  2484. template<typename T, typename... Args>
  2485. std::unique_ptr<T> make_unique( Args&&... args ) {
  2486. return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
  2487. }
  2488. }
  2489. template<typename T>
  2490. struct IGenerator {
  2491. virtual ~IGenerator() {}
  2492. virtual auto get( size_t index ) const -> T = 0;
  2493. };
  2494. template<typename T>
  2495. class SingleValueGenerator : public IGenerator<T> {
  2496. T m_value;
  2497. public:
  2498. SingleValueGenerator( T const& value ) : m_value( value ) {}
  2499. auto get( size_t ) const -> T override {
  2500. return m_value;
  2501. }
  2502. };
  2503. template<typename T>
  2504. class FixedValuesGenerator : public IGenerator<T> {
  2505. std::vector<T> m_values;
  2506. public:
  2507. FixedValuesGenerator( std::initializer_list<T> values ) : m_values( values ) {}
  2508. auto get( size_t index ) const -> T override {
  2509. return m_values[index];
  2510. }
  2511. };
  2512. template<typename T>
  2513. class RangeGenerator : public IGenerator<T> {
  2514. T const m_first;
  2515. T const m_last;
  2516. public:
  2517. RangeGenerator( T const& first, T const& last ) : m_first( first ), m_last( last ) {
  2518. assert( m_last > m_first );
  2519. }
  2520. auto get( size_t index ) const -> T override {
  2521. // ToDo:: introduce a safe cast to catch potential overflows
  2522. return static_cast<T>(m_first+index);
  2523. }
  2524. };
  2525. template<typename T>
  2526. struct NullGenerator : IGenerator<T> {
  2527. auto get( size_t ) const -> T override {
  2528. CATCH_INTERNAL_ERROR("A Null Generator is always empty");
  2529. }
  2530. };
  2531. template<typename T>
  2532. class Generator {
  2533. std::unique_ptr<IGenerator<T>> m_generator;
  2534. size_t m_size;
  2535. public:
  2536. Generator( size_t size, std::unique_ptr<IGenerator<T>> generator )
  2537. : m_generator( std::move( generator ) ),
  2538. m_size( size )
  2539. {}
  2540. auto size() const -> size_t { return m_size; }
  2541. auto operator[]( size_t index ) const -> T {
  2542. assert( index < m_size );
  2543. return m_generator->get( index );
  2544. }
  2545. };
  2546. std::vector<size_t> randomiseIndices( size_t selectionSize, size_t sourceSize );
  2547. template<typename T>
  2548. class GeneratorRandomiser : public IGenerator<T> {
  2549. Generator<T> m_baseGenerator;
  2550. std::vector<size_t> m_indices;
  2551. public:
  2552. GeneratorRandomiser( Generator<T>&& baseGenerator, size_t numberOfItems )
  2553. : m_baseGenerator( std::move( baseGenerator ) ),
  2554. m_indices( randomiseIndices( numberOfItems, m_baseGenerator.size() ) )
  2555. {}
  2556. auto get( size_t index ) const -> T override {
  2557. return m_baseGenerator[m_indices[index]];
  2558. }
  2559. };
  2560. template<typename T>
  2561. struct RequiresASpecialisationFor;
  2562. template<typename T>
  2563. auto all() -> Generator<T> { return RequiresASpecialisationFor<T>(); }
  2564. template<>
  2565. auto all<int>() -> Generator<int>;
  2566. template<typename T>
  2567. auto range( T const& first, T const& last ) -> Generator<T> {
  2568. return Generator<T>( (last-first), pf::make_unique<RangeGenerator<T>>( first, last ) );
  2569. }
  2570. template<typename T>
  2571. auto random( T const& first, T const& last ) -> Generator<T> {
  2572. auto gen = range( first, last );
  2573. auto size = gen.size();
  2574. return Generator<T>( size, pf::make_unique<GeneratorRandomiser<T>>( std::move( gen ), size ) );
  2575. }
  2576. template<typename T>
  2577. auto random( size_t size ) -> Generator<T> {
  2578. return Generator<T>( size, pf::make_unique<GeneratorRandomiser<T>>( all<T>(), size ) );
  2579. }
  2580. template<typename T>
  2581. auto values( std::initializer_list<T> values ) -> Generator<T> {
  2582. return Generator<T>( values.size(), pf::make_unique<FixedValuesGenerator<T>>( values ) );
  2583. }
  2584. template<typename T>
  2585. auto value( T const& val ) -> Generator<T> {
  2586. return Generator<T>( 1, pf::make_unique<SingleValueGenerator<T>>( val ) );
  2587. }
  2588. template<typename T>
  2589. auto as() -> Generator<T> {
  2590. return Generator<T>( 0, pf::make_unique<NullGenerator<T>>() );
  2591. }
  2592. template<typename... Ts>
  2593. auto table( std::initializer_list<std::tuple<Ts...>>&& tuples ) -> Generator<std::tuple<Ts...>> {
  2594. return values<std::tuple<Ts...>>( std::forward<std::initializer_list<std::tuple<Ts...>>>( tuples ) );
  2595. }
  2596. template<typename T>
  2597. struct Generators : GeneratorBase {
  2598. std::vector<Generator<T>> m_generators;
  2599. using type = T;
  2600. Generators() : GeneratorBase( 0 ) {}
  2601. void populate( T&& val ) {
  2602. m_size += 1;
  2603. m_generators.emplace_back( value( std::move( val ) ) );
  2604. }
  2605. template<typename U>
  2606. void populate( U&& val ) {
  2607. populate( T( std::move( val ) ) );
  2608. }
  2609. void populate( Generator<T>&& generator ) {
  2610. m_size += generator.size();
  2611. m_generators.emplace_back( std::move( generator ) );
  2612. }
  2613. template<typename U, typename... Gs>
  2614. void populate( U&& valueOrGenerator, Gs... moreGenerators ) {
  2615. populate( std::forward<U>( valueOrGenerator ) );
  2616. populate( std::forward<Gs>( moreGenerators )... );
  2617. }
  2618. auto operator[]( size_t index ) const -> T {
  2619. size_t sizes = 0;
  2620. for( auto const& gen : m_generators ) {
  2621. auto localIndex = index-sizes;
  2622. sizes += gen.size();
  2623. if( index < sizes )
  2624. return gen[localIndex];
  2625. }
  2626. CATCH_INTERNAL_ERROR("Index '" << index << "' is out of range (" << sizes << ')');
  2627. }
  2628. };
  2629. template<typename T, typename... Gs>
  2630. auto makeGenerators( Generator<T>&& generator, Gs... moreGenerators ) -> Generators<T> {
  2631. Generators<T> generators;
  2632. generators.m_generators.reserve( 1+sizeof...(Gs) );
  2633. generators.populate( std::move( generator ), std::forward<Gs>( moreGenerators )... );
  2634. return generators;
  2635. }
  2636. template<typename T>
  2637. auto makeGenerators( Generator<T>&& generator ) -> Generators<T> {
  2638. Generators<T> generators;
  2639. generators.populate( std::move( generator ) );
  2640. return generators;
  2641. }
  2642. template<typename T, typename... Gs>
  2643. auto makeGenerators( T&& val, Gs... moreGenerators ) -> Generators<T> {
  2644. return makeGenerators( value( std::forward<T>( val ) ), std::forward<Gs>( moreGenerators )... );
  2645. }
  2646. template<typename T, typename U, typename... Gs>
  2647. auto makeGenerators( U&& val, Gs... moreGenerators ) -> Generators<T> {
  2648. return makeGenerators( value( T( std::forward<U>( val ) ) ), std::forward<Gs>( moreGenerators )... );
  2649. }
  2650. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker&;
  2651. template<typename L>
  2652. // Note: The type after -> is weird, because VS2015 cannot parse
  2653. // the expression used in the typedef inside, when it is in
  2654. // return type. Yeah, ¯\_(ツ)_/¯
  2655. auto generate( SourceLineInfo const& lineInfo, L const& generatorExpression ) -> decltype(std::declval<decltype(generatorExpression())>()[0]) {
  2656. using UnderlyingType = typename decltype(generatorExpression())::type;
  2657. IGeneratorTracker& tracker = acquireGeneratorTracker( lineInfo );
  2658. if( !tracker.hasGenerator() )
  2659. tracker.setGenerator( pf::make_unique<Generators<UnderlyingType>>( generatorExpression() ) );
  2660. auto const& generator = static_cast<Generators<UnderlyingType> const&>( *tracker.getGenerator() );
  2661. return generator[tracker.getIndex()];
  2662. }
  2663. } // namespace Generators
  2664. } // namespace Catch
  2665. #define GENERATE( ... ) \
  2666. Catch::Generators::generate( CATCH_INTERNAL_LINEINFO, []{ using namespace Catch::Generators; return makeGenerators( __VA_ARGS__ ); } )
  2667. // end catch_generators.hpp
  2668. // These files are included here so the single_include script doesn't put them
  2669. // in the conditionally compiled sections
  2670. // start catch_test_case_info.h
  2671. #include <string>
  2672. #include <vector>
  2673. #include <memory>
  2674. #ifdef __clang__
  2675. #pragma clang diagnostic push
  2676. #pragma clang diagnostic ignored "-Wpadded"
  2677. #endif
  2678. namespace Catch {
  2679. struct ITestInvoker;
  2680. struct TestCaseInfo {
  2681. enum SpecialProperties{
  2682. None = 0,
  2683. IsHidden = 1 << 1,
  2684. ShouldFail = 1 << 2,
  2685. MayFail = 1 << 3,
  2686. Throws = 1 << 4,
  2687. NonPortable = 1 << 5,
  2688. Benchmark = 1 << 6
  2689. };
  2690. TestCaseInfo( std::string const& _name,
  2691. std::string const& _className,
  2692. std::string const& _description,
  2693. std::vector<std::string> const& _tags,
  2694. SourceLineInfo const& _lineInfo );
  2695. friend void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags );
  2696. bool isHidden() const;
  2697. bool throws() const;
  2698. bool okToFail() const;
  2699. bool expectedToFail() const;
  2700. std::string tagsAsString() const;
  2701. std::string name;
  2702. std::string className;
  2703. std::string description;
  2704. std::vector<std::string> tags;
  2705. std::vector<std::string> lcaseTags;
  2706. SourceLineInfo lineInfo;
  2707. SpecialProperties properties;
  2708. };
  2709. class TestCase : public TestCaseInfo {
  2710. public:
  2711. TestCase( ITestInvoker* testCase, TestCaseInfo&& info );
  2712. TestCase withName( std::string const& _newName ) const;
  2713. void invoke() const;
  2714. TestCaseInfo const& getTestCaseInfo() const;
  2715. bool operator == ( TestCase const& other ) const;
  2716. bool operator < ( TestCase const& other ) const;
  2717. private:
  2718. std::shared_ptr<ITestInvoker> test;
  2719. };
  2720. TestCase makeTestCase( ITestInvoker* testCase,
  2721. std::string const& className,
  2722. NameAndTags const& nameAndTags,
  2723. SourceLineInfo const& lineInfo );
  2724. }
  2725. #ifdef __clang__
  2726. #pragma clang diagnostic pop
  2727. #endif
  2728. // end catch_test_case_info.h
  2729. // start catch_interfaces_runner.h
  2730. namespace Catch {
  2731. struct IRunner {
  2732. virtual ~IRunner();
  2733. virtual bool aborting() const = 0;
  2734. };
  2735. }
  2736. // end catch_interfaces_runner.h
  2737. #ifdef __OBJC__
  2738. // start catch_objc.hpp
  2739. #import <objc/runtime.h>
  2740. #include <string>
  2741. // NB. Any general catch headers included here must be included
  2742. // in catch.hpp first to make sure they are included by the single
  2743. // header for non obj-usage
  2744. ///////////////////////////////////////////////////////////////////////////////
  2745. // This protocol is really only here for (self) documenting purposes, since
  2746. // all its methods are optional.
  2747. @protocol OcFixture
  2748. @optional
  2749. -(void) setUp;
  2750. -(void) tearDown;
  2751. @end
  2752. namespace Catch {
  2753. class OcMethod : public ITestInvoker {
  2754. public:
  2755. OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {}
  2756. virtual void invoke() const {
  2757. id obj = [[m_cls alloc] init];
  2758. performOptionalSelector( obj, @selector(setUp) );
  2759. performOptionalSelector( obj, m_sel );
  2760. performOptionalSelector( obj, @selector(tearDown) );
  2761. arcSafeRelease( obj );
  2762. }
  2763. private:
  2764. virtual ~OcMethod() {}
  2765. Class m_cls;
  2766. SEL m_sel;
  2767. };
  2768. namespace Detail{
  2769. inline std::string getAnnotation( Class cls,
  2770. std::string const& annotationName,
  2771. std::string const& testCaseName ) {
  2772. NSString* selStr = [[NSString alloc] initWithFormat:@"Catch_%s_%s", annotationName.c_str(), testCaseName.c_str()];
  2773. SEL sel = NSSelectorFromString( selStr );
  2774. arcSafeRelease( selStr );
  2775. id value = performOptionalSelector( cls, sel );
  2776. if( value )
  2777. return [(NSString*)value UTF8String];
  2778. return "";
  2779. }
  2780. }
  2781. inline std::size_t registerTestMethods() {
  2782. std::size_t noTestMethods = 0;
  2783. int noClasses = objc_getClassList( nullptr, 0 );
  2784. Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses);
  2785. objc_getClassList( classes, noClasses );
  2786. for( int c = 0; c < noClasses; c++ ) {
  2787. Class cls = classes[c];
  2788. {
  2789. u_int count;
  2790. Method* methods = class_copyMethodList( cls, &count );
  2791. for( u_int m = 0; m < count ; m++ ) {
  2792. SEL selector = method_getName(methods[m]);
  2793. std::string methodName = sel_getName(selector);
  2794. if( startsWith( methodName, "Catch_TestCase_" ) ) {
  2795. std::string testCaseName = methodName.substr( 15 );
  2796. std::string name = Detail::getAnnotation( cls, "Name", testCaseName );
  2797. std::string desc = Detail::getAnnotation( cls, "Description", testCaseName );
  2798. const char* className = class_getName( cls );
  2799. getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, NameAndTags( name.c_str(), desc.c_str() ), SourceLineInfo("",0) ) );
  2800. noTestMethods++;
  2801. }
  2802. }
  2803. free(methods);
  2804. }
  2805. }
  2806. return noTestMethods;
  2807. }
  2808. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  2809. namespace Matchers {
  2810. namespace Impl {
  2811. namespace NSStringMatchers {
  2812. struct StringHolder : MatcherBase<NSString*>{
  2813. StringHolder( NSString* substr ) : m_substr( [substr copy] ){}
  2814. StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){}
  2815. StringHolder() {
  2816. arcSafeRelease( m_substr );
  2817. }
  2818. bool match( NSString* arg ) const override {
  2819. return false;
  2820. }
  2821. NSString* CATCH_ARC_STRONG m_substr;
  2822. };
  2823. struct Equals : StringHolder {
  2824. Equals( NSString* substr ) : StringHolder( substr ){}
  2825. bool match( NSString* str ) const override {
  2826. return (str != nil || m_substr == nil ) &&
  2827. [str isEqualToString:m_substr];
  2828. }
  2829. std::string describe() const override {
  2830. return "equals string: " + Catch::Detail::stringify( m_substr );
  2831. }
  2832. };
  2833. struct Contains : StringHolder {
  2834. Contains( NSString* substr ) : StringHolder( substr ){}
  2835. bool match( NSString* str ) const {
  2836. return (str != nil || m_substr == nil ) &&
  2837. [str rangeOfString:m_substr].location != NSNotFound;
  2838. }
  2839. std::string describe() const override {
  2840. return "contains string: " + Catch::Detail::stringify( m_substr );
  2841. }
  2842. };
  2843. struct StartsWith : StringHolder {
  2844. StartsWith( NSString* substr ) : StringHolder( substr ){}
  2845. bool match( NSString* str ) const override {
  2846. return (str != nil || m_substr == nil ) &&
  2847. [str rangeOfString:m_substr].location == 0;
  2848. }
  2849. std::string describe() const override {
  2850. return "starts with: " + Catch::Detail::stringify( m_substr );
  2851. }
  2852. };
  2853. struct EndsWith : StringHolder {
  2854. EndsWith( NSString* substr ) : StringHolder( substr ){}
  2855. bool match( NSString* str ) const override {
  2856. return (str != nil || m_substr == nil ) &&
  2857. [str rangeOfString:m_substr].location == [str length] - [m_substr length];
  2858. }
  2859. std::string describe() const override {
  2860. return "ends with: " + Catch::Detail::stringify( m_substr );
  2861. }
  2862. };
  2863. } // namespace NSStringMatchers
  2864. } // namespace Impl
  2865. inline Impl::NSStringMatchers::Equals
  2866. Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); }
  2867. inline Impl::NSStringMatchers::Contains
  2868. Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); }
  2869. inline Impl::NSStringMatchers::StartsWith
  2870. StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); }
  2871. inline Impl::NSStringMatchers::EndsWith
  2872. EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); }
  2873. } // namespace Matchers
  2874. using namespace Matchers;
  2875. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  2876. } // namespace Catch
  2877. ///////////////////////////////////////////////////////////////////////////////
  2878. #define OC_MAKE_UNIQUE_NAME( root, uniqueSuffix ) root##uniqueSuffix
  2879. #define OC_TEST_CASE2( name, desc, uniqueSuffix ) \
  2880. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Name_test_, uniqueSuffix ) \
  2881. { \
  2882. return @ name; \
  2883. } \
  2884. +(NSString*) OC_MAKE_UNIQUE_NAME( Catch_Description_test_, uniqueSuffix ) \
  2885. { \
  2886. return @ desc; \
  2887. } \
  2888. -(void) OC_MAKE_UNIQUE_NAME( Catch_TestCase_test_, uniqueSuffix )
  2889. #define OC_TEST_CASE( name, desc ) OC_TEST_CASE2( name, desc, __LINE__ )
  2890. // end catch_objc.hpp
  2891. #endif
  2892. #ifdef CATCH_CONFIG_EXTERNAL_INTERFACES
  2893. // start catch_external_interfaces.h
  2894. // start catch_reporter_bases.hpp
  2895. // start catch_interfaces_reporter.h
  2896. // start catch_config.hpp
  2897. // start catch_test_spec_parser.h
  2898. #ifdef __clang__
  2899. #pragma clang diagnostic push
  2900. #pragma clang diagnostic ignored "-Wpadded"
  2901. #endif
  2902. // start catch_test_spec.h
  2903. #ifdef __clang__
  2904. #pragma clang diagnostic push
  2905. #pragma clang diagnostic ignored "-Wpadded"
  2906. #endif
  2907. // start catch_wildcard_pattern.h
  2908. namespace Catch
  2909. {
  2910. class WildcardPattern {
  2911. enum WildcardPosition {
  2912. NoWildcard = 0,
  2913. WildcardAtStart = 1,
  2914. WildcardAtEnd = 2,
  2915. WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd
  2916. };
  2917. public:
  2918. WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity );
  2919. virtual ~WildcardPattern() = default;
  2920. virtual bool matches( std::string const& str ) const;
  2921. private:
  2922. std::string adjustCase( std::string const& str ) const;
  2923. CaseSensitive::Choice m_caseSensitivity;
  2924. WildcardPosition m_wildcard = NoWildcard;
  2925. std::string m_pattern;
  2926. };
  2927. }
  2928. // end catch_wildcard_pattern.h
  2929. #include <string>
  2930. #include <vector>
  2931. #include <memory>
  2932. namespace Catch {
  2933. class TestSpec {
  2934. struct Pattern {
  2935. virtual ~Pattern();
  2936. virtual bool matches( TestCaseInfo const& testCase ) const = 0;
  2937. };
  2938. using PatternPtr = std::shared_ptr<Pattern>;
  2939. class NamePattern : public Pattern {
  2940. public:
  2941. NamePattern( std::string const& name );
  2942. virtual ~NamePattern();
  2943. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2944. private:
  2945. WildcardPattern m_wildcardPattern;
  2946. };
  2947. class TagPattern : public Pattern {
  2948. public:
  2949. TagPattern( std::string const& tag );
  2950. virtual ~TagPattern();
  2951. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2952. private:
  2953. std::string m_tag;
  2954. };
  2955. class ExcludedPattern : public Pattern {
  2956. public:
  2957. ExcludedPattern( PatternPtr const& underlyingPattern );
  2958. virtual ~ExcludedPattern();
  2959. virtual bool matches( TestCaseInfo const& testCase ) const override;
  2960. private:
  2961. PatternPtr m_underlyingPattern;
  2962. };
  2963. struct Filter {
  2964. std::vector<PatternPtr> m_patterns;
  2965. bool matches( TestCaseInfo const& testCase ) const;
  2966. };
  2967. public:
  2968. bool hasFilters() const;
  2969. bool matches( TestCaseInfo const& testCase ) const;
  2970. private:
  2971. std::vector<Filter> m_filters;
  2972. friend class TestSpecParser;
  2973. };
  2974. }
  2975. #ifdef __clang__
  2976. #pragma clang diagnostic pop
  2977. #endif
  2978. // end catch_test_spec.h
  2979. // start catch_interfaces_tag_alias_registry.h
  2980. #include <string>
  2981. namespace Catch {
  2982. struct TagAlias;
  2983. struct ITagAliasRegistry {
  2984. virtual ~ITagAliasRegistry();
  2985. // Nullptr if not present
  2986. virtual TagAlias const* find( std::string const& alias ) const = 0;
  2987. virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0;
  2988. static ITagAliasRegistry const& get();
  2989. };
  2990. } // end namespace Catch
  2991. // end catch_interfaces_tag_alias_registry.h
  2992. namespace Catch {
  2993. class TestSpecParser {
  2994. enum Mode{ None, Name, QuotedName, Tag, EscapedName };
  2995. Mode m_mode = None;
  2996. bool m_exclusion = false;
  2997. std::size_t m_start = std::string::npos, m_pos = 0;
  2998. std::string m_arg;
  2999. std::vector<std::size_t> m_escapeChars;
  3000. TestSpec::Filter m_currentFilter;
  3001. TestSpec m_testSpec;
  3002. ITagAliasRegistry const* m_tagAliases = nullptr;
  3003. public:
  3004. TestSpecParser( ITagAliasRegistry const& tagAliases );
  3005. TestSpecParser& parse( std::string const& arg );
  3006. TestSpec testSpec();
  3007. private:
  3008. void visitChar( char c );
  3009. void startNewMode( Mode mode, std::size_t start );
  3010. void escape();
  3011. std::string subString() const;
  3012. template<typename T>
  3013. void addPattern() {
  3014. std::string token = subString();
  3015. for( std::size_t i = 0; i < m_escapeChars.size(); ++i )
  3016. token = token.substr( 0, m_escapeChars[i]-m_start-i ) + token.substr( m_escapeChars[i]-m_start-i+1 );
  3017. m_escapeChars.clear();
  3018. if( startsWith( token, "exclude:" ) ) {
  3019. m_exclusion = true;
  3020. token = token.substr( 8 );
  3021. }
  3022. if( !token.empty() ) {
  3023. TestSpec::PatternPtr pattern = std::make_shared<T>( token );
  3024. if( m_exclusion )
  3025. pattern = std::make_shared<TestSpec::ExcludedPattern>( pattern );
  3026. m_currentFilter.m_patterns.push_back( pattern );
  3027. }
  3028. m_exclusion = false;
  3029. m_mode = None;
  3030. }
  3031. void addFilter();
  3032. };
  3033. TestSpec parseTestSpec( std::string const& arg );
  3034. } // namespace Catch
  3035. #ifdef __clang__
  3036. #pragma clang diagnostic pop
  3037. #endif
  3038. // end catch_test_spec_parser.h
  3039. // start catch_interfaces_config.h
  3040. #include <iosfwd>
  3041. #include <string>
  3042. #include <vector>
  3043. #include <memory>
  3044. namespace Catch {
  3045. enum class Verbosity {
  3046. Quiet = 0,
  3047. Normal,
  3048. High
  3049. };
  3050. struct WarnAbout { enum What {
  3051. Nothing = 0x00,
  3052. NoAssertions = 0x01,
  3053. NoTests = 0x02
  3054. }; };
  3055. struct ShowDurations { enum OrNot {
  3056. DefaultForReporter,
  3057. Always,
  3058. Never
  3059. }; };
  3060. struct RunTests { enum InWhatOrder {
  3061. InDeclarationOrder,
  3062. InLexicographicalOrder,
  3063. InRandomOrder
  3064. }; };
  3065. struct UseColour { enum YesOrNo {
  3066. Auto,
  3067. Yes,
  3068. No
  3069. }; };
  3070. struct WaitForKeypress { enum When {
  3071. Never,
  3072. BeforeStart = 1,
  3073. BeforeExit = 2,
  3074. BeforeStartAndExit = BeforeStart | BeforeExit
  3075. }; };
  3076. class TestSpec;
  3077. struct IConfig : NonCopyable {
  3078. virtual ~IConfig();
  3079. virtual bool allowThrows() const = 0;
  3080. virtual std::ostream& stream() const = 0;
  3081. virtual std::string name() const = 0;
  3082. virtual bool includeSuccessfulResults() const = 0;
  3083. virtual bool shouldDebugBreak() const = 0;
  3084. virtual bool warnAboutMissingAssertions() const = 0;
  3085. virtual bool warnAboutNoTests() const = 0;
  3086. virtual int abortAfter() const = 0;
  3087. virtual bool showInvisibles() const = 0;
  3088. virtual ShowDurations::OrNot showDurations() const = 0;
  3089. virtual TestSpec const& testSpec() const = 0;
  3090. virtual bool hasTestFilters() const = 0;
  3091. virtual RunTests::InWhatOrder runOrder() const = 0;
  3092. virtual unsigned int rngSeed() const = 0;
  3093. virtual int benchmarkResolutionMultiple() const = 0;
  3094. virtual UseColour::YesOrNo useColour() const = 0;
  3095. virtual std::vector<std::string> const& getSectionsToRun() const = 0;
  3096. virtual Verbosity verbosity() const = 0;
  3097. };
  3098. using IConfigPtr = std::shared_ptr<IConfig const>;
  3099. }
  3100. // end catch_interfaces_config.h
  3101. // Libstdc++ doesn't like incomplete classes for unique_ptr
  3102. #include <memory>
  3103. #include <vector>
  3104. #include <string>
  3105. #ifndef CATCH_CONFIG_CONSOLE_WIDTH
  3106. #define CATCH_CONFIG_CONSOLE_WIDTH 80
  3107. #endif
  3108. namespace Catch {
  3109. struct IStream;
  3110. struct ConfigData {
  3111. bool listTests = false;
  3112. bool listTags = false;
  3113. bool listReporters = false;
  3114. bool listTestNamesOnly = false;
  3115. bool showSuccessfulTests = false;
  3116. bool shouldDebugBreak = false;
  3117. bool noThrow = false;
  3118. bool showHelp = false;
  3119. bool showInvisibles = false;
  3120. bool filenamesAsTags = false;
  3121. bool libIdentify = false;
  3122. int abortAfter = -1;
  3123. unsigned int rngSeed = 0;
  3124. int benchmarkResolutionMultiple = 100;
  3125. Verbosity verbosity = Verbosity::Normal;
  3126. WarnAbout::What warnings = WarnAbout::Nothing;
  3127. ShowDurations::OrNot showDurations = ShowDurations::DefaultForReporter;
  3128. RunTests::InWhatOrder runOrder = RunTests::InDeclarationOrder;
  3129. UseColour::YesOrNo useColour = UseColour::Auto;
  3130. WaitForKeypress::When waitForKeypress = WaitForKeypress::Never;
  3131. std::string outputFilename;
  3132. std::string name;
  3133. std::string processName;
  3134. #ifndef CATCH_CONFIG_DEFAULT_REPORTER
  3135. #define CATCH_CONFIG_DEFAULT_REPORTER "console"
  3136. #endif
  3137. std::string reporterName = CATCH_CONFIG_DEFAULT_REPORTER;
  3138. #undef CATCH_CONFIG_DEFAULT_REPORTER
  3139. std::vector<std::string> testsOrTags;
  3140. std::vector<std::string> sectionsToRun;
  3141. };
  3142. class Config : public IConfig {
  3143. public:
  3144. Config() = default;
  3145. Config( ConfigData const& data );
  3146. virtual ~Config() = default;
  3147. std::string const& getFilename() const;
  3148. bool listTests() const;
  3149. bool listTestNamesOnly() const;
  3150. bool listTags() const;
  3151. bool listReporters() const;
  3152. std::string getProcessName() const;
  3153. std::string const& getReporterName() const;
  3154. std::vector<std::string> const& getTestsOrTags() const;
  3155. std::vector<std::string> const& getSectionsToRun() const override;
  3156. virtual TestSpec const& testSpec() const override;
  3157. bool hasTestFilters() const override;
  3158. bool showHelp() const;
  3159. // IConfig interface
  3160. bool allowThrows() const override;
  3161. std::ostream& stream() const override;
  3162. std::string name() const override;
  3163. bool includeSuccessfulResults() const override;
  3164. bool warnAboutMissingAssertions() const override;
  3165. bool warnAboutNoTests() const override;
  3166. ShowDurations::OrNot showDurations() const override;
  3167. RunTests::InWhatOrder runOrder() const override;
  3168. unsigned int rngSeed() const override;
  3169. int benchmarkResolutionMultiple() const override;
  3170. UseColour::YesOrNo useColour() const override;
  3171. bool shouldDebugBreak() const override;
  3172. int abortAfter() const override;
  3173. bool showInvisibles() const override;
  3174. Verbosity verbosity() const override;
  3175. private:
  3176. IStream const* openStream();
  3177. ConfigData m_data;
  3178. std::unique_ptr<IStream const> m_stream;
  3179. TestSpec m_testSpec;
  3180. bool m_hasTestFilters = false;
  3181. };
  3182. } // end namespace Catch
  3183. // end catch_config.hpp
  3184. // start catch_assertionresult.h
  3185. #include <string>
  3186. namespace Catch {
  3187. struct AssertionResultData
  3188. {
  3189. AssertionResultData() = delete;
  3190. AssertionResultData( ResultWas::OfType _resultType, LazyExpression const& _lazyExpression );
  3191. std::string message;
  3192. mutable std::string reconstructedExpression;
  3193. LazyExpression lazyExpression;
  3194. ResultWas::OfType resultType;
  3195. std::string reconstructExpression() const;
  3196. };
  3197. class AssertionResult {
  3198. public:
  3199. AssertionResult() = delete;
  3200. AssertionResult( AssertionInfo const& info, AssertionResultData const& data );
  3201. bool isOk() const;
  3202. bool succeeded() const;
  3203. ResultWas::OfType getResultType() const;
  3204. bool hasExpression() const;
  3205. bool hasMessage() const;
  3206. std::string getExpression() const;
  3207. std::string getExpressionInMacro() const;
  3208. bool hasExpandedExpression() const;
  3209. std::string getExpandedExpression() const;
  3210. std::string getMessage() const;
  3211. SourceLineInfo getSourceInfo() const;
  3212. StringRef getTestMacroName() const;
  3213. //protected:
  3214. AssertionInfo m_info;
  3215. AssertionResultData m_resultData;
  3216. };
  3217. } // end namespace Catch
  3218. // end catch_assertionresult.h
  3219. // start catch_option.hpp
  3220. namespace Catch {
  3221. // An optional type
  3222. template<typename T>
  3223. class Option {
  3224. public:
  3225. Option() : nullableValue( nullptr ) {}
  3226. Option( T const& _value )
  3227. : nullableValue( new( storage ) T( _value ) )
  3228. {}
  3229. Option( Option const& _other )
  3230. : nullableValue( _other ? new( storage ) T( *_other ) : nullptr )
  3231. {}
  3232. ~Option() {
  3233. reset();
  3234. }
  3235. Option& operator= ( Option const& _other ) {
  3236. if( &_other != this ) {
  3237. reset();
  3238. if( _other )
  3239. nullableValue = new( storage ) T( *_other );
  3240. }
  3241. return *this;
  3242. }
  3243. Option& operator = ( T const& _value ) {
  3244. reset();
  3245. nullableValue = new( storage ) T( _value );
  3246. return *this;
  3247. }
  3248. void reset() {
  3249. if( nullableValue )
  3250. nullableValue->~T();
  3251. nullableValue = nullptr;
  3252. }
  3253. T& operator*() { return *nullableValue; }
  3254. T const& operator*() const { return *nullableValue; }
  3255. T* operator->() { return nullableValue; }
  3256. const T* operator->() const { return nullableValue; }
  3257. T valueOr( T const& defaultValue ) const {
  3258. return nullableValue ? *nullableValue : defaultValue;
  3259. }
  3260. bool some() const { return nullableValue != nullptr; }
  3261. bool none() const { return nullableValue == nullptr; }
  3262. bool operator !() const { return nullableValue == nullptr; }
  3263. explicit operator bool() const {
  3264. return some();
  3265. }
  3266. private:
  3267. T *nullableValue;
  3268. alignas(alignof(T)) char storage[sizeof(T)];
  3269. };
  3270. } // end namespace Catch
  3271. // end catch_option.hpp
  3272. #include <string>
  3273. #include <iosfwd>
  3274. #include <map>
  3275. #include <set>
  3276. #include <memory>
  3277. namespace Catch {
  3278. struct ReporterConfig {
  3279. explicit ReporterConfig( IConfigPtr const& _fullConfig );
  3280. ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream );
  3281. std::ostream& stream() const;
  3282. IConfigPtr fullConfig() const;
  3283. private:
  3284. std::ostream* m_stream;
  3285. IConfigPtr m_fullConfig;
  3286. };
  3287. struct ReporterPreferences {
  3288. bool shouldRedirectStdOut = false;
  3289. bool shouldReportAllAssertions = false;
  3290. };
  3291. template<typename T>
  3292. struct LazyStat : Option<T> {
  3293. LazyStat& operator=( T const& _value ) {
  3294. Option<T>::operator=( _value );
  3295. used = false;
  3296. return *this;
  3297. }
  3298. void reset() {
  3299. Option<T>::reset();
  3300. used = false;
  3301. }
  3302. bool used = false;
  3303. };
  3304. struct TestRunInfo {
  3305. TestRunInfo( std::string const& _name );
  3306. std::string name;
  3307. };
  3308. struct GroupInfo {
  3309. GroupInfo( std::string const& _name,
  3310. std::size_t _groupIndex,
  3311. std::size_t _groupsCount );
  3312. std::string name;
  3313. std::size_t groupIndex;
  3314. std::size_t groupsCounts;
  3315. };
  3316. struct AssertionStats {
  3317. AssertionStats( AssertionResult const& _assertionResult,
  3318. std::vector<MessageInfo> const& _infoMessages,
  3319. Totals const& _totals );
  3320. AssertionStats( AssertionStats const& ) = default;
  3321. AssertionStats( AssertionStats && ) = default;
  3322. AssertionStats& operator = ( AssertionStats const& ) = default;
  3323. AssertionStats& operator = ( AssertionStats && ) = default;
  3324. virtual ~AssertionStats();
  3325. AssertionResult assertionResult;
  3326. std::vector<MessageInfo> infoMessages;
  3327. Totals totals;
  3328. };
  3329. struct SectionStats {
  3330. SectionStats( SectionInfo const& _sectionInfo,
  3331. Counts const& _assertions,
  3332. double _durationInSeconds,
  3333. bool _missingAssertions );
  3334. SectionStats( SectionStats const& ) = default;
  3335. SectionStats( SectionStats && ) = default;
  3336. SectionStats& operator = ( SectionStats const& ) = default;
  3337. SectionStats& operator = ( SectionStats && ) = default;
  3338. virtual ~SectionStats();
  3339. SectionInfo sectionInfo;
  3340. Counts assertions;
  3341. double durationInSeconds;
  3342. bool missingAssertions;
  3343. };
  3344. struct TestCaseStats {
  3345. TestCaseStats( TestCaseInfo const& _testInfo,
  3346. Totals const& _totals,
  3347. std::string const& _stdOut,
  3348. std::string const& _stdErr,
  3349. bool _aborting );
  3350. TestCaseStats( TestCaseStats const& ) = default;
  3351. TestCaseStats( TestCaseStats && ) = default;
  3352. TestCaseStats& operator = ( TestCaseStats const& ) = default;
  3353. TestCaseStats& operator = ( TestCaseStats && ) = default;
  3354. virtual ~TestCaseStats();
  3355. TestCaseInfo testInfo;
  3356. Totals totals;
  3357. std::string stdOut;
  3358. std::string stdErr;
  3359. bool aborting;
  3360. };
  3361. struct TestGroupStats {
  3362. TestGroupStats( GroupInfo const& _groupInfo,
  3363. Totals const& _totals,
  3364. bool _aborting );
  3365. TestGroupStats( GroupInfo const& _groupInfo );
  3366. TestGroupStats( TestGroupStats const& ) = default;
  3367. TestGroupStats( TestGroupStats && ) = default;
  3368. TestGroupStats& operator = ( TestGroupStats const& ) = default;
  3369. TestGroupStats& operator = ( TestGroupStats && ) = default;
  3370. virtual ~TestGroupStats();
  3371. GroupInfo groupInfo;
  3372. Totals totals;
  3373. bool aborting;
  3374. };
  3375. struct TestRunStats {
  3376. TestRunStats( TestRunInfo const& _runInfo,
  3377. Totals const& _totals,
  3378. bool _aborting );
  3379. TestRunStats( TestRunStats const& ) = default;
  3380. TestRunStats( TestRunStats && ) = default;
  3381. TestRunStats& operator = ( TestRunStats const& ) = default;
  3382. TestRunStats& operator = ( TestRunStats && ) = default;
  3383. virtual ~TestRunStats();
  3384. TestRunInfo runInfo;
  3385. Totals totals;
  3386. bool aborting;
  3387. };
  3388. struct BenchmarkInfo {
  3389. std::string name;
  3390. };
  3391. struct BenchmarkStats {
  3392. BenchmarkInfo info;
  3393. std::size_t iterations;
  3394. uint64_t elapsedTimeInNanoseconds;
  3395. };
  3396. struct IStreamingReporter {
  3397. virtual ~IStreamingReporter() = default;
  3398. // Implementing class must also provide the following static methods:
  3399. // static std::string getDescription();
  3400. // static std::set<Verbosity> getSupportedVerbosities()
  3401. virtual ReporterPreferences getPreferences() const = 0;
  3402. virtual void noMatchingTestCases( std::string const& spec ) = 0;
  3403. virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0;
  3404. virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0;
  3405. virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0;
  3406. virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0;
  3407. // *** experimental ***
  3408. virtual void benchmarkStarting( BenchmarkInfo const& ) {}
  3409. virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0;
  3410. // The return value indicates if the messages buffer should be cleared:
  3411. virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0;
  3412. // *** experimental ***
  3413. virtual void benchmarkEnded( BenchmarkStats const& ) {}
  3414. virtual void sectionEnded( SectionStats const& sectionStats ) = 0;
  3415. virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0;
  3416. virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0;
  3417. virtual void testRunEnded( TestRunStats const& testRunStats ) = 0;
  3418. virtual void skipTest( TestCaseInfo const& testInfo ) = 0;
  3419. // Default empty implementation provided
  3420. virtual void fatalErrorEncountered( StringRef name );
  3421. virtual bool isMulti() const;
  3422. };
  3423. using IStreamingReporterPtr = std::unique_ptr<IStreamingReporter>;
  3424. struct IReporterFactory {
  3425. virtual ~IReporterFactory();
  3426. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const = 0;
  3427. virtual std::string getDescription() const = 0;
  3428. };
  3429. using IReporterFactoryPtr = std::shared_ptr<IReporterFactory>;
  3430. struct IReporterRegistry {
  3431. using FactoryMap = std::map<std::string, IReporterFactoryPtr>;
  3432. using Listeners = std::vector<IReporterFactoryPtr>;
  3433. virtual ~IReporterRegistry();
  3434. virtual IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const = 0;
  3435. virtual FactoryMap const& getFactories() const = 0;
  3436. virtual Listeners const& getListeners() const = 0;
  3437. };
  3438. } // end namespace Catch
  3439. // end catch_interfaces_reporter.h
  3440. #include <algorithm>
  3441. #include <cstring>
  3442. #include <cfloat>
  3443. #include <cstdio>
  3444. #include <cassert>
  3445. #include <memory>
  3446. #include <ostream>
  3447. namespace Catch {
  3448. void prepareExpandedExpression(AssertionResult& result);
  3449. // Returns double formatted as %.3f (format expected on output)
  3450. std::string getFormattedDuration( double duration );
  3451. template<typename DerivedT>
  3452. struct StreamingReporterBase : IStreamingReporter {
  3453. StreamingReporterBase( ReporterConfig const& _config )
  3454. : m_config( _config.fullConfig() ),
  3455. stream( _config.stream() )
  3456. {
  3457. m_reporterPrefs.shouldRedirectStdOut = false;
  3458. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3459. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  3460. }
  3461. ReporterPreferences getPreferences() const override {
  3462. return m_reporterPrefs;
  3463. }
  3464. static std::set<Verbosity> getSupportedVerbosities() {
  3465. return { Verbosity::Normal };
  3466. }
  3467. ~StreamingReporterBase() override = default;
  3468. void noMatchingTestCases(std::string const&) override {}
  3469. void testRunStarting(TestRunInfo const& _testRunInfo) override {
  3470. currentTestRunInfo = _testRunInfo;
  3471. }
  3472. void testGroupStarting(GroupInfo const& _groupInfo) override {
  3473. currentGroupInfo = _groupInfo;
  3474. }
  3475. void testCaseStarting(TestCaseInfo const& _testInfo) override {
  3476. currentTestCaseInfo = _testInfo;
  3477. }
  3478. void sectionStarting(SectionInfo const& _sectionInfo) override {
  3479. m_sectionStack.push_back(_sectionInfo);
  3480. }
  3481. void sectionEnded(SectionStats const& /* _sectionStats */) override {
  3482. m_sectionStack.pop_back();
  3483. }
  3484. void testCaseEnded(TestCaseStats const& /* _testCaseStats */) override {
  3485. currentTestCaseInfo.reset();
  3486. }
  3487. void testGroupEnded(TestGroupStats const& /* _testGroupStats */) override {
  3488. currentGroupInfo.reset();
  3489. }
  3490. void testRunEnded(TestRunStats const& /* _testRunStats */) override {
  3491. currentTestCaseInfo.reset();
  3492. currentGroupInfo.reset();
  3493. currentTestRunInfo.reset();
  3494. }
  3495. void skipTest(TestCaseInfo const&) override {
  3496. // Don't do anything with this by default.
  3497. // It can optionally be overridden in the derived class.
  3498. }
  3499. IConfigPtr m_config;
  3500. std::ostream& stream;
  3501. LazyStat<TestRunInfo> currentTestRunInfo;
  3502. LazyStat<GroupInfo> currentGroupInfo;
  3503. LazyStat<TestCaseInfo> currentTestCaseInfo;
  3504. std::vector<SectionInfo> m_sectionStack;
  3505. ReporterPreferences m_reporterPrefs;
  3506. };
  3507. template<typename DerivedT>
  3508. struct CumulativeReporterBase : IStreamingReporter {
  3509. template<typename T, typename ChildNodeT>
  3510. struct Node {
  3511. explicit Node( T const& _value ) : value( _value ) {}
  3512. virtual ~Node() {}
  3513. using ChildNodes = std::vector<std::shared_ptr<ChildNodeT>>;
  3514. T value;
  3515. ChildNodes children;
  3516. };
  3517. struct SectionNode {
  3518. explicit SectionNode(SectionStats const& _stats) : stats(_stats) {}
  3519. virtual ~SectionNode() = default;
  3520. bool operator == (SectionNode const& other) const {
  3521. return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo;
  3522. }
  3523. bool operator == (std::shared_ptr<SectionNode> const& other) const {
  3524. return operator==(*other);
  3525. }
  3526. SectionStats stats;
  3527. using ChildSections = std::vector<std::shared_ptr<SectionNode>>;
  3528. using Assertions = std::vector<AssertionStats>;
  3529. ChildSections childSections;
  3530. Assertions assertions;
  3531. std::string stdOut;
  3532. std::string stdErr;
  3533. };
  3534. struct BySectionInfo {
  3535. BySectionInfo( SectionInfo const& other ) : m_other( other ) {}
  3536. BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {}
  3537. bool operator() (std::shared_ptr<SectionNode> const& node) const {
  3538. return ((node->stats.sectionInfo.name == m_other.name) &&
  3539. (node->stats.sectionInfo.lineInfo == m_other.lineInfo));
  3540. }
  3541. void operator=(BySectionInfo const&) = delete;
  3542. private:
  3543. SectionInfo const& m_other;
  3544. };
  3545. using TestCaseNode = Node<TestCaseStats, SectionNode>;
  3546. using TestGroupNode = Node<TestGroupStats, TestCaseNode>;
  3547. using TestRunNode = Node<TestRunStats, TestGroupNode>;
  3548. CumulativeReporterBase( ReporterConfig const& _config )
  3549. : m_config( _config.fullConfig() ),
  3550. stream( _config.stream() )
  3551. {
  3552. m_reporterPrefs.shouldRedirectStdOut = false;
  3553. if( !DerivedT::getSupportedVerbosities().count( m_config->verbosity() ) )
  3554. CATCH_ERROR( "Verbosity level not supported by this reporter" );
  3555. }
  3556. ~CumulativeReporterBase() override = default;
  3557. ReporterPreferences getPreferences() const override {
  3558. return m_reporterPrefs;
  3559. }
  3560. static std::set<Verbosity> getSupportedVerbosities() {
  3561. return { Verbosity::Normal };
  3562. }
  3563. void testRunStarting( TestRunInfo const& ) override {}
  3564. void testGroupStarting( GroupInfo const& ) override {}
  3565. void testCaseStarting( TestCaseInfo const& ) override {}
  3566. void sectionStarting( SectionInfo const& sectionInfo ) override {
  3567. SectionStats incompleteStats( sectionInfo, Counts(), 0, false );
  3568. std::shared_ptr<SectionNode> node;
  3569. if( m_sectionStack.empty() ) {
  3570. if( !m_rootSection )
  3571. m_rootSection = std::make_shared<SectionNode>( incompleteStats );
  3572. node = m_rootSection;
  3573. }
  3574. else {
  3575. SectionNode& parentNode = *m_sectionStack.back();
  3576. auto it =
  3577. std::find_if( parentNode.childSections.begin(),
  3578. parentNode.childSections.end(),
  3579. BySectionInfo( sectionInfo ) );
  3580. if( it == parentNode.childSections.end() ) {
  3581. node = std::make_shared<SectionNode>( incompleteStats );
  3582. parentNode.childSections.push_back( node );
  3583. }
  3584. else
  3585. node = *it;
  3586. }
  3587. m_sectionStack.push_back( node );
  3588. m_deepestSection = std::move(node);
  3589. }
  3590. void assertionStarting(AssertionInfo const&) override {}
  3591. bool assertionEnded(AssertionStats const& assertionStats) override {
  3592. assert(!m_sectionStack.empty());
  3593. // AssertionResult holds a pointer to a temporary DecomposedExpression,
  3594. // which getExpandedExpression() calls to build the expression string.
  3595. // Our section stack copy of the assertionResult will likely outlive the
  3596. // temporary, so it must be expanded or discarded now to avoid calling
  3597. // a destroyed object later.
  3598. prepareExpandedExpression(const_cast<AssertionResult&>( assertionStats.assertionResult ) );
  3599. SectionNode& sectionNode = *m_sectionStack.back();
  3600. sectionNode.assertions.push_back(assertionStats);
  3601. return true;
  3602. }
  3603. void sectionEnded(SectionStats const& sectionStats) override {
  3604. assert(!m_sectionStack.empty());
  3605. SectionNode& node = *m_sectionStack.back();
  3606. node.stats = sectionStats;
  3607. m_sectionStack.pop_back();
  3608. }
  3609. void testCaseEnded(TestCaseStats const& testCaseStats) override {
  3610. auto node = std::make_shared<TestCaseNode>(testCaseStats);
  3611. assert(m_sectionStack.size() == 0);
  3612. node->children.push_back(m_rootSection);
  3613. m_testCases.push_back(node);
  3614. m_rootSection.reset();
  3615. assert(m_deepestSection);
  3616. m_deepestSection->stdOut = testCaseStats.stdOut;
  3617. m_deepestSection->stdErr = testCaseStats.stdErr;
  3618. }
  3619. void testGroupEnded(TestGroupStats const& testGroupStats) override {
  3620. auto node = std::make_shared<TestGroupNode>(testGroupStats);
  3621. node->children.swap(m_testCases);
  3622. m_testGroups.push_back(node);
  3623. }
  3624. void testRunEnded(TestRunStats const& testRunStats) override {
  3625. auto node = std::make_shared<TestRunNode>(testRunStats);
  3626. node->children.swap(m_testGroups);
  3627. m_testRuns.push_back(node);
  3628. testRunEndedCumulative();
  3629. }
  3630. virtual void testRunEndedCumulative() = 0;
  3631. void skipTest(TestCaseInfo const&) override {}
  3632. IConfigPtr m_config;
  3633. std::ostream& stream;
  3634. std::vector<AssertionStats> m_assertions;
  3635. std::vector<std::vector<std::shared_ptr<SectionNode>>> m_sections;
  3636. std::vector<std::shared_ptr<TestCaseNode>> m_testCases;
  3637. std::vector<std::shared_ptr<TestGroupNode>> m_testGroups;
  3638. std::vector<std::shared_ptr<TestRunNode>> m_testRuns;
  3639. std::shared_ptr<SectionNode> m_rootSection;
  3640. std::shared_ptr<SectionNode> m_deepestSection;
  3641. std::vector<std::shared_ptr<SectionNode>> m_sectionStack;
  3642. ReporterPreferences m_reporterPrefs;
  3643. };
  3644. template<char C>
  3645. char const* getLineOfChars() {
  3646. static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0};
  3647. if( !*line ) {
  3648. std::memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 );
  3649. line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0;
  3650. }
  3651. return line;
  3652. }
  3653. struct TestEventListenerBase : StreamingReporterBase<TestEventListenerBase> {
  3654. TestEventListenerBase( ReporterConfig const& _config );
  3655. void assertionStarting(AssertionInfo const&) override;
  3656. bool assertionEnded(AssertionStats const&) override;
  3657. };
  3658. } // end namespace Catch
  3659. // end catch_reporter_bases.hpp
  3660. // start catch_console_colour.h
  3661. namespace Catch {
  3662. struct Colour {
  3663. enum Code {
  3664. None = 0,
  3665. White,
  3666. Red,
  3667. Green,
  3668. Blue,
  3669. Cyan,
  3670. Yellow,
  3671. Grey,
  3672. Bright = 0x10,
  3673. BrightRed = Bright | Red,
  3674. BrightGreen = Bright | Green,
  3675. LightGrey = Bright | Grey,
  3676. BrightWhite = Bright | White,
  3677. BrightYellow = Bright | Yellow,
  3678. // By intention
  3679. FileName = LightGrey,
  3680. Warning = BrightYellow,
  3681. ResultError = BrightRed,
  3682. ResultSuccess = BrightGreen,
  3683. ResultExpectedFailure = Warning,
  3684. Error = BrightRed,
  3685. Success = Green,
  3686. OriginalExpression = Cyan,
  3687. ReconstructedExpression = BrightYellow,
  3688. SecondaryText = LightGrey,
  3689. Headers = White
  3690. };
  3691. // Use constructed object for RAII guard
  3692. Colour( Code _colourCode );
  3693. Colour( Colour&& other ) noexcept;
  3694. Colour& operator=( Colour&& other ) noexcept;
  3695. ~Colour();
  3696. // Use static method for one-shot changes
  3697. static void use( Code _colourCode );
  3698. private:
  3699. bool m_moved = false;
  3700. };
  3701. std::ostream& operator << ( std::ostream& os, Colour const& );
  3702. } // end namespace Catch
  3703. // end catch_console_colour.h
  3704. // start catch_reporter_registrars.hpp
  3705. namespace Catch {
  3706. template<typename T>
  3707. class ReporterRegistrar {
  3708. class ReporterFactory : public IReporterFactory {
  3709. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3710. return std::unique_ptr<T>( new T( config ) );
  3711. }
  3712. virtual std::string getDescription() const override {
  3713. return T::getDescription();
  3714. }
  3715. };
  3716. public:
  3717. explicit ReporterRegistrar( std::string const& name ) {
  3718. getMutableRegistryHub().registerReporter( name, std::make_shared<ReporterFactory>() );
  3719. }
  3720. };
  3721. template<typename T>
  3722. class ListenerRegistrar {
  3723. class ListenerFactory : public IReporterFactory {
  3724. virtual IStreamingReporterPtr create( ReporterConfig const& config ) const override {
  3725. return std::unique_ptr<T>( new T( config ) );
  3726. }
  3727. virtual std::string getDescription() const override {
  3728. return std::string();
  3729. }
  3730. };
  3731. public:
  3732. ListenerRegistrar() {
  3733. getMutableRegistryHub().registerListener( std::make_shared<ListenerFactory>() );
  3734. }
  3735. };
  3736. }
  3737. #if !defined(CATCH_CONFIG_DISABLE)
  3738. #define CATCH_REGISTER_REPORTER( name, reporterType ) \
  3739. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3740. namespace{ Catch::ReporterRegistrar<reporterType> catch_internal_RegistrarFor##reporterType( name ); } \
  3741. CATCH_INTERNAL_UNSUPPRESS_GLOBALS_WARNINGS
  3742. #define CATCH_REGISTER_LISTENER( listenerType ) \
  3743. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS \
  3744. namespace{ Catch::ListenerRegistrar<listenerType> catch_internal_RegistrarFor##listenerType; } \
  3745. CATCH_INTERNAL_SUPPRESS_GLOBALS_WARNINGS
  3746. #else // CATCH_CONFIG_DISABLE
  3747. #define CATCH_REGISTER_REPORTER(name, reporterType)
  3748. #define CATCH_REGISTER_LISTENER(listenerType)
  3749. #endif // CATCH_CONFIG_DISABLE
  3750. // end catch_reporter_registrars.hpp
  3751. // Allow users to base their work off existing reporters
  3752. // start catch_reporter_compact.h
  3753. namespace Catch {
  3754. struct CompactReporter : StreamingReporterBase<CompactReporter> {
  3755. using StreamingReporterBase::StreamingReporterBase;
  3756. ~CompactReporter() override;
  3757. static std::string getDescription();
  3758. ReporterPreferences getPreferences() const override;
  3759. void noMatchingTestCases(std::string const& spec) override;
  3760. void assertionStarting(AssertionInfo const&) override;
  3761. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3762. void sectionEnded(SectionStats const& _sectionStats) override;
  3763. void testRunEnded(TestRunStats const& _testRunStats) override;
  3764. };
  3765. } // end namespace Catch
  3766. // end catch_reporter_compact.h
  3767. // start catch_reporter_console.h
  3768. #if defined(_MSC_VER)
  3769. #pragma warning(push)
  3770. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  3771. // Note that 4062 (not all labels are handled
  3772. // and default is missing) is enabled
  3773. #endif
  3774. namespace Catch {
  3775. // Fwd decls
  3776. struct SummaryColumn;
  3777. class TablePrinter;
  3778. struct ConsoleReporter : StreamingReporterBase<ConsoleReporter> {
  3779. std::unique_ptr<TablePrinter> m_tablePrinter;
  3780. ConsoleReporter(ReporterConfig const& config);
  3781. ~ConsoleReporter() override;
  3782. static std::string getDescription();
  3783. void noMatchingTestCases(std::string const& spec) override;
  3784. void assertionStarting(AssertionInfo const&) override;
  3785. bool assertionEnded(AssertionStats const& _assertionStats) override;
  3786. void sectionStarting(SectionInfo const& _sectionInfo) override;
  3787. void sectionEnded(SectionStats const& _sectionStats) override;
  3788. void benchmarkStarting(BenchmarkInfo const& info) override;
  3789. void benchmarkEnded(BenchmarkStats const& stats) override;
  3790. void testCaseEnded(TestCaseStats const& _testCaseStats) override;
  3791. void testGroupEnded(TestGroupStats const& _testGroupStats) override;
  3792. void testRunEnded(TestRunStats const& _testRunStats) override;
  3793. private:
  3794. void lazyPrint();
  3795. void lazyPrintWithoutClosingBenchmarkTable();
  3796. void lazyPrintRunInfo();
  3797. void lazyPrintGroupInfo();
  3798. void printTestCaseAndSectionHeader();
  3799. void printClosedHeader(std::string const& _name);
  3800. void printOpenHeader(std::string const& _name);
  3801. // if string has a : in first line will set indent to follow it on
  3802. // subsequent lines
  3803. void printHeaderString(std::string const& _string, std::size_t indent = 0);
  3804. void printTotals(Totals const& totals);
  3805. void printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row);
  3806. void printTotalsDivider(Totals const& totals);
  3807. void printSummaryDivider();
  3808. private:
  3809. bool m_headerPrinted = false;
  3810. };
  3811. } // end namespace Catch
  3812. #if defined(_MSC_VER)
  3813. #pragma warning(pop)
  3814. #endif
  3815. // end catch_reporter_console.h
  3816. // start catch_reporter_junit.h
  3817. // start catch_xmlwriter.h
  3818. #include <vector>
  3819. namespace Catch {
  3820. class XmlEncode {
  3821. public:
  3822. enum ForWhat { ForTextNodes, ForAttributes };
  3823. XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes );
  3824. void encodeTo( std::ostream& os ) const;
  3825. friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode );
  3826. private:
  3827. std::string m_str;
  3828. ForWhat m_forWhat;
  3829. };
  3830. class XmlWriter {
  3831. public:
  3832. class ScopedElement {
  3833. public:
  3834. ScopedElement( XmlWriter* writer );
  3835. ScopedElement( ScopedElement&& other ) noexcept;
  3836. ScopedElement& operator=( ScopedElement&& other ) noexcept;
  3837. ~ScopedElement();
  3838. ScopedElement& writeText( std::string const& text, bool indent = true );
  3839. template<typename T>
  3840. ScopedElement& writeAttribute( std::string const& name, T const& attribute ) {
  3841. m_writer->writeAttribute( name, attribute );
  3842. return *this;
  3843. }
  3844. private:
  3845. mutable XmlWriter* m_writer = nullptr;
  3846. };
  3847. XmlWriter( std::ostream& os = Catch::cout() );
  3848. ~XmlWriter();
  3849. XmlWriter( XmlWriter const& ) = delete;
  3850. XmlWriter& operator=( XmlWriter const& ) = delete;
  3851. XmlWriter& startElement( std::string const& name );
  3852. ScopedElement scopedElement( std::string const& name );
  3853. XmlWriter& endElement();
  3854. XmlWriter& writeAttribute( std::string const& name, std::string const& attribute );
  3855. XmlWriter& writeAttribute( std::string const& name, bool attribute );
  3856. template<typename T>
  3857. XmlWriter& writeAttribute( std::string const& name, T const& attribute ) {
  3858. ReusableStringStream rss;
  3859. rss << attribute;
  3860. return writeAttribute( name, rss.str() );
  3861. }
  3862. XmlWriter& writeText( std::string const& text, bool indent = true );
  3863. XmlWriter& writeComment( std::string const& text );
  3864. void writeStylesheetRef( std::string const& url );
  3865. XmlWriter& writeBlankLine();
  3866. void ensureTagClosed();
  3867. private:
  3868. void writeDeclaration();
  3869. void newlineIfNecessary();
  3870. bool m_tagIsOpen = false;
  3871. bool m_needsNewline = false;
  3872. std::vector<std::string> m_tags;
  3873. std::string m_indent;
  3874. std::ostream& m_os;
  3875. };
  3876. }
  3877. // end catch_xmlwriter.h
  3878. namespace Catch {
  3879. class JunitReporter : public CumulativeReporterBase<JunitReporter> {
  3880. public:
  3881. JunitReporter(ReporterConfig const& _config);
  3882. ~JunitReporter() override;
  3883. static std::string getDescription();
  3884. void noMatchingTestCases(std::string const& /*spec*/) override;
  3885. void testRunStarting(TestRunInfo const& runInfo) override;
  3886. void testGroupStarting(GroupInfo const& groupInfo) override;
  3887. void testCaseStarting(TestCaseInfo const& testCaseInfo) override;
  3888. bool assertionEnded(AssertionStats const& assertionStats) override;
  3889. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3890. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3891. void testRunEndedCumulative() override;
  3892. void writeGroup(TestGroupNode const& groupNode, double suiteTime);
  3893. void writeTestCase(TestCaseNode const& testCaseNode);
  3894. void writeSection(std::string const& className,
  3895. std::string const& rootName,
  3896. SectionNode const& sectionNode);
  3897. void writeAssertions(SectionNode const& sectionNode);
  3898. void writeAssertion(AssertionStats const& stats);
  3899. XmlWriter xml;
  3900. Timer suiteTimer;
  3901. std::string stdOutForSuite;
  3902. std::string stdErrForSuite;
  3903. unsigned int unexpectedExceptions = 0;
  3904. bool m_okToFail = false;
  3905. };
  3906. } // end namespace Catch
  3907. // end catch_reporter_junit.h
  3908. // start catch_reporter_xml.h
  3909. namespace Catch {
  3910. class XmlReporter : public StreamingReporterBase<XmlReporter> {
  3911. public:
  3912. XmlReporter(ReporterConfig const& _config);
  3913. ~XmlReporter() override;
  3914. static std::string getDescription();
  3915. virtual std::string getStylesheetRef() const;
  3916. void writeSourceInfo(SourceLineInfo const& sourceInfo);
  3917. public: // StreamingReporterBase
  3918. void noMatchingTestCases(std::string const& s) override;
  3919. void testRunStarting(TestRunInfo const& testInfo) override;
  3920. void testGroupStarting(GroupInfo const& groupInfo) override;
  3921. void testCaseStarting(TestCaseInfo const& testInfo) override;
  3922. void sectionStarting(SectionInfo const& sectionInfo) override;
  3923. void assertionStarting(AssertionInfo const&) override;
  3924. bool assertionEnded(AssertionStats const& assertionStats) override;
  3925. void sectionEnded(SectionStats const& sectionStats) override;
  3926. void testCaseEnded(TestCaseStats const& testCaseStats) override;
  3927. void testGroupEnded(TestGroupStats const& testGroupStats) override;
  3928. void testRunEnded(TestRunStats const& testRunStats) override;
  3929. private:
  3930. Timer m_testCaseTimer;
  3931. XmlWriter m_xml;
  3932. int m_sectionDepth = 0;
  3933. };
  3934. } // end namespace Catch
  3935. // end catch_reporter_xml.h
  3936. // end catch_external_interfaces.h
  3937. #endif
  3938. #endif // ! CATCH_CONFIG_IMPL_ONLY
  3939. #ifdef CATCH_IMPL
  3940. // start catch_impl.hpp
  3941. #ifdef __clang__
  3942. #pragma clang diagnostic push
  3943. #pragma clang diagnostic ignored "-Wweak-vtables"
  3944. #endif
  3945. // Keep these here for external reporters
  3946. // start catch_test_case_tracker.h
  3947. #include <string>
  3948. #include <vector>
  3949. #include <memory>
  3950. namespace Catch {
  3951. namespace TestCaseTracking {
  3952. struct NameAndLocation {
  3953. std::string name;
  3954. SourceLineInfo location;
  3955. NameAndLocation( std::string const& _name, SourceLineInfo const& _location );
  3956. };
  3957. struct ITracker;
  3958. using ITrackerPtr = std::shared_ptr<ITracker>;
  3959. struct ITracker {
  3960. virtual ~ITracker();
  3961. // static queries
  3962. virtual NameAndLocation const& nameAndLocation() const = 0;
  3963. // dynamic queries
  3964. virtual bool isComplete() const = 0; // Successfully completed or failed
  3965. virtual bool isSuccessfullyCompleted() const = 0;
  3966. virtual bool isOpen() const = 0; // Started but not complete
  3967. virtual bool hasChildren() const = 0;
  3968. virtual ITracker& parent() = 0;
  3969. // actions
  3970. virtual void close() = 0; // Successfully complete
  3971. virtual void fail() = 0;
  3972. virtual void markAsNeedingAnotherRun() = 0;
  3973. virtual void addChild( ITrackerPtr const& child ) = 0;
  3974. virtual ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) = 0;
  3975. virtual void openChild() = 0;
  3976. // Debug/ checking
  3977. virtual bool isSectionTracker() const = 0;
  3978. virtual bool isIndexTracker() const = 0;
  3979. };
  3980. class TrackerContext {
  3981. enum RunState {
  3982. NotStarted,
  3983. Executing,
  3984. CompletedCycle
  3985. };
  3986. ITrackerPtr m_rootTracker;
  3987. ITracker* m_currentTracker = nullptr;
  3988. RunState m_runState = NotStarted;
  3989. public:
  3990. static TrackerContext& instance();
  3991. ITracker& startRun();
  3992. void endRun();
  3993. void startCycle();
  3994. void completeCycle();
  3995. bool completedCycle() const;
  3996. ITracker& currentTracker();
  3997. void setCurrentTracker( ITracker* tracker );
  3998. };
  3999. class TrackerBase : public ITracker {
  4000. protected:
  4001. enum CycleState {
  4002. NotStarted,
  4003. Executing,
  4004. ExecutingChildren,
  4005. NeedsAnotherRun,
  4006. CompletedSuccessfully,
  4007. Failed
  4008. };
  4009. using Children = std::vector<ITrackerPtr>;
  4010. NameAndLocation m_nameAndLocation;
  4011. TrackerContext& m_ctx;
  4012. ITracker* m_parent;
  4013. Children m_children;
  4014. CycleState m_runState = NotStarted;
  4015. public:
  4016. TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  4017. NameAndLocation const& nameAndLocation() const override;
  4018. bool isComplete() const override;
  4019. bool isSuccessfullyCompleted() const override;
  4020. bool isOpen() const override;
  4021. bool hasChildren() const override;
  4022. void addChild( ITrackerPtr const& child ) override;
  4023. ITrackerPtr findChild( NameAndLocation const& nameAndLocation ) override;
  4024. ITracker& parent() override;
  4025. void openChild() override;
  4026. bool isSectionTracker() const override;
  4027. bool isIndexTracker() const override;
  4028. void open();
  4029. void close() override;
  4030. void fail() override;
  4031. void markAsNeedingAnotherRun() override;
  4032. private:
  4033. void moveToParent();
  4034. void moveToThis();
  4035. };
  4036. class SectionTracker : public TrackerBase {
  4037. std::vector<std::string> m_filters;
  4038. public:
  4039. SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent );
  4040. bool isSectionTracker() const override;
  4041. static SectionTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation );
  4042. void tryOpen();
  4043. void addInitialFilters( std::vector<std::string> const& filters );
  4044. void addNextFilters( std::vector<std::string> const& filters );
  4045. };
  4046. class IndexTracker : public TrackerBase {
  4047. int m_size;
  4048. int m_index = -1;
  4049. public:
  4050. IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size );
  4051. bool isIndexTracker() const override;
  4052. void close() override;
  4053. static IndexTracker& acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size );
  4054. int index() const;
  4055. void moveNext();
  4056. };
  4057. } // namespace TestCaseTracking
  4058. using TestCaseTracking::ITracker;
  4059. using TestCaseTracking::TrackerContext;
  4060. using TestCaseTracking::SectionTracker;
  4061. using TestCaseTracking::IndexTracker;
  4062. } // namespace Catch
  4063. // end catch_test_case_tracker.h
  4064. // start catch_leak_detector.h
  4065. namespace Catch {
  4066. struct LeakDetector {
  4067. LeakDetector();
  4068. ~LeakDetector();
  4069. };
  4070. }
  4071. // end catch_leak_detector.h
  4072. // Cpp files will be included in the single-header file here
  4073. // start catch_approx.cpp
  4074. #include <cmath>
  4075. #include <limits>
  4076. namespace {
  4077. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  4078. // But without the subtraction to allow for INFINITY in comparison
  4079. bool marginComparison(double lhs, double rhs, double margin) {
  4080. return (lhs + margin >= rhs) && (rhs + margin >= lhs);
  4081. }
  4082. }
  4083. namespace Catch {
  4084. namespace Detail {
  4085. Approx::Approx ( double value )
  4086. : m_epsilon( std::numeric_limits<float>::epsilon()*100 ),
  4087. m_margin( 0.0 ),
  4088. m_scale( 0.0 ),
  4089. m_value( value )
  4090. {}
  4091. Approx Approx::custom() {
  4092. return Approx( 0 );
  4093. }
  4094. Approx Approx::operator-() const {
  4095. auto temp(*this);
  4096. temp.m_value = -temp.m_value;
  4097. return temp;
  4098. }
  4099. std::string Approx::toString() const {
  4100. ReusableStringStream rss;
  4101. rss << "Approx( " << ::Catch::Detail::stringify( m_value ) << " )";
  4102. return rss.str();
  4103. }
  4104. bool Approx::equalityComparisonImpl(const double other) const {
  4105. // First try with fixed margin, then compute margin based on epsilon, scale and Approx's value
  4106. // Thanks to Richard Harris for his help refining the scaled margin value
  4107. return marginComparison(m_value, other, m_margin) || marginComparison(m_value, other, m_epsilon * (m_scale + std::fabs(m_value)));
  4108. }
  4109. void Approx::setMargin(double margin) {
  4110. CATCH_ENFORCE(margin >= 0,
  4111. "Invalid Approx::margin: " << margin << '.'
  4112. << " Approx::Margin has to be non-negative.");
  4113. m_margin = margin;
  4114. }
  4115. void Approx::setEpsilon(double epsilon) {
  4116. CATCH_ENFORCE(epsilon >= 0 && epsilon <= 1.0,
  4117. "Invalid Approx::epsilon: " << epsilon << '.'
  4118. << " Approx::epsilon has to be in [0, 1]");
  4119. m_epsilon = epsilon;
  4120. }
  4121. } // end namespace Detail
  4122. namespace literals {
  4123. Detail::Approx operator "" _a(long double val) {
  4124. return Detail::Approx(val);
  4125. }
  4126. Detail::Approx operator "" _a(unsigned long long val) {
  4127. return Detail::Approx(val);
  4128. }
  4129. } // end namespace literals
  4130. std::string StringMaker<Catch::Detail::Approx>::convert(Catch::Detail::Approx const& value) {
  4131. return value.toString();
  4132. }
  4133. } // end namespace Catch
  4134. // end catch_approx.cpp
  4135. // start catch_assertionhandler.cpp
  4136. // start catch_context.h
  4137. #include <memory>
  4138. namespace Catch {
  4139. struct IResultCapture;
  4140. struct IRunner;
  4141. struct IConfig;
  4142. struct IMutableContext;
  4143. using IConfigPtr = std::shared_ptr<IConfig const>;
  4144. struct IContext
  4145. {
  4146. virtual ~IContext();
  4147. virtual IResultCapture* getResultCapture() = 0;
  4148. virtual IRunner* getRunner() = 0;
  4149. virtual IConfigPtr const& getConfig() const = 0;
  4150. };
  4151. struct IMutableContext : IContext
  4152. {
  4153. virtual ~IMutableContext();
  4154. virtual void setResultCapture( IResultCapture* resultCapture ) = 0;
  4155. virtual void setRunner( IRunner* runner ) = 0;
  4156. virtual void setConfig( IConfigPtr const& config ) = 0;
  4157. private:
  4158. static IMutableContext *currentContext;
  4159. friend IMutableContext& getCurrentMutableContext();
  4160. friend void cleanUpContext();
  4161. static void createContext();
  4162. };
  4163. inline IMutableContext& getCurrentMutableContext()
  4164. {
  4165. if( !IMutableContext::currentContext )
  4166. IMutableContext::createContext();
  4167. return *IMutableContext::currentContext;
  4168. }
  4169. inline IContext& getCurrentContext()
  4170. {
  4171. return getCurrentMutableContext();
  4172. }
  4173. void cleanUpContext();
  4174. }
  4175. // end catch_context.h
  4176. // start catch_debugger.h
  4177. namespace Catch {
  4178. bool isDebuggerActive();
  4179. }
  4180. #ifdef CATCH_PLATFORM_MAC
  4181. #define CATCH_TRAP() __asm__("int $3\n" : : ) /* NOLINT */
  4182. #elif defined(CATCH_PLATFORM_LINUX)
  4183. // If we can use inline assembler, do it because this allows us to break
  4184. // directly at the location of the failing check instead of breaking inside
  4185. // raise() called from it, i.e. one stack frame below.
  4186. #if defined(__GNUC__) && (defined(__i386) || defined(__x86_64))
  4187. #define CATCH_TRAP() asm volatile ("int $3") /* NOLINT */
  4188. #else // Fall back to the generic way.
  4189. #include <signal.h>
  4190. #define CATCH_TRAP() raise(SIGTRAP)
  4191. #endif
  4192. #elif defined(_MSC_VER)
  4193. #define CATCH_TRAP() __debugbreak()
  4194. #elif defined(__MINGW32__)
  4195. extern "C" __declspec(dllimport) void __stdcall DebugBreak();
  4196. #define CATCH_TRAP() DebugBreak()
  4197. #endif
  4198. #ifdef CATCH_TRAP
  4199. #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { CATCH_TRAP(); }
  4200. #else
  4201. namespace Catch {
  4202. inline void doNothing() {}
  4203. }
  4204. #define CATCH_BREAK_INTO_DEBUGGER() Catch::doNothing()
  4205. #endif
  4206. // end catch_debugger.h
  4207. // start catch_run_context.h
  4208. // start catch_fatal_condition.h
  4209. // start catch_windows_h_proxy.h
  4210. #if defined(CATCH_PLATFORM_WINDOWS)
  4211. #if !defined(NOMINMAX) && !defined(CATCH_CONFIG_NO_NOMINMAX)
  4212. # define CATCH_DEFINED_NOMINMAX
  4213. # define NOMINMAX
  4214. #endif
  4215. #if !defined(WIN32_LEAN_AND_MEAN) && !defined(CATCH_CONFIG_NO_WIN32_LEAN_AND_MEAN)
  4216. # define CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4217. # define WIN32_LEAN_AND_MEAN
  4218. #endif
  4219. #ifdef __AFXDLL
  4220. #include <AfxWin.h>
  4221. #else
  4222. #include <windows.h>
  4223. #endif
  4224. #ifdef CATCH_DEFINED_NOMINMAX
  4225. # undef NOMINMAX
  4226. #endif
  4227. #ifdef CATCH_DEFINED_WIN32_LEAN_AND_MEAN
  4228. # undef WIN32_LEAN_AND_MEAN
  4229. #endif
  4230. #endif // defined(CATCH_PLATFORM_WINDOWS)
  4231. // end catch_windows_h_proxy.h
  4232. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  4233. namespace Catch {
  4234. struct FatalConditionHandler {
  4235. static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo);
  4236. FatalConditionHandler();
  4237. static void reset();
  4238. ~FatalConditionHandler();
  4239. private:
  4240. static bool isSet;
  4241. static ULONG guaranteeSize;
  4242. static PVOID exceptionHandlerHandle;
  4243. };
  4244. } // namespace Catch
  4245. #elif defined ( CATCH_CONFIG_POSIX_SIGNALS )
  4246. #include <signal.h>
  4247. namespace Catch {
  4248. struct FatalConditionHandler {
  4249. static bool isSet;
  4250. static struct sigaction oldSigActions[];
  4251. static stack_t oldSigStack;
  4252. static char altStackMem[];
  4253. static void handleSignal( int sig );
  4254. FatalConditionHandler();
  4255. ~FatalConditionHandler();
  4256. static void reset();
  4257. };
  4258. } // namespace Catch
  4259. #else
  4260. namespace Catch {
  4261. struct FatalConditionHandler {
  4262. void reset();
  4263. };
  4264. }
  4265. #endif
  4266. // end catch_fatal_condition.h
  4267. #include <string>
  4268. namespace Catch {
  4269. struct IMutableContext;
  4270. ///////////////////////////////////////////////////////////////////////////
  4271. class RunContext : public IResultCapture, public IRunner {
  4272. public:
  4273. RunContext( RunContext const& ) = delete;
  4274. RunContext& operator =( RunContext const& ) = delete;
  4275. explicit RunContext( IConfigPtr const& _config, IStreamingReporterPtr&& reporter );
  4276. ~RunContext() override;
  4277. void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount );
  4278. void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount );
  4279. Totals runTest(TestCase const& testCase);
  4280. IConfigPtr config() const;
  4281. IStreamingReporter& reporter() const;
  4282. public: // IResultCapture
  4283. // Assertion handlers
  4284. void handleExpr
  4285. ( AssertionInfo const& info,
  4286. ITransientExpression const& expr,
  4287. AssertionReaction& reaction ) override;
  4288. void handleMessage
  4289. ( AssertionInfo const& info,
  4290. ResultWas::OfType resultType,
  4291. StringRef const& message,
  4292. AssertionReaction& reaction ) override;
  4293. void handleUnexpectedExceptionNotThrown
  4294. ( AssertionInfo const& info,
  4295. AssertionReaction& reaction ) override;
  4296. void handleUnexpectedInflightException
  4297. ( AssertionInfo const& info,
  4298. std::string const& message,
  4299. AssertionReaction& reaction ) override;
  4300. void handleIncomplete
  4301. ( AssertionInfo const& info ) override;
  4302. void handleNonExpr
  4303. ( AssertionInfo const &info,
  4304. ResultWas::OfType resultType,
  4305. AssertionReaction &reaction ) override;
  4306. bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) override;
  4307. void sectionEnded( SectionEndInfo const& endInfo ) override;
  4308. void sectionEndedEarly( SectionEndInfo const& endInfo ) override;
  4309. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& override;
  4310. void benchmarkStarting( BenchmarkInfo const& info ) override;
  4311. void benchmarkEnded( BenchmarkStats const& stats ) override;
  4312. void pushScopedMessage( MessageInfo const& message ) override;
  4313. void popScopedMessage( MessageInfo const& message ) override;
  4314. std::string getCurrentTestName() const override;
  4315. const AssertionResult* getLastResult() const override;
  4316. void exceptionEarlyReported() override;
  4317. void handleFatalErrorCondition( StringRef message ) override;
  4318. bool lastAssertionPassed() override;
  4319. void assertionPassed() override;
  4320. public:
  4321. // !TBD We need to do this another way!
  4322. bool aborting() const final;
  4323. private:
  4324. void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr );
  4325. void invokeActiveTestCase();
  4326. void resetAssertionInfo();
  4327. bool testForMissingAssertions( Counts& assertions );
  4328. void assertionEnded( AssertionResult const& result );
  4329. void reportExpr
  4330. ( AssertionInfo const &info,
  4331. ResultWas::OfType resultType,
  4332. ITransientExpression const *expr,
  4333. bool negated );
  4334. void populateReaction( AssertionReaction& reaction );
  4335. private:
  4336. void handleUnfinishedSections();
  4337. TestRunInfo m_runInfo;
  4338. IMutableContext& m_context;
  4339. TestCase const* m_activeTestCase = nullptr;
  4340. ITracker* m_testCaseTracker;
  4341. Option<AssertionResult> m_lastResult;
  4342. IConfigPtr m_config;
  4343. Totals m_totals;
  4344. IStreamingReporterPtr m_reporter;
  4345. std::vector<MessageInfo> m_messages;
  4346. AssertionInfo m_lastAssertionInfo;
  4347. std::vector<SectionEndInfo> m_unfinishedSections;
  4348. std::vector<ITracker*> m_activeSections;
  4349. TrackerContext m_trackerContext;
  4350. bool m_lastAssertionPassed = false;
  4351. bool m_shouldReportUnexpected = true;
  4352. bool m_includeSuccessfulResults;
  4353. };
  4354. } // end namespace Catch
  4355. // end catch_run_context.h
  4356. namespace Catch {
  4357. namespace {
  4358. auto operator <<( std::ostream& os, ITransientExpression const& expr ) -> std::ostream& {
  4359. expr.streamReconstructedExpression( os );
  4360. return os;
  4361. }
  4362. }
  4363. LazyExpression::LazyExpression( bool isNegated )
  4364. : m_isNegated( isNegated )
  4365. {}
  4366. LazyExpression::LazyExpression( LazyExpression const& other ) : m_isNegated( other.m_isNegated ) {}
  4367. LazyExpression::operator bool() const {
  4368. return m_transientExpression != nullptr;
  4369. }
  4370. auto operator << ( std::ostream& os, LazyExpression const& lazyExpr ) -> std::ostream& {
  4371. if( lazyExpr.m_isNegated )
  4372. os << "!";
  4373. if( lazyExpr ) {
  4374. if( lazyExpr.m_isNegated && lazyExpr.m_transientExpression->isBinaryExpression() )
  4375. os << "(" << *lazyExpr.m_transientExpression << ")";
  4376. else
  4377. os << *lazyExpr.m_transientExpression;
  4378. }
  4379. else {
  4380. os << "{** error - unchecked empty expression requested **}";
  4381. }
  4382. return os;
  4383. }
  4384. AssertionHandler::AssertionHandler
  4385. ( StringRef const& macroName,
  4386. SourceLineInfo const& lineInfo,
  4387. StringRef capturedExpression,
  4388. ResultDisposition::Flags resultDisposition )
  4389. : m_assertionInfo{ macroName, lineInfo, capturedExpression, resultDisposition },
  4390. m_resultCapture( getResultCapture() )
  4391. {}
  4392. void AssertionHandler::handleExpr( ITransientExpression const& expr ) {
  4393. m_resultCapture.handleExpr( m_assertionInfo, expr, m_reaction );
  4394. }
  4395. void AssertionHandler::handleMessage(ResultWas::OfType resultType, StringRef const& message) {
  4396. m_resultCapture.handleMessage( m_assertionInfo, resultType, message, m_reaction );
  4397. }
  4398. auto AssertionHandler::allowThrows() const -> bool {
  4399. return getCurrentContext().getConfig()->allowThrows();
  4400. }
  4401. void AssertionHandler::complete() {
  4402. setCompleted();
  4403. if( m_reaction.shouldDebugBreak ) {
  4404. // If you find your debugger stopping you here then go one level up on the
  4405. // call-stack for the code that caused it (typically a failed assertion)
  4406. // (To go back to the test and change execution, jump over the throw, next)
  4407. CATCH_BREAK_INTO_DEBUGGER();
  4408. }
  4409. if (m_reaction.shouldThrow) {
  4410. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  4411. throw Catch::TestFailureException();
  4412. #else
  4413. CATCH_ERROR( "Test failure requires aborting test!" );
  4414. #endif
  4415. }
  4416. }
  4417. void AssertionHandler::setCompleted() {
  4418. m_completed = true;
  4419. }
  4420. void AssertionHandler::handleUnexpectedInflightException() {
  4421. m_resultCapture.handleUnexpectedInflightException( m_assertionInfo, Catch::translateActiveException(), m_reaction );
  4422. }
  4423. void AssertionHandler::handleExceptionThrownAsExpected() {
  4424. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4425. }
  4426. void AssertionHandler::handleExceptionNotThrownAsExpected() {
  4427. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4428. }
  4429. void AssertionHandler::handleUnexpectedExceptionNotThrown() {
  4430. m_resultCapture.handleUnexpectedExceptionNotThrown( m_assertionInfo, m_reaction );
  4431. }
  4432. void AssertionHandler::handleThrowingCallSkipped() {
  4433. m_resultCapture.handleNonExpr(m_assertionInfo, ResultWas::Ok, m_reaction);
  4434. }
  4435. // This is the overload that takes a string and infers the Equals matcher from it
  4436. // The more general overload, that takes any string matcher, is in catch_capture_matchers.cpp
  4437. void handleExceptionMatchExpr( AssertionHandler& handler, std::string const& str, StringRef const& matcherString ) {
  4438. handleExceptionMatchExpr( handler, Matchers::Equals( str ), matcherString );
  4439. }
  4440. } // namespace Catch
  4441. // end catch_assertionhandler.cpp
  4442. // start catch_assertionresult.cpp
  4443. namespace Catch {
  4444. AssertionResultData::AssertionResultData(ResultWas::OfType _resultType, LazyExpression const & _lazyExpression):
  4445. lazyExpression(_lazyExpression),
  4446. resultType(_resultType) {}
  4447. std::string AssertionResultData::reconstructExpression() const {
  4448. if( reconstructedExpression.empty() ) {
  4449. if( lazyExpression ) {
  4450. ReusableStringStream rss;
  4451. rss << lazyExpression;
  4452. reconstructedExpression = rss.str();
  4453. }
  4454. }
  4455. return reconstructedExpression;
  4456. }
  4457. AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data )
  4458. : m_info( info ),
  4459. m_resultData( data )
  4460. {}
  4461. // Result was a success
  4462. bool AssertionResult::succeeded() const {
  4463. return Catch::isOk( m_resultData.resultType );
  4464. }
  4465. // Result was a success, or failure is suppressed
  4466. bool AssertionResult::isOk() const {
  4467. return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition );
  4468. }
  4469. ResultWas::OfType AssertionResult::getResultType() const {
  4470. return m_resultData.resultType;
  4471. }
  4472. bool AssertionResult::hasExpression() const {
  4473. return m_info.capturedExpression[0] != 0;
  4474. }
  4475. bool AssertionResult::hasMessage() const {
  4476. return !m_resultData.message.empty();
  4477. }
  4478. std::string AssertionResult::getExpression() const {
  4479. if( isFalseTest( m_info.resultDisposition ) )
  4480. return "!(" + m_info.capturedExpression + ")";
  4481. else
  4482. return m_info.capturedExpression;
  4483. }
  4484. std::string AssertionResult::getExpressionInMacro() const {
  4485. std::string expr;
  4486. if( m_info.macroName[0] == 0 )
  4487. expr = m_info.capturedExpression;
  4488. else {
  4489. expr.reserve( m_info.macroName.size() + m_info.capturedExpression.size() + 4 );
  4490. expr += m_info.macroName;
  4491. expr += "( ";
  4492. expr += m_info.capturedExpression;
  4493. expr += " )";
  4494. }
  4495. return expr;
  4496. }
  4497. bool AssertionResult::hasExpandedExpression() const {
  4498. return hasExpression() && getExpandedExpression() != getExpression();
  4499. }
  4500. std::string AssertionResult::getExpandedExpression() const {
  4501. std::string expr = m_resultData.reconstructExpression();
  4502. return expr.empty()
  4503. ? getExpression()
  4504. : expr;
  4505. }
  4506. std::string AssertionResult::getMessage() const {
  4507. return m_resultData.message;
  4508. }
  4509. SourceLineInfo AssertionResult::getSourceInfo() const {
  4510. return m_info.lineInfo;
  4511. }
  4512. StringRef AssertionResult::getTestMacroName() const {
  4513. return m_info.macroName;
  4514. }
  4515. } // end namespace Catch
  4516. // end catch_assertionresult.cpp
  4517. // start catch_benchmark.cpp
  4518. namespace Catch {
  4519. auto BenchmarkLooper::getResolution() -> uint64_t {
  4520. return getEstimatedClockResolution() * getCurrentContext().getConfig()->benchmarkResolutionMultiple();
  4521. }
  4522. void BenchmarkLooper::reportStart() {
  4523. getResultCapture().benchmarkStarting( { m_name } );
  4524. }
  4525. auto BenchmarkLooper::needsMoreIterations() -> bool {
  4526. auto elapsed = m_timer.getElapsedNanoseconds();
  4527. // Exponentially increasing iterations until we're confident in our timer resolution
  4528. if( elapsed < m_resolution ) {
  4529. m_iterationsToRun *= 10;
  4530. return true;
  4531. }
  4532. getResultCapture().benchmarkEnded( { { m_name }, m_count, elapsed } );
  4533. return false;
  4534. }
  4535. } // end namespace Catch
  4536. // end catch_benchmark.cpp
  4537. // start catch_capture_matchers.cpp
  4538. namespace Catch {
  4539. using StringMatcher = Matchers::Impl::MatcherBase<std::string>;
  4540. // This is the general overload that takes a any string matcher
  4541. // There is another overload, in catch_assertionhandler.h/.cpp, that only takes a string and infers
  4542. // the Equals matcher (so the header does not mention matchers)
  4543. void handleExceptionMatchExpr( AssertionHandler& handler, StringMatcher const& matcher, StringRef const& matcherString ) {
  4544. std::string exceptionMessage = Catch::translateActiveException();
  4545. MatchExpr<std::string, StringMatcher const&> expr( exceptionMessage, matcher, matcherString );
  4546. handler.handleExpr( expr );
  4547. }
  4548. } // namespace Catch
  4549. // end catch_capture_matchers.cpp
  4550. // start catch_commandline.cpp
  4551. // start catch_commandline.h
  4552. // start catch_clara.h
  4553. // Use Catch's value for console width (store Clara's off to the side, if present)
  4554. #ifdef CLARA_CONFIG_CONSOLE_WIDTH
  4555. #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4556. #undef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4557. #endif
  4558. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH-1
  4559. #ifdef __clang__
  4560. #pragma clang diagnostic push
  4561. #pragma clang diagnostic ignored "-Wweak-vtables"
  4562. #pragma clang diagnostic ignored "-Wexit-time-destructors"
  4563. #pragma clang diagnostic ignored "-Wshadow"
  4564. #endif
  4565. // start clara.hpp
  4566. // Copyright 2017 Two Blue Cubes Ltd. All rights reserved.
  4567. //
  4568. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4569. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4570. //
  4571. // See https://github.com/philsquared/Clara for more details
  4572. // Clara v1.1.5
  4573. #ifndef CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4574. #define CATCH_CLARA_CONFIG_CONSOLE_WIDTH 80
  4575. #endif
  4576. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4577. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_CLARA_CONFIG_CONSOLE_WIDTH
  4578. #endif
  4579. #ifndef CLARA_CONFIG_OPTIONAL_TYPE
  4580. #ifdef __has_include
  4581. #if __has_include(<optional>) && __cplusplus >= 201703L
  4582. #include <optional>
  4583. #define CLARA_CONFIG_OPTIONAL_TYPE std::optional
  4584. #endif
  4585. #endif
  4586. #endif
  4587. // ----------- #included from clara_textflow.hpp -----------
  4588. // TextFlowCpp
  4589. //
  4590. // A single-header library for wrapping and laying out basic text, by Phil Nash
  4591. //
  4592. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4593. // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  4594. //
  4595. // This project is hosted at https://github.com/philsquared/textflowcpp
  4596. #include <cassert>
  4597. #include <ostream>
  4598. #include <sstream>
  4599. #include <vector>
  4600. #ifndef CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH
  4601. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH 80
  4602. #endif
  4603. namespace Catch {
  4604. namespace clara {
  4605. namespace TextFlow {
  4606. inline auto isWhitespace(char c) -> bool {
  4607. static std::string chars = " \t\n\r";
  4608. return chars.find(c) != std::string::npos;
  4609. }
  4610. inline auto isBreakableBefore(char c) -> bool {
  4611. static std::string chars = "[({<|";
  4612. return chars.find(c) != std::string::npos;
  4613. }
  4614. inline auto isBreakableAfter(char c) -> bool {
  4615. static std::string chars = "])}>.,:;*+-=&/\\";
  4616. return chars.find(c) != std::string::npos;
  4617. }
  4618. class Columns;
  4619. class Column {
  4620. std::vector<std::string> m_strings;
  4621. size_t m_width = CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH;
  4622. size_t m_indent = 0;
  4623. size_t m_initialIndent = std::string::npos;
  4624. public:
  4625. class iterator {
  4626. friend Column;
  4627. Column const& m_column;
  4628. size_t m_stringIndex = 0;
  4629. size_t m_pos = 0;
  4630. size_t m_len = 0;
  4631. size_t m_end = 0;
  4632. bool m_suffix = false;
  4633. iterator(Column const& column, size_t stringIndex)
  4634. : m_column(column),
  4635. m_stringIndex(stringIndex) {}
  4636. auto line() const -> std::string const& { return m_column.m_strings[m_stringIndex]; }
  4637. auto isBoundary(size_t at) const -> bool {
  4638. assert(at > 0);
  4639. assert(at <= line().size());
  4640. return at == line().size() ||
  4641. (isWhitespace(line()[at]) && !isWhitespace(line()[at - 1])) ||
  4642. isBreakableBefore(line()[at]) ||
  4643. isBreakableAfter(line()[at - 1]);
  4644. }
  4645. void calcLength() {
  4646. assert(m_stringIndex < m_column.m_strings.size());
  4647. m_suffix = false;
  4648. auto width = m_column.m_width - indent();
  4649. m_end = m_pos;
  4650. while (m_end < line().size() && line()[m_end] != '\n')
  4651. ++m_end;
  4652. if (m_end < m_pos + width) {
  4653. m_len = m_end - m_pos;
  4654. } else {
  4655. size_t len = width;
  4656. while (len > 0 && !isBoundary(m_pos + len))
  4657. --len;
  4658. while (len > 0 && isWhitespace(line()[m_pos + len - 1]))
  4659. --len;
  4660. if (len > 0) {
  4661. m_len = len;
  4662. } else {
  4663. m_suffix = true;
  4664. m_len = width - 1;
  4665. }
  4666. }
  4667. }
  4668. auto indent() const -> size_t {
  4669. auto initial = m_pos == 0 && m_stringIndex == 0 ? m_column.m_initialIndent : std::string::npos;
  4670. return initial == std::string::npos ? m_column.m_indent : initial;
  4671. }
  4672. auto addIndentAndSuffix(std::string const &plain) const -> std::string {
  4673. return std::string(indent(), ' ') + (m_suffix ? plain + "-" : plain);
  4674. }
  4675. public:
  4676. using difference_type = std::ptrdiff_t;
  4677. using value_type = std::string;
  4678. using pointer = value_type * ;
  4679. using reference = value_type & ;
  4680. using iterator_category = std::forward_iterator_tag;
  4681. explicit iterator(Column const& column) : m_column(column) {
  4682. assert(m_column.m_width > m_column.m_indent);
  4683. assert(m_column.m_initialIndent == std::string::npos || m_column.m_width > m_column.m_initialIndent);
  4684. calcLength();
  4685. if (m_len == 0)
  4686. m_stringIndex++; // Empty string
  4687. }
  4688. auto operator *() const -> std::string {
  4689. assert(m_stringIndex < m_column.m_strings.size());
  4690. assert(m_pos <= m_end);
  4691. return addIndentAndSuffix(line().substr(m_pos, m_len));
  4692. }
  4693. auto operator ++() -> iterator& {
  4694. m_pos += m_len;
  4695. if (m_pos < line().size() && line()[m_pos] == '\n')
  4696. m_pos += 1;
  4697. else
  4698. while (m_pos < line().size() && isWhitespace(line()[m_pos]))
  4699. ++m_pos;
  4700. if (m_pos == line().size()) {
  4701. m_pos = 0;
  4702. ++m_stringIndex;
  4703. }
  4704. if (m_stringIndex < m_column.m_strings.size())
  4705. calcLength();
  4706. return *this;
  4707. }
  4708. auto operator ++(int) -> iterator {
  4709. iterator prev(*this);
  4710. operator++();
  4711. return prev;
  4712. }
  4713. auto operator ==(iterator const& other) const -> bool {
  4714. return
  4715. m_pos == other.m_pos &&
  4716. m_stringIndex == other.m_stringIndex &&
  4717. &m_column == &other.m_column;
  4718. }
  4719. auto operator !=(iterator const& other) const -> bool {
  4720. return !operator==(other);
  4721. }
  4722. };
  4723. using const_iterator = iterator;
  4724. explicit Column(std::string const& text) { m_strings.push_back(text); }
  4725. auto width(size_t newWidth) -> Column& {
  4726. assert(newWidth > 0);
  4727. m_width = newWidth;
  4728. return *this;
  4729. }
  4730. auto indent(size_t newIndent) -> Column& {
  4731. m_indent = newIndent;
  4732. return *this;
  4733. }
  4734. auto initialIndent(size_t newIndent) -> Column& {
  4735. m_initialIndent = newIndent;
  4736. return *this;
  4737. }
  4738. auto width() const -> size_t { return m_width; }
  4739. auto begin() const -> iterator { return iterator(*this); }
  4740. auto end() const -> iterator { return { *this, m_strings.size() }; }
  4741. inline friend std::ostream& operator << (std::ostream& os, Column const& col) {
  4742. bool first = true;
  4743. for (auto line : col) {
  4744. if (first)
  4745. first = false;
  4746. else
  4747. os << "\n";
  4748. os << line;
  4749. }
  4750. return os;
  4751. }
  4752. auto operator + (Column const& other)->Columns;
  4753. auto toString() const -> std::string {
  4754. std::ostringstream oss;
  4755. oss << *this;
  4756. return oss.str();
  4757. }
  4758. };
  4759. class Spacer : public Column {
  4760. public:
  4761. explicit Spacer(size_t spaceWidth) : Column("") {
  4762. width(spaceWidth);
  4763. }
  4764. };
  4765. class Columns {
  4766. std::vector<Column> m_columns;
  4767. public:
  4768. class iterator {
  4769. friend Columns;
  4770. struct EndTag {};
  4771. std::vector<Column> const& m_columns;
  4772. std::vector<Column::iterator> m_iterators;
  4773. size_t m_activeIterators;
  4774. iterator(Columns const& columns, EndTag)
  4775. : m_columns(columns.m_columns),
  4776. m_activeIterators(0) {
  4777. m_iterators.reserve(m_columns.size());
  4778. for (auto const& col : m_columns)
  4779. m_iterators.push_back(col.end());
  4780. }
  4781. public:
  4782. using difference_type = std::ptrdiff_t;
  4783. using value_type = std::string;
  4784. using pointer = value_type * ;
  4785. using reference = value_type & ;
  4786. using iterator_category = std::forward_iterator_tag;
  4787. explicit iterator(Columns const& columns)
  4788. : m_columns(columns.m_columns),
  4789. m_activeIterators(m_columns.size()) {
  4790. m_iterators.reserve(m_columns.size());
  4791. for (auto const& col : m_columns)
  4792. m_iterators.push_back(col.begin());
  4793. }
  4794. auto operator ==(iterator const& other) const -> bool {
  4795. return m_iterators == other.m_iterators;
  4796. }
  4797. auto operator !=(iterator const& other) const -> bool {
  4798. return m_iterators != other.m_iterators;
  4799. }
  4800. auto operator *() const -> std::string {
  4801. std::string row, padding;
  4802. for (size_t i = 0; i < m_columns.size(); ++i) {
  4803. auto width = m_columns[i].width();
  4804. if (m_iterators[i] != m_columns[i].end()) {
  4805. std::string col = *m_iterators[i];
  4806. row += padding + col;
  4807. if (col.size() < width)
  4808. padding = std::string(width - col.size(), ' ');
  4809. else
  4810. padding = "";
  4811. } else {
  4812. padding += std::string(width, ' ');
  4813. }
  4814. }
  4815. return row;
  4816. }
  4817. auto operator ++() -> iterator& {
  4818. for (size_t i = 0; i < m_columns.size(); ++i) {
  4819. if (m_iterators[i] != m_columns[i].end())
  4820. ++m_iterators[i];
  4821. }
  4822. return *this;
  4823. }
  4824. auto operator ++(int) -> iterator {
  4825. iterator prev(*this);
  4826. operator++();
  4827. return prev;
  4828. }
  4829. };
  4830. using const_iterator = iterator;
  4831. auto begin() const -> iterator { return iterator(*this); }
  4832. auto end() const -> iterator { return { *this, iterator::EndTag() }; }
  4833. auto operator += (Column const& col) -> Columns& {
  4834. m_columns.push_back(col);
  4835. return *this;
  4836. }
  4837. auto operator + (Column const& col) -> Columns {
  4838. Columns combined = *this;
  4839. combined += col;
  4840. return combined;
  4841. }
  4842. inline friend std::ostream& operator << (std::ostream& os, Columns const& cols) {
  4843. bool first = true;
  4844. for (auto line : cols) {
  4845. if (first)
  4846. first = false;
  4847. else
  4848. os << "\n";
  4849. os << line;
  4850. }
  4851. return os;
  4852. }
  4853. auto toString() const -> std::string {
  4854. std::ostringstream oss;
  4855. oss << *this;
  4856. return oss.str();
  4857. }
  4858. };
  4859. inline auto Column::operator + (Column const& other) -> Columns {
  4860. Columns cols;
  4861. cols += *this;
  4862. cols += other;
  4863. return cols;
  4864. }
  4865. }
  4866. }
  4867. }
  4868. // ----------- end of #include from clara_textflow.hpp -----------
  4869. // ........... back in clara.hpp
  4870. #include <string>
  4871. #include <memory>
  4872. #include <set>
  4873. #include <algorithm>
  4874. #if !defined(CATCH_PLATFORM_WINDOWS) && ( defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) )
  4875. #define CATCH_PLATFORM_WINDOWS
  4876. #endif
  4877. namespace Catch { namespace clara {
  4878. namespace detail {
  4879. // Traits for extracting arg and return type of lambdas (for single argument lambdas)
  4880. template<typename L>
  4881. struct UnaryLambdaTraits : UnaryLambdaTraits<decltype( &L::operator() )> {};
  4882. template<typename ClassT, typename ReturnT, typename... Args>
  4883. struct UnaryLambdaTraits<ReturnT( ClassT::* )( Args... ) const> {
  4884. static const bool isValid = false;
  4885. };
  4886. template<typename ClassT, typename ReturnT, typename ArgT>
  4887. struct UnaryLambdaTraits<ReturnT( ClassT::* )( ArgT ) const> {
  4888. static const bool isValid = true;
  4889. using ArgType = typename std::remove_const<typename std::remove_reference<ArgT>::type>::type;
  4890. using ReturnType = ReturnT;
  4891. };
  4892. class TokenStream;
  4893. // Transport for raw args (copied from main args, or supplied via init list for testing)
  4894. class Args {
  4895. friend TokenStream;
  4896. std::string m_exeName;
  4897. std::vector<std::string> m_args;
  4898. public:
  4899. Args( int argc, char const* const* argv )
  4900. : m_exeName(argv[0]),
  4901. m_args(argv + 1, argv + argc) {}
  4902. Args( std::initializer_list<std::string> args )
  4903. : m_exeName( *args.begin() ),
  4904. m_args( args.begin()+1, args.end() )
  4905. {}
  4906. auto exeName() const -> std::string {
  4907. return m_exeName;
  4908. }
  4909. };
  4910. // Wraps a token coming from a token stream. These may not directly correspond to strings as a single string
  4911. // may encode an option + its argument if the : or = form is used
  4912. enum class TokenType {
  4913. Option, Argument
  4914. };
  4915. struct Token {
  4916. TokenType type;
  4917. std::string token;
  4918. };
  4919. inline auto isOptPrefix( char c ) -> bool {
  4920. return c == '-'
  4921. #ifdef CATCH_PLATFORM_WINDOWS
  4922. || c == '/'
  4923. #endif
  4924. ;
  4925. }
  4926. // Abstracts iterators into args as a stream of tokens, with option arguments uniformly handled
  4927. class TokenStream {
  4928. using Iterator = std::vector<std::string>::const_iterator;
  4929. Iterator it;
  4930. Iterator itEnd;
  4931. std::vector<Token> m_tokenBuffer;
  4932. void loadBuffer() {
  4933. m_tokenBuffer.resize( 0 );
  4934. // Skip any empty strings
  4935. while( it != itEnd && it->empty() )
  4936. ++it;
  4937. if( it != itEnd ) {
  4938. auto const &next = *it;
  4939. if( isOptPrefix( next[0] ) ) {
  4940. auto delimiterPos = next.find_first_of( " :=" );
  4941. if( delimiterPos != std::string::npos ) {
  4942. m_tokenBuffer.push_back( { TokenType::Option, next.substr( 0, delimiterPos ) } );
  4943. m_tokenBuffer.push_back( { TokenType::Argument, next.substr( delimiterPos + 1 ) } );
  4944. } else {
  4945. if( next[1] != '-' && next.size() > 2 ) {
  4946. std::string opt = "- ";
  4947. for( size_t i = 1; i < next.size(); ++i ) {
  4948. opt[1] = next[i];
  4949. m_tokenBuffer.push_back( { TokenType::Option, opt } );
  4950. }
  4951. } else {
  4952. m_tokenBuffer.push_back( { TokenType::Option, next } );
  4953. }
  4954. }
  4955. } else {
  4956. m_tokenBuffer.push_back( { TokenType::Argument, next } );
  4957. }
  4958. }
  4959. }
  4960. public:
  4961. explicit TokenStream( Args const &args ) : TokenStream( args.m_args.begin(), args.m_args.end() ) {}
  4962. TokenStream( Iterator it, Iterator itEnd ) : it( it ), itEnd( itEnd ) {
  4963. loadBuffer();
  4964. }
  4965. explicit operator bool() const {
  4966. return !m_tokenBuffer.empty() || it != itEnd;
  4967. }
  4968. auto count() const -> size_t { return m_tokenBuffer.size() + (itEnd - it); }
  4969. auto operator*() const -> Token {
  4970. assert( !m_tokenBuffer.empty() );
  4971. return m_tokenBuffer.front();
  4972. }
  4973. auto operator->() const -> Token const * {
  4974. assert( !m_tokenBuffer.empty() );
  4975. return &m_tokenBuffer.front();
  4976. }
  4977. auto operator++() -> TokenStream & {
  4978. if( m_tokenBuffer.size() >= 2 ) {
  4979. m_tokenBuffer.erase( m_tokenBuffer.begin() );
  4980. } else {
  4981. if( it != itEnd )
  4982. ++it;
  4983. loadBuffer();
  4984. }
  4985. return *this;
  4986. }
  4987. };
  4988. class ResultBase {
  4989. public:
  4990. enum Type {
  4991. Ok, LogicError, RuntimeError
  4992. };
  4993. protected:
  4994. ResultBase( Type type ) : m_type( type ) {}
  4995. virtual ~ResultBase() = default;
  4996. virtual void enforceOk() const = 0;
  4997. Type m_type;
  4998. };
  4999. template<typename T>
  5000. class ResultValueBase : public ResultBase {
  5001. public:
  5002. auto value() const -> T const & {
  5003. enforceOk();
  5004. return m_value;
  5005. }
  5006. protected:
  5007. ResultValueBase( Type type ) : ResultBase( type ) {}
  5008. ResultValueBase( ResultValueBase const &other ) : ResultBase( other ) {
  5009. if( m_type == ResultBase::Ok )
  5010. new( &m_value ) T( other.m_value );
  5011. }
  5012. ResultValueBase( Type, T const &value ) : ResultBase( Ok ) {
  5013. new( &m_value ) T( value );
  5014. }
  5015. auto operator=( ResultValueBase const &other ) -> ResultValueBase & {
  5016. if( m_type == ResultBase::Ok )
  5017. m_value.~T();
  5018. ResultBase::operator=(other);
  5019. if( m_type == ResultBase::Ok )
  5020. new( &m_value ) T( other.m_value );
  5021. return *this;
  5022. }
  5023. ~ResultValueBase() override {
  5024. if( m_type == Ok )
  5025. m_value.~T();
  5026. }
  5027. union {
  5028. T m_value;
  5029. };
  5030. };
  5031. template<>
  5032. class ResultValueBase<void> : public ResultBase {
  5033. protected:
  5034. using ResultBase::ResultBase;
  5035. };
  5036. template<typename T = void>
  5037. class BasicResult : public ResultValueBase<T> {
  5038. public:
  5039. template<typename U>
  5040. explicit BasicResult( BasicResult<U> const &other )
  5041. : ResultValueBase<T>( other.type() ),
  5042. m_errorMessage( other.errorMessage() )
  5043. {
  5044. assert( type() != ResultBase::Ok );
  5045. }
  5046. template<typename U>
  5047. static auto ok( U const &value ) -> BasicResult { return { ResultBase::Ok, value }; }
  5048. static auto ok() -> BasicResult { return { ResultBase::Ok }; }
  5049. static auto logicError( std::string const &message ) -> BasicResult { return { ResultBase::LogicError, message }; }
  5050. static auto runtimeError( std::string const &message ) -> BasicResult { return { ResultBase::RuntimeError, message }; }
  5051. explicit operator bool() const { return m_type == ResultBase::Ok; }
  5052. auto type() const -> ResultBase::Type { return m_type; }
  5053. auto errorMessage() const -> std::string { return m_errorMessage; }
  5054. protected:
  5055. void enforceOk() const override {
  5056. // Errors shouldn't reach this point, but if they do
  5057. // the actual error message will be in m_errorMessage
  5058. assert( m_type != ResultBase::LogicError );
  5059. assert( m_type != ResultBase::RuntimeError );
  5060. if( m_type != ResultBase::Ok )
  5061. std::abort();
  5062. }
  5063. std::string m_errorMessage; // Only populated if resultType is an error
  5064. BasicResult( ResultBase::Type type, std::string const &message )
  5065. : ResultValueBase<T>(type),
  5066. m_errorMessage(message)
  5067. {
  5068. assert( m_type != ResultBase::Ok );
  5069. }
  5070. using ResultValueBase<T>::ResultValueBase;
  5071. using ResultBase::m_type;
  5072. };
  5073. enum class ParseResultType {
  5074. Matched, NoMatch, ShortCircuitAll, ShortCircuitSame
  5075. };
  5076. class ParseState {
  5077. public:
  5078. ParseState( ParseResultType type, TokenStream const &remainingTokens )
  5079. : m_type(type),
  5080. m_remainingTokens( remainingTokens )
  5081. {}
  5082. auto type() const -> ParseResultType { return m_type; }
  5083. auto remainingTokens() const -> TokenStream { return m_remainingTokens; }
  5084. private:
  5085. ParseResultType m_type;
  5086. TokenStream m_remainingTokens;
  5087. };
  5088. using Result = BasicResult<void>;
  5089. using ParserResult = BasicResult<ParseResultType>;
  5090. using InternalParseResult = BasicResult<ParseState>;
  5091. struct HelpColumns {
  5092. std::string left;
  5093. std::string right;
  5094. };
  5095. template<typename T>
  5096. inline auto convertInto( std::string const &source, T& target ) -> ParserResult {
  5097. std::stringstream ss;
  5098. ss << source;
  5099. ss >> target;
  5100. if( ss.fail() )
  5101. return ParserResult::runtimeError( "Unable to convert '" + source + "' to destination type" );
  5102. else
  5103. return ParserResult::ok( ParseResultType::Matched );
  5104. }
  5105. inline auto convertInto( std::string const &source, std::string& target ) -> ParserResult {
  5106. target = source;
  5107. return ParserResult::ok( ParseResultType::Matched );
  5108. }
  5109. inline auto convertInto( std::string const &source, bool &target ) -> ParserResult {
  5110. std::string srcLC = source;
  5111. std::transform( srcLC.begin(), srcLC.end(), srcLC.begin(), []( char c ) { return static_cast<char>( ::tolower(c) ); } );
  5112. if (srcLC == "y" || srcLC == "1" || srcLC == "true" || srcLC == "yes" || srcLC == "on")
  5113. target = true;
  5114. else if (srcLC == "n" || srcLC == "0" || srcLC == "false" || srcLC == "no" || srcLC == "off")
  5115. target = false;
  5116. else
  5117. return ParserResult::runtimeError( "Expected a boolean value but did not recognise: '" + source + "'" );
  5118. return ParserResult::ok( ParseResultType::Matched );
  5119. }
  5120. #ifdef CLARA_CONFIG_OPTIONAL_TYPE
  5121. template<typename T>
  5122. inline auto convertInto( std::string const &source, CLARA_CONFIG_OPTIONAL_TYPE<T>& target ) -> ParserResult {
  5123. T temp;
  5124. auto result = convertInto( source, temp );
  5125. if( result )
  5126. target = std::move(temp);
  5127. return result;
  5128. }
  5129. #endif // CLARA_CONFIG_OPTIONAL_TYPE
  5130. struct NonCopyable {
  5131. NonCopyable() = default;
  5132. NonCopyable( NonCopyable const & ) = delete;
  5133. NonCopyable( NonCopyable && ) = delete;
  5134. NonCopyable &operator=( NonCopyable const & ) = delete;
  5135. NonCopyable &operator=( NonCopyable && ) = delete;
  5136. };
  5137. struct BoundRef : NonCopyable {
  5138. virtual ~BoundRef() = default;
  5139. virtual auto isContainer() const -> bool { return false; }
  5140. virtual auto isFlag() const -> bool { return false; }
  5141. };
  5142. struct BoundValueRefBase : BoundRef {
  5143. virtual auto setValue( std::string const &arg ) -> ParserResult = 0;
  5144. };
  5145. struct BoundFlagRefBase : BoundRef {
  5146. virtual auto setFlag( bool flag ) -> ParserResult = 0;
  5147. virtual auto isFlag() const -> bool { return true; }
  5148. };
  5149. template<typename T>
  5150. struct BoundValueRef : BoundValueRefBase {
  5151. T &m_ref;
  5152. explicit BoundValueRef( T &ref ) : m_ref( ref ) {}
  5153. auto setValue( std::string const &arg ) -> ParserResult override {
  5154. return convertInto( arg, m_ref );
  5155. }
  5156. };
  5157. template<typename T>
  5158. struct BoundValueRef<std::vector<T>> : BoundValueRefBase {
  5159. std::vector<T> &m_ref;
  5160. explicit BoundValueRef( std::vector<T> &ref ) : m_ref( ref ) {}
  5161. auto isContainer() const -> bool override { return true; }
  5162. auto setValue( std::string const &arg ) -> ParserResult override {
  5163. T temp;
  5164. auto result = convertInto( arg, temp );
  5165. if( result )
  5166. m_ref.push_back( temp );
  5167. return result;
  5168. }
  5169. };
  5170. struct BoundFlagRef : BoundFlagRefBase {
  5171. bool &m_ref;
  5172. explicit BoundFlagRef( bool &ref ) : m_ref( ref ) {}
  5173. auto setFlag( bool flag ) -> ParserResult override {
  5174. m_ref = flag;
  5175. return ParserResult::ok( ParseResultType::Matched );
  5176. }
  5177. };
  5178. template<typename ReturnType>
  5179. struct LambdaInvoker {
  5180. static_assert( std::is_same<ReturnType, ParserResult>::value, "Lambda must return void or clara::ParserResult" );
  5181. template<typename L, typename ArgType>
  5182. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  5183. return lambda( arg );
  5184. }
  5185. };
  5186. template<>
  5187. struct LambdaInvoker<void> {
  5188. template<typename L, typename ArgType>
  5189. static auto invoke( L const &lambda, ArgType const &arg ) -> ParserResult {
  5190. lambda( arg );
  5191. return ParserResult::ok( ParseResultType::Matched );
  5192. }
  5193. };
  5194. template<typename ArgType, typename L>
  5195. inline auto invokeLambda( L const &lambda, std::string const &arg ) -> ParserResult {
  5196. ArgType temp{};
  5197. auto result = convertInto( arg, temp );
  5198. return !result
  5199. ? result
  5200. : LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( lambda, temp );
  5201. }
  5202. template<typename L>
  5203. struct BoundLambda : BoundValueRefBase {
  5204. L m_lambda;
  5205. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  5206. explicit BoundLambda( L const &lambda ) : m_lambda( lambda ) {}
  5207. auto setValue( std::string const &arg ) -> ParserResult override {
  5208. return invokeLambda<typename UnaryLambdaTraits<L>::ArgType>( m_lambda, arg );
  5209. }
  5210. };
  5211. template<typename L>
  5212. struct BoundFlagLambda : BoundFlagRefBase {
  5213. L m_lambda;
  5214. static_assert( UnaryLambdaTraits<L>::isValid, "Supplied lambda must take exactly one argument" );
  5215. static_assert( std::is_same<typename UnaryLambdaTraits<L>::ArgType, bool>::value, "flags must be boolean" );
  5216. explicit BoundFlagLambda( L const &lambda ) : m_lambda( lambda ) {}
  5217. auto setFlag( bool flag ) -> ParserResult override {
  5218. return LambdaInvoker<typename UnaryLambdaTraits<L>::ReturnType>::invoke( m_lambda, flag );
  5219. }
  5220. };
  5221. enum class Optionality { Optional, Required };
  5222. struct Parser;
  5223. class ParserBase {
  5224. public:
  5225. virtual ~ParserBase() = default;
  5226. virtual auto validate() const -> Result { return Result::ok(); }
  5227. virtual auto parse( std::string const& exeName, TokenStream const &tokens) const -> InternalParseResult = 0;
  5228. virtual auto cardinality() const -> size_t { return 1; }
  5229. auto parse( Args const &args ) const -> InternalParseResult {
  5230. return parse( args.exeName(), TokenStream( args ) );
  5231. }
  5232. };
  5233. template<typename DerivedT>
  5234. class ComposableParserImpl : public ParserBase {
  5235. public:
  5236. template<typename T>
  5237. auto operator|( T const &other ) const -> Parser;
  5238. template<typename T>
  5239. auto operator+( T const &other ) const -> Parser;
  5240. };
  5241. // Common code and state for Args and Opts
  5242. template<typename DerivedT>
  5243. class ParserRefImpl : public ComposableParserImpl<DerivedT> {
  5244. protected:
  5245. Optionality m_optionality = Optionality::Optional;
  5246. std::shared_ptr<BoundRef> m_ref;
  5247. std::string m_hint;
  5248. std::string m_description;
  5249. explicit ParserRefImpl( std::shared_ptr<BoundRef> const &ref ) : m_ref( ref ) {}
  5250. public:
  5251. template<typename T>
  5252. ParserRefImpl( T &ref, std::string const &hint )
  5253. : m_ref( std::make_shared<BoundValueRef<T>>( ref ) ),
  5254. m_hint( hint )
  5255. {}
  5256. template<typename LambdaT>
  5257. ParserRefImpl( LambdaT const &ref, std::string const &hint )
  5258. : m_ref( std::make_shared<BoundLambda<LambdaT>>( ref ) ),
  5259. m_hint(hint)
  5260. {}
  5261. auto operator()( std::string const &description ) -> DerivedT & {
  5262. m_description = description;
  5263. return static_cast<DerivedT &>( *this );
  5264. }
  5265. auto optional() -> DerivedT & {
  5266. m_optionality = Optionality::Optional;
  5267. return static_cast<DerivedT &>( *this );
  5268. };
  5269. auto required() -> DerivedT & {
  5270. m_optionality = Optionality::Required;
  5271. return static_cast<DerivedT &>( *this );
  5272. };
  5273. auto isOptional() const -> bool {
  5274. return m_optionality == Optionality::Optional;
  5275. }
  5276. auto cardinality() const -> size_t override {
  5277. if( m_ref->isContainer() )
  5278. return 0;
  5279. else
  5280. return 1;
  5281. }
  5282. auto hint() const -> std::string { return m_hint; }
  5283. };
  5284. class ExeName : public ComposableParserImpl<ExeName> {
  5285. std::shared_ptr<std::string> m_name;
  5286. std::shared_ptr<BoundValueRefBase> m_ref;
  5287. template<typename LambdaT>
  5288. static auto makeRef(LambdaT const &lambda) -> std::shared_ptr<BoundValueRefBase> {
  5289. return std::make_shared<BoundLambda<LambdaT>>( lambda) ;
  5290. }
  5291. public:
  5292. ExeName() : m_name( std::make_shared<std::string>( "<executable>" ) ) {}
  5293. explicit ExeName( std::string &ref ) : ExeName() {
  5294. m_ref = std::make_shared<BoundValueRef<std::string>>( ref );
  5295. }
  5296. template<typename LambdaT>
  5297. explicit ExeName( LambdaT const& lambda ) : ExeName() {
  5298. m_ref = std::make_shared<BoundLambda<LambdaT>>( lambda );
  5299. }
  5300. // The exe name is not parsed out of the normal tokens, but is handled specially
  5301. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  5302. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  5303. }
  5304. auto name() const -> std::string { return *m_name; }
  5305. auto set( std::string const& newName ) -> ParserResult {
  5306. auto lastSlash = newName.find_last_of( "\\/" );
  5307. auto filename = ( lastSlash == std::string::npos )
  5308. ? newName
  5309. : newName.substr( lastSlash+1 );
  5310. *m_name = filename;
  5311. if( m_ref )
  5312. return m_ref->setValue( filename );
  5313. else
  5314. return ParserResult::ok( ParseResultType::Matched );
  5315. }
  5316. };
  5317. class Arg : public ParserRefImpl<Arg> {
  5318. public:
  5319. using ParserRefImpl::ParserRefImpl;
  5320. auto parse( std::string const &, TokenStream const &tokens ) const -> InternalParseResult override {
  5321. auto validationResult = validate();
  5322. if( !validationResult )
  5323. return InternalParseResult( validationResult );
  5324. auto remainingTokens = tokens;
  5325. auto const &token = *remainingTokens;
  5326. if( token.type != TokenType::Argument )
  5327. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  5328. assert( !m_ref->isFlag() );
  5329. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  5330. auto result = valueRef->setValue( remainingTokens->token );
  5331. if( !result )
  5332. return InternalParseResult( result );
  5333. else
  5334. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  5335. }
  5336. };
  5337. inline auto normaliseOpt( std::string const &optName ) -> std::string {
  5338. #ifdef CATCH_PLATFORM_WINDOWS
  5339. if( optName[0] == '/' )
  5340. return "-" + optName.substr( 1 );
  5341. else
  5342. #endif
  5343. return optName;
  5344. }
  5345. class Opt : public ParserRefImpl<Opt> {
  5346. protected:
  5347. std::vector<std::string> m_optNames;
  5348. public:
  5349. template<typename LambdaT>
  5350. explicit Opt( LambdaT const &ref ) : ParserRefImpl( std::make_shared<BoundFlagLambda<LambdaT>>( ref ) ) {}
  5351. explicit Opt( bool &ref ) : ParserRefImpl( std::make_shared<BoundFlagRef>( ref ) ) {}
  5352. template<typename LambdaT>
  5353. Opt( LambdaT const &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  5354. template<typename T>
  5355. Opt( T &ref, std::string const &hint ) : ParserRefImpl( ref, hint ) {}
  5356. auto operator[]( std::string const &optName ) -> Opt & {
  5357. m_optNames.push_back( optName );
  5358. return *this;
  5359. }
  5360. auto getHelpColumns() const -> std::vector<HelpColumns> {
  5361. std::ostringstream oss;
  5362. bool first = true;
  5363. for( auto const &opt : m_optNames ) {
  5364. if (first)
  5365. first = false;
  5366. else
  5367. oss << ", ";
  5368. oss << opt;
  5369. }
  5370. if( !m_hint.empty() )
  5371. oss << " <" << m_hint << ">";
  5372. return { { oss.str(), m_description } };
  5373. }
  5374. auto isMatch( std::string const &optToken ) const -> bool {
  5375. auto normalisedToken = normaliseOpt( optToken );
  5376. for( auto const &name : m_optNames ) {
  5377. if( normaliseOpt( name ) == normalisedToken )
  5378. return true;
  5379. }
  5380. return false;
  5381. }
  5382. using ParserBase::parse;
  5383. auto parse( std::string const&, TokenStream const &tokens ) const -> InternalParseResult override {
  5384. auto validationResult = validate();
  5385. if( !validationResult )
  5386. return InternalParseResult( validationResult );
  5387. auto remainingTokens = tokens;
  5388. if( remainingTokens && remainingTokens->type == TokenType::Option ) {
  5389. auto const &token = *remainingTokens;
  5390. if( isMatch(token.token ) ) {
  5391. if( m_ref->isFlag() ) {
  5392. auto flagRef = static_cast<detail::BoundFlagRefBase*>( m_ref.get() );
  5393. auto result = flagRef->setFlag( true );
  5394. if( !result )
  5395. return InternalParseResult( result );
  5396. if( result.value() == ParseResultType::ShortCircuitAll )
  5397. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  5398. } else {
  5399. auto valueRef = static_cast<detail::BoundValueRefBase*>( m_ref.get() );
  5400. ++remainingTokens;
  5401. if( !remainingTokens )
  5402. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  5403. auto const &argToken = *remainingTokens;
  5404. if( argToken.type != TokenType::Argument )
  5405. return InternalParseResult::runtimeError( "Expected argument following " + token.token );
  5406. auto result = valueRef->setValue( argToken.token );
  5407. if( !result )
  5408. return InternalParseResult( result );
  5409. if( result.value() == ParseResultType::ShortCircuitAll )
  5410. return InternalParseResult::ok( ParseState( result.value(), remainingTokens ) );
  5411. }
  5412. return InternalParseResult::ok( ParseState( ParseResultType::Matched, ++remainingTokens ) );
  5413. }
  5414. }
  5415. return InternalParseResult::ok( ParseState( ParseResultType::NoMatch, remainingTokens ) );
  5416. }
  5417. auto validate() const -> Result override {
  5418. if( m_optNames.empty() )
  5419. return Result::logicError( "No options supplied to Opt" );
  5420. for( auto const &name : m_optNames ) {
  5421. if( name.empty() )
  5422. return Result::logicError( "Option name cannot be empty" );
  5423. #ifdef CATCH_PLATFORM_WINDOWS
  5424. if( name[0] != '-' && name[0] != '/' )
  5425. return Result::logicError( "Option name must begin with '-' or '/'" );
  5426. #else
  5427. if( name[0] != '-' )
  5428. return Result::logicError( "Option name must begin with '-'" );
  5429. #endif
  5430. }
  5431. return ParserRefImpl::validate();
  5432. }
  5433. };
  5434. struct Help : Opt {
  5435. Help( bool &showHelpFlag )
  5436. : Opt([&]( bool flag ) {
  5437. showHelpFlag = flag;
  5438. return ParserResult::ok( ParseResultType::ShortCircuitAll );
  5439. })
  5440. {
  5441. static_cast<Opt &>( *this )
  5442. ("display usage information")
  5443. ["-?"]["-h"]["--help"]
  5444. .optional();
  5445. }
  5446. };
  5447. struct Parser : ParserBase {
  5448. mutable ExeName m_exeName;
  5449. std::vector<Opt> m_options;
  5450. std::vector<Arg> m_args;
  5451. auto operator|=( ExeName const &exeName ) -> Parser & {
  5452. m_exeName = exeName;
  5453. return *this;
  5454. }
  5455. auto operator|=( Arg const &arg ) -> Parser & {
  5456. m_args.push_back(arg);
  5457. return *this;
  5458. }
  5459. auto operator|=( Opt const &opt ) -> Parser & {
  5460. m_options.push_back(opt);
  5461. return *this;
  5462. }
  5463. auto operator|=( Parser const &other ) -> Parser & {
  5464. m_options.insert(m_options.end(), other.m_options.begin(), other.m_options.end());
  5465. m_args.insert(m_args.end(), other.m_args.begin(), other.m_args.end());
  5466. return *this;
  5467. }
  5468. template<typename T>
  5469. auto operator|( T const &other ) const -> Parser {
  5470. return Parser( *this ) |= other;
  5471. }
  5472. // Forward deprecated interface with '+' instead of '|'
  5473. template<typename T>
  5474. auto operator+=( T const &other ) -> Parser & { return operator|=( other ); }
  5475. template<typename T>
  5476. auto operator+( T const &other ) const -> Parser { return operator|( other ); }
  5477. auto getHelpColumns() const -> std::vector<HelpColumns> {
  5478. std::vector<HelpColumns> cols;
  5479. for (auto const &o : m_options) {
  5480. auto childCols = o.getHelpColumns();
  5481. cols.insert( cols.end(), childCols.begin(), childCols.end() );
  5482. }
  5483. return cols;
  5484. }
  5485. void writeToStream( std::ostream &os ) const {
  5486. if (!m_exeName.name().empty()) {
  5487. os << "usage:\n" << " " << m_exeName.name() << " ";
  5488. bool required = true, first = true;
  5489. for( auto const &arg : m_args ) {
  5490. if (first)
  5491. first = false;
  5492. else
  5493. os << " ";
  5494. if( arg.isOptional() && required ) {
  5495. os << "[";
  5496. required = false;
  5497. }
  5498. os << "<" << arg.hint() << ">";
  5499. if( arg.cardinality() == 0 )
  5500. os << " ... ";
  5501. }
  5502. if( !required )
  5503. os << "]";
  5504. if( !m_options.empty() )
  5505. os << " options";
  5506. os << "\n\nwhere options are:" << std::endl;
  5507. }
  5508. auto rows = getHelpColumns();
  5509. size_t consoleWidth = CATCH_CLARA_CONFIG_CONSOLE_WIDTH;
  5510. size_t optWidth = 0;
  5511. for( auto const &cols : rows )
  5512. optWidth = (std::max)(optWidth, cols.left.size() + 2);
  5513. optWidth = (std::min)(optWidth, consoleWidth/2);
  5514. for( auto const &cols : rows ) {
  5515. auto row =
  5516. TextFlow::Column( cols.left ).width( optWidth ).indent( 2 ) +
  5517. TextFlow::Spacer(4) +
  5518. TextFlow::Column( cols.right ).width( consoleWidth - 7 - optWidth );
  5519. os << row << std::endl;
  5520. }
  5521. }
  5522. friend auto operator<<( std::ostream &os, Parser const &parser ) -> std::ostream& {
  5523. parser.writeToStream( os );
  5524. return os;
  5525. }
  5526. auto validate() const -> Result override {
  5527. for( auto const &opt : m_options ) {
  5528. auto result = opt.validate();
  5529. if( !result )
  5530. return result;
  5531. }
  5532. for( auto const &arg : m_args ) {
  5533. auto result = arg.validate();
  5534. if( !result )
  5535. return result;
  5536. }
  5537. return Result::ok();
  5538. }
  5539. using ParserBase::parse;
  5540. auto parse( std::string const& exeName, TokenStream const &tokens ) const -> InternalParseResult override {
  5541. struct ParserInfo {
  5542. ParserBase const* parser = nullptr;
  5543. size_t count = 0;
  5544. };
  5545. const size_t totalParsers = m_options.size() + m_args.size();
  5546. assert( totalParsers < 512 );
  5547. // ParserInfo parseInfos[totalParsers]; // <-- this is what we really want to do
  5548. ParserInfo parseInfos[512];
  5549. {
  5550. size_t i = 0;
  5551. for (auto const &opt : m_options) parseInfos[i++].parser = &opt;
  5552. for (auto const &arg : m_args) parseInfos[i++].parser = &arg;
  5553. }
  5554. m_exeName.set( exeName );
  5555. auto result = InternalParseResult::ok( ParseState( ParseResultType::NoMatch, tokens ) );
  5556. while( result.value().remainingTokens() ) {
  5557. bool tokenParsed = false;
  5558. for( size_t i = 0; i < totalParsers; ++i ) {
  5559. auto& parseInfo = parseInfos[i];
  5560. if( parseInfo.parser->cardinality() == 0 || parseInfo.count < parseInfo.parser->cardinality() ) {
  5561. result = parseInfo.parser->parse(exeName, result.value().remainingTokens());
  5562. if (!result)
  5563. return result;
  5564. if (result.value().type() != ParseResultType::NoMatch) {
  5565. tokenParsed = true;
  5566. ++parseInfo.count;
  5567. break;
  5568. }
  5569. }
  5570. }
  5571. if( result.value().type() == ParseResultType::ShortCircuitAll )
  5572. return result;
  5573. if( !tokenParsed )
  5574. return InternalParseResult::runtimeError( "Unrecognised token: " + result.value().remainingTokens()->token );
  5575. }
  5576. // !TBD Check missing required options
  5577. return result;
  5578. }
  5579. };
  5580. template<typename DerivedT>
  5581. template<typename T>
  5582. auto ComposableParserImpl<DerivedT>::operator|( T const &other ) const -> Parser {
  5583. return Parser() | static_cast<DerivedT const &>( *this ) | other;
  5584. }
  5585. } // namespace detail
  5586. // A Combined parser
  5587. using detail::Parser;
  5588. // A parser for options
  5589. using detail::Opt;
  5590. // A parser for arguments
  5591. using detail::Arg;
  5592. // Wrapper for argc, argv from main()
  5593. using detail::Args;
  5594. // Specifies the name of the executable
  5595. using detail::ExeName;
  5596. // Convenience wrapper for option parser that specifies the help option
  5597. using detail::Help;
  5598. // enum of result types from a parse
  5599. using detail::ParseResultType;
  5600. // Result type for parser operation
  5601. using detail::ParserResult;
  5602. }} // namespace Catch::clara
  5603. // end clara.hpp
  5604. #ifdef __clang__
  5605. #pragma clang diagnostic pop
  5606. #endif
  5607. // Restore Clara's value for console width, if present
  5608. #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5609. #define CATCH_CLARA_TEXTFLOW_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5610. #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH
  5611. #endif
  5612. // end catch_clara.h
  5613. namespace Catch {
  5614. clara::Parser makeCommandLineParser( ConfigData& config );
  5615. } // end namespace Catch
  5616. // end catch_commandline.h
  5617. #include <fstream>
  5618. #include <ctime>
  5619. namespace Catch {
  5620. clara::Parser makeCommandLineParser( ConfigData& config ) {
  5621. using namespace clara;
  5622. auto const setWarning = [&]( std::string const& warning ) {
  5623. auto warningSet = [&]() {
  5624. if( warning == "NoAssertions" )
  5625. return WarnAbout::NoAssertions;
  5626. if ( warning == "NoTests" )
  5627. return WarnAbout::NoTests;
  5628. return WarnAbout::Nothing;
  5629. }();
  5630. if (warningSet == WarnAbout::Nothing)
  5631. return ParserResult::runtimeError( "Unrecognised warning: '" + warning + "'" );
  5632. config.warnings = static_cast<WarnAbout::What>( config.warnings | warningSet );
  5633. return ParserResult::ok( ParseResultType::Matched );
  5634. };
  5635. auto const loadTestNamesFromFile = [&]( std::string const& filename ) {
  5636. std::ifstream f( filename.c_str() );
  5637. if( !f.is_open() )
  5638. return ParserResult::runtimeError( "Unable to load input file: '" + filename + "'" );
  5639. std::string line;
  5640. while( std::getline( f, line ) ) {
  5641. line = trim(line);
  5642. if( !line.empty() && !startsWith( line, '#' ) ) {
  5643. if( !startsWith( line, '"' ) )
  5644. line = '"' + line + '"';
  5645. config.testsOrTags.push_back( line + ',' );
  5646. }
  5647. }
  5648. return ParserResult::ok( ParseResultType::Matched );
  5649. };
  5650. auto const setTestOrder = [&]( std::string const& order ) {
  5651. if( startsWith( "declared", order ) )
  5652. config.runOrder = RunTests::InDeclarationOrder;
  5653. else if( startsWith( "lexical", order ) )
  5654. config.runOrder = RunTests::InLexicographicalOrder;
  5655. else if( startsWith( "random", order ) )
  5656. config.runOrder = RunTests::InRandomOrder;
  5657. else
  5658. return clara::ParserResult::runtimeError( "Unrecognised ordering: '" + order + "'" );
  5659. return ParserResult::ok( ParseResultType::Matched );
  5660. };
  5661. auto const setRngSeed = [&]( std::string const& seed ) {
  5662. if( seed != "time" )
  5663. return clara::detail::convertInto( seed, config.rngSeed );
  5664. config.rngSeed = static_cast<unsigned int>( std::time(nullptr) );
  5665. return ParserResult::ok( ParseResultType::Matched );
  5666. };
  5667. auto const setColourUsage = [&]( std::string const& useColour ) {
  5668. auto mode = toLower( useColour );
  5669. if( mode == "yes" )
  5670. config.useColour = UseColour::Yes;
  5671. else if( mode == "no" )
  5672. config.useColour = UseColour::No;
  5673. else if( mode == "auto" )
  5674. config.useColour = UseColour::Auto;
  5675. else
  5676. return ParserResult::runtimeError( "colour mode must be one of: auto, yes or no. '" + useColour + "' not recognised" );
  5677. return ParserResult::ok( ParseResultType::Matched );
  5678. };
  5679. auto const setWaitForKeypress = [&]( std::string const& keypress ) {
  5680. auto keypressLc = toLower( keypress );
  5681. if( keypressLc == "start" )
  5682. config.waitForKeypress = WaitForKeypress::BeforeStart;
  5683. else if( keypressLc == "exit" )
  5684. config.waitForKeypress = WaitForKeypress::BeforeExit;
  5685. else if( keypressLc == "both" )
  5686. config.waitForKeypress = WaitForKeypress::BeforeStartAndExit;
  5687. else
  5688. return ParserResult::runtimeError( "keypress argument must be one of: start, exit or both. '" + keypress + "' not recognised" );
  5689. return ParserResult::ok( ParseResultType::Matched );
  5690. };
  5691. auto const setVerbosity = [&]( std::string const& verbosity ) {
  5692. auto lcVerbosity = toLower( verbosity );
  5693. if( lcVerbosity == "quiet" )
  5694. config.verbosity = Verbosity::Quiet;
  5695. else if( lcVerbosity == "normal" )
  5696. config.verbosity = Verbosity::Normal;
  5697. else if( lcVerbosity == "high" )
  5698. config.verbosity = Verbosity::High;
  5699. else
  5700. return ParserResult::runtimeError( "Unrecognised verbosity, '" + verbosity + "'" );
  5701. return ParserResult::ok( ParseResultType::Matched );
  5702. };
  5703. auto const setReporter = [&]( std::string const& reporter ) {
  5704. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  5705. auto lcReporter = toLower( reporter );
  5706. auto result = factories.find( lcReporter );
  5707. if( factories.end() != result )
  5708. config.reporterName = lcReporter;
  5709. else
  5710. return ParserResult::runtimeError( "Unrecognized reporter, '" + reporter + "'. Check available with --list-reporters" );
  5711. return ParserResult::ok( ParseResultType::Matched );
  5712. };
  5713. auto cli
  5714. = ExeName( config.processName )
  5715. | Help( config.showHelp )
  5716. | Opt( config.listTests )
  5717. ["-l"]["--list-tests"]
  5718. ( "list all/matching test cases" )
  5719. | Opt( config.listTags )
  5720. ["-t"]["--list-tags"]
  5721. ( "list all/matching tags" )
  5722. | Opt( config.showSuccessfulTests )
  5723. ["-s"]["--success"]
  5724. ( "include successful tests in output" )
  5725. | Opt( config.shouldDebugBreak )
  5726. ["-b"]["--break"]
  5727. ( "break into debugger on failure" )
  5728. | Opt( config.noThrow )
  5729. ["-e"]["--nothrow"]
  5730. ( "skip exception tests" )
  5731. | Opt( config.showInvisibles )
  5732. ["-i"]["--invisibles"]
  5733. ( "show invisibles (tabs, newlines)" )
  5734. | Opt( config.outputFilename, "filename" )
  5735. ["-o"]["--out"]
  5736. ( "output filename" )
  5737. | Opt( setReporter, "name" )
  5738. ["-r"]["--reporter"]
  5739. ( "reporter to use (defaults to console)" )
  5740. | Opt( config.name, "name" )
  5741. ["-n"]["--name"]
  5742. ( "suite name" )
  5743. | Opt( [&]( bool ){ config.abortAfter = 1; } )
  5744. ["-a"]["--abort"]
  5745. ( "abort at first failure" )
  5746. | Opt( [&]( int x ){ config.abortAfter = x; }, "no. failures" )
  5747. ["-x"]["--abortx"]
  5748. ( "abort after x failures" )
  5749. | Opt( setWarning, "warning name" )
  5750. ["-w"]["--warn"]
  5751. ( "enable warnings" )
  5752. | Opt( [&]( bool flag ) { config.showDurations = flag ? ShowDurations::Always : ShowDurations::Never; }, "yes|no" )
  5753. ["-d"]["--durations"]
  5754. ( "show test durations" )
  5755. | Opt( loadTestNamesFromFile, "filename" )
  5756. ["-f"]["--input-file"]
  5757. ( "load test names to run from a file" )
  5758. | Opt( config.filenamesAsTags )
  5759. ["-#"]["--filenames-as-tags"]
  5760. ( "adds a tag for the filename" )
  5761. | Opt( config.sectionsToRun, "section name" )
  5762. ["-c"]["--section"]
  5763. ( "specify section to run" )
  5764. | Opt( setVerbosity, "quiet|normal|high" )
  5765. ["-v"]["--verbosity"]
  5766. ( "set output verbosity" )
  5767. | Opt( config.listTestNamesOnly )
  5768. ["--list-test-names-only"]
  5769. ( "list all/matching test cases names only" )
  5770. | Opt( config.listReporters )
  5771. ["--list-reporters"]
  5772. ( "list all reporters" )
  5773. | Opt( setTestOrder, "decl|lex|rand" )
  5774. ["--order"]
  5775. ( "test case order (defaults to decl)" )
  5776. | Opt( setRngSeed, "'time'|number" )
  5777. ["--rng-seed"]
  5778. ( "set a specific seed for random numbers" )
  5779. | Opt( setColourUsage, "yes|no" )
  5780. ["--use-colour"]
  5781. ( "should output be colourised" )
  5782. | Opt( config.libIdentify )
  5783. ["--libidentify"]
  5784. ( "report name and version according to libidentify standard" )
  5785. | Opt( setWaitForKeypress, "start|exit|both" )
  5786. ["--wait-for-keypress"]
  5787. ( "waits for a keypress before exiting" )
  5788. | Opt( config.benchmarkResolutionMultiple, "multiplier" )
  5789. ["--benchmark-resolution-multiple"]
  5790. ( "multiple of clock resolution to run benchmarks" )
  5791. | Arg( config.testsOrTags, "test name|pattern|tags" )
  5792. ( "which test or tests to use" );
  5793. return cli;
  5794. }
  5795. } // end namespace Catch
  5796. // end catch_commandline.cpp
  5797. // start catch_common.cpp
  5798. #include <cstring>
  5799. #include <ostream>
  5800. namespace Catch {
  5801. bool SourceLineInfo::empty() const noexcept {
  5802. return file[0] == '\0';
  5803. }
  5804. bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const noexcept {
  5805. return line == other.line && (file == other.file || std::strcmp(file, other.file) == 0);
  5806. }
  5807. bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const noexcept {
  5808. // We can assume that the same file will usually have the same pointer.
  5809. // Thus, if the pointers are the same, there is no point in calling the strcmp
  5810. return line < other.line || ( line == other.line && file != other.file && (std::strcmp(file, other.file) < 0));
  5811. }
  5812. std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) {
  5813. #ifndef __GNUG__
  5814. os << info.file << '(' << info.line << ')';
  5815. #else
  5816. os << info.file << ':' << info.line;
  5817. #endif
  5818. return os;
  5819. }
  5820. std::string StreamEndStop::operator+() const {
  5821. return std::string();
  5822. }
  5823. NonCopyable::NonCopyable() = default;
  5824. NonCopyable::~NonCopyable() = default;
  5825. }
  5826. // end catch_common.cpp
  5827. // start catch_config.cpp
  5828. namespace Catch {
  5829. Config::Config( ConfigData const& data )
  5830. : m_data( data ),
  5831. m_stream( openStream() )
  5832. {
  5833. TestSpecParser parser(ITagAliasRegistry::get());
  5834. if (data.testsOrTags.empty()) {
  5835. parser.parse("~[.]"); // All not hidden tests
  5836. }
  5837. else {
  5838. m_hasTestFilters = true;
  5839. for( auto const& testOrTags : data.testsOrTags )
  5840. parser.parse( testOrTags );
  5841. }
  5842. m_testSpec = parser.testSpec();
  5843. }
  5844. std::string const& Config::getFilename() const {
  5845. return m_data.outputFilename ;
  5846. }
  5847. bool Config::listTests() const { return m_data.listTests; }
  5848. bool Config::listTestNamesOnly() const { return m_data.listTestNamesOnly; }
  5849. bool Config::listTags() const { return m_data.listTags; }
  5850. bool Config::listReporters() const { return m_data.listReporters; }
  5851. std::string Config::getProcessName() const { return m_data.processName; }
  5852. std::string const& Config::getReporterName() const { return m_data.reporterName; }
  5853. std::vector<std::string> const& Config::getTestsOrTags() const { return m_data.testsOrTags; }
  5854. std::vector<std::string> const& Config::getSectionsToRun() const { return m_data.sectionsToRun; }
  5855. TestSpec const& Config::testSpec() const { return m_testSpec; }
  5856. bool Config::hasTestFilters() const { return m_hasTestFilters; }
  5857. bool Config::showHelp() const { return m_data.showHelp; }
  5858. // IConfig interface
  5859. bool Config::allowThrows() const { return !m_data.noThrow; }
  5860. std::ostream& Config::stream() const { return m_stream->stream(); }
  5861. std::string Config::name() const { return m_data.name.empty() ? m_data.processName : m_data.name; }
  5862. bool Config::includeSuccessfulResults() const { return m_data.showSuccessfulTests; }
  5863. bool Config::warnAboutMissingAssertions() const { return !!(m_data.warnings & WarnAbout::NoAssertions); }
  5864. bool Config::warnAboutNoTests() const { return !!(m_data.warnings & WarnAbout::NoTests); }
  5865. ShowDurations::OrNot Config::showDurations() const { return m_data.showDurations; }
  5866. RunTests::InWhatOrder Config::runOrder() const { return m_data.runOrder; }
  5867. unsigned int Config::rngSeed() const { return m_data.rngSeed; }
  5868. int Config::benchmarkResolutionMultiple() const { return m_data.benchmarkResolutionMultiple; }
  5869. UseColour::YesOrNo Config::useColour() const { return m_data.useColour; }
  5870. bool Config::shouldDebugBreak() const { return m_data.shouldDebugBreak; }
  5871. int Config::abortAfter() const { return m_data.abortAfter; }
  5872. bool Config::showInvisibles() const { return m_data.showInvisibles; }
  5873. Verbosity Config::verbosity() const { return m_data.verbosity; }
  5874. IStream const* Config::openStream() {
  5875. return Catch::makeStream(m_data.outputFilename);
  5876. }
  5877. } // end namespace Catch
  5878. // end catch_config.cpp
  5879. // start catch_console_colour.cpp
  5880. #if defined(__clang__)
  5881. # pragma clang diagnostic push
  5882. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  5883. #endif
  5884. // start catch_errno_guard.h
  5885. namespace Catch {
  5886. class ErrnoGuard {
  5887. public:
  5888. ErrnoGuard();
  5889. ~ErrnoGuard();
  5890. private:
  5891. int m_oldErrno;
  5892. };
  5893. }
  5894. // end catch_errno_guard.h
  5895. #include <sstream>
  5896. namespace Catch {
  5897. namespace {
  5898. struct IColourImpl {
  5899. virtual ~IColourImpl() = default;
  5900. virtual void use( Colour::Code _colourCode ) = 0;
  5901. };
  5902. struct NoColourImpl : IColourImpl {
  5903. void use( Colour::Code ) {}
  5904. static IColourImpl* instance() {
  5905. static NoColourImpl s_instance;
  5906. return &s_instance;
  5907. }
  5908. };
  5909. } // anon namespace
  5910. } // namespace Catch
  5911. #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI )
  5912. # ifdef CATCH_PLATFORM_WINDOWS
  5913. # define CATCH_CONFIG_COLOUR_WINDOWS
  5914. # else
  5915. # define CATCH_CONFIG_COLOUR_ANSI
  5916. # endif
  5917. #endif
  5918. #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) /////////////////////////////////////////
  5919. namespace Catch {
  5920. namespace {
  5921. class Win32ColourImpl : public IColourImpl {
  5922. public:
  5923. Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) )
  5924. {
  5925. CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
  5926. GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo );
  5927. originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY );
  5928. originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY );
  5929. }
  5930. virtual void use( Colour::Code _colourCode ) override {
  5931. switch( _colourCode ) {
  5932. case Colour::None: return setTextAttribute( originalForegroundAttributes );
  5933. case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5934. case Colour::Red: return setTextAttribute( FOREGROUND_RED );
  5935. case Colour::Green: return setTextAttribute( FOREGROUND_GREEN );
  5936. case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE );
  5937. case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN );
  5938. case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN );
  5939. case Colour::Grey: return setTextAttribute( 0 );
  5940. case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY );
  5941. case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED );
  5942. case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN );
  5943. case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE );
  5944. case Colour::BrightYellow: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN );
  5945. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5946. default:
  5947. CATCH_ERROR( "Unknown colour requested" );
  5948. }
  5949. }
  5950. private:
  5951. void setTextAttribute( WORD _textAttribute ) {
  5952. SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes );
  5953. }
  5954. HANDLE stdoutHandle;
  5955. WORD originalForegroundAttributes;
  5956. WORD originalBackgroundAttributes;
  5957. };
  5958. IColourImpl* platformColourInstance() {
  5959. static Win32ColourImpl s_instance;
  5960. IConfigPtr config = getCurrentContext().getConfig();
  5961. UseColour::YesOrNo colourMode = config
  5962. ? config->useColour()
  5963. : UseColour::Auto;
  5964. if( colourMode == UseColour::Auto )
  5965. colourMode = UseColour::Yes;
  5966. return colourMode == UseColour::Yes
  5967. ? &s_instance
  5968. : NoColourImpl::instance();
  5969. }
  5970. } // end anon namespace
  5971. } // end namespace Catch
  5972. #elif defined( CATCH_CONFIG_COLOUR_ANSI ) //////////////////////////////////////
  5973. #include <unistd.h>
  5974. namespace Catch {
  5975. namespace {
  5976. // use POSIX/ ANSI console terminal codes
  5977. // Thanks to Adam Strzelecki for original contribution
  5978. // (http://github.com/nanoant)
  5979. // https://github.com/philsquared/Catch/pull/131
  5980. class PosixColourImpl : public IColourImpl {
  5981. public:
  5982. virtual void use( Colour::Code _colourCode ) override {
  5983. switch( _colourCode ) {
  5984. case Colour::None:
  5985. case Colour::White: return setColour( "[0m" );
  5986. case Colour::Red: return setColour( "[0;31m" );
  5987. case Colour::Green: return setColour( "[0;32m" );
  5988. case Colour::Blue: return setColour( "[0;34m" );
  5989. case Colour::Cyan: return setColour( "[0;36m" );
  5990. case Colour::Yellow: return setColour( "[0;33m" );
  5991. case Colour::Grey: return setColour( "[1;30m" );
  5992. case Colour::LightGrey: return setColour( "[0;37m" );
  5993. case Colour::BrightRed: return setColour( "[1;31m" );
  5994. case Colour::BrightGreen: return setColour( "[1;32m" );
  5995. case Colour::BrightWhite: return setColour( "[1;37m" );
  5996. case Colour::BrightYellow: return setColour( "[1;33m" );
  5997. case Colour::Bright: CATCH_INTERNAL_ERROR( "not a colour" );
  5998. default: CATCH_INTERNAL_ERROR( "Unknown colour requested" );
  5999. }
  6000. }
  6001. static IColourImpl* instance() {
  6002. static PosixColourImpl s_instance;
  6003. return &s_instance;
  6004. }
  6005. private:
  6006. void setColour( const char* _escapeCode ) {
  6007. Catch::cout() << '\033' << _escapeCode;
  6008. }
  6009. };
  6010. bool useColourOnPlatform() {
  6011. return
  6012. #ifdef CATCH_PLATFORM_MAC
  6013. !isDebuggerActive() &&
  6014. #endif
  6015. #if !(defined(__DJGPP__) && defined(__STRICT_ANSI__))
  6016. isatty(STDOUT_FILENO)
  6017. #else
  6018. false
  6019. #endif
  6020. ;
  6021. }
  6022. IColourImpl* platformColourInstance() {
  6023. ErrnoGuard guard;
  6024. IConfigPtr config = getCurrentContext().getConfig();
  6025. UseColour::YesOrNo colourMode = config
  6026. ? config->useColour()
  6027. : UseColour::Auto;
  6028. if( colourMode == UseColour::Auto )
  6029. colourMode = useColourOnPlatform()
  6030. ? UseColour::Yes
  6031. : UseColour::No;
  6032. return colourMode == UseColour::Yes
  6033. ? PosixColourImpl::instance()
  6034. : NoColourImpl::instance();
  6035. }
  6036. } // end anon namespace
  6037. } // end namespace Catch
  6038. #else // not Windows or ANSI ///////////////////////////////////////////////
  6039. namespace Catch {
  6040. static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); }
  6041. } // end namespace Catch
  6042. #endif // Windows/ ANSI/ None
  6043. namespace Catch {
  6044. Colour::Colour( Code _colourCode ) { use( _colourCode ); }
  6045. Colour::Colour( Colour&& rhs ) noexcept {
  6046. m_moved = rhs.m_moved;
  6047. rhs.m_moved = true;
  6048. }
  6049. Colour& Colour::operator=( Colour&& rhs ) noexcept {
  6050. m_moved = rhs.m_moved;
  6051. rhs.m_moved = true;
  6052. return *this;
  6053. }
  6054. Colour::~Colour(){ if( !m_moved ) use( None ); }
  6055. void Colour::use( Code _colourCode ) {
  6056. static IColourImpl* impl = platformColourInstance();
  6057. impl->use( _colourCode );
  6058. }
  6059. std::ostream& operator << ( std::ostream& os, Colour const& ) {
  6060. return os;
  6061. }
  6062. } // end namespace Catch
  6063. #if defined(__clang__)
  6064. # pragma clang diagnostic pop
  6065. #endif
  6066. // end catch_console_colour.cpp
  6067. // start catch_context.cpp
  6068. namespace Catch {
  6069. class Context : public IMutableContext, NonCopyable {
  6070. public: // IContext
  6071. virtual IResultCapture* getResultCapture() override {
  6072. return m_resultCapture;
  6073. }
  6074. virtual IRunner* getRunner() override {
  6075. return m_runner;
  6076. }
  6077. virtual IConfigPtr const& getConfig() const override {
  6078. return m_config;
  6079. }
  6080. virtual ~Context() override;
  6081. public: // IMutableContext
  6082. virtual void setResultCapture( IResultCapture* resultCapture ) override {
  6083. m_resultCapture = resultCapture;
  6084. }
  6085. virtual void setRunner( IRunner* runner ) override {
  6086. m_runner = runner;
  6087. }
  6088. virtual void setConfig( IConfigPtr const& config ) override {
  6089. m_config = config;
  6090. }
  6091. friend IMutableContext& getCurrentMutableContext();
  6092. private:
  6093. IConfigPtr m_config;
  6094. IRunner* m_runner = nullptr;
  6095. IResultCapture* m_resultCapture = nullptr;
  6096. };
  6097. IMutableContext *IMutableContext::currentContext = nullptr;
  6098. void IMutableContext::createContext()
  6099. {
  6100. currentContext = new Context();
  6101. }
  6102. void cleanUpContext() {
  6103. delete IMutableContext::currentContext;
  6104. IMutableContext::currentContext = nullptr;
  6105. }
  6106. IContext::~IContext() = default;
  6107. IMutableContext::~IMutableContext() = default;
  6108. Context::~Context() = default;
  6109. }
  6110. // end catch_context.cpp
  6111. // start catch_debug_console.cpp
  6112. // start catch_debug_console.h
  6113. #include <string>
  6114. namespace Catch {
  6115. void writeToDebugConsole( std::string const& text );
  6116. }
  6117. // end catch_debug_console.h
  6118. #ifdef CATCH_PLATFORM_WINDOWS
  6119. namespace Catch {
  6120. void writeToDebugConsole( std::string const& text ) {
  6121. ::OutputDebugStringA( text.c_str() );
  6122. }
  6123. }
  6124. #else
  6125. namespace Catch {
  6126. void writeToDebugConsole( std::string const& text ) {
  6127. // !TBD: Need a version for Mac/ XCode and other IDEs
  6128. Catch::cout() << text;
  6129. }
  6130. }
  6131. #endif // Platform
  6132. // end catch_debug_console.cpp
  6133. // start catch_debugger.cpp
  6134. #ifdef CATCH_PLATFORM_MAC
  6135. # include <assert.h>
  6136. # include <stdbool.h>
  6137. # include <sys/types.h>
  6138. # include <unistd.h>
  6139. # include <sys/sysctl.h>
  6140. # include <cstddef>
  6141. # include <ostream>
  6142. namespace Catch {
  6143. // The following function is taken directly from the following technical note:
  6144. // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html
  6145. // Returns true if the current process is being debugged (either
  6146. // running under the debugger or has a debugger attached post facto).
  6147. bool isDebuggerActive(){
  6148. int mib[4];
  6149. struct kinfo_proc info;
  6150. std::size_t size;
  6151. // Initialize the flags so that, if sysctl fails for some bizarre
  6152. // reason, we get a predictable result.
  6153. info.kp_proc.p_flag = 0;
  6154. // Initialize mib, which tells sysctl the info we want, in this case
  6155. // we're looking for information about a specific process ID.
  6156. mib[0] = CTL_KERN;
  6157. mib[1] = KERN_PROC;
  6158. mib[2] = KERN_PROC_PID;
  6159. mib[3] = getpid();
  6160. // Call sysctl.
  6161. size = sizeof(info);
  6162. if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, nullptr, 0) != 0 ) {
  6163. Catch::cerr() << "\n** Call to sysctl failed - unable to determine if debugger is active **\n" << std::endl;
  6164. return false;
  6165. }
  6166. // We're being debugged if the P_TRACED flag is set.
  6167. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  6168. }
  6169. } // namespace Catch
  6170. #elif defined(CATCH_PLATFORM_LINUX)
  6171. #include <fstream>
  6172. #include <string>
  6173. namespace Catch{
  6174. // The standard POSIX way of detecting a debugger is to attempt to
  6175. // ptrace() the process, but this needs to be done from a child and not
  6176. // this process itself to still allow attaching to this process later
  6177. // if wanted, so is rather heavy. Under Linux we have the PID of the
  6178. // "debugger" (which doesn't need to be gdb, of course, it could also
  6179. // be strace, for example) in /proc/$PID/status, so just get it from
  6180. // there instead.
  6181. bool isDebuggerActive(){
  6182. // Libstdc++ has a bug, where std::ifstream sets errno to 0
  6183. // This way our users can properly assert over errno values
  6184. ErrnoGuard guard;
  6185. std::ifstream in("/proc/self/status");
  6186. for( std::string line; std::getline(in, line); ) {
  6187. static const int PREFIX_LEN = 11;
  6188. if( line.compare(0, PREFIX_LEN, "TracerPid:\t") == 0 ) {
  6189. // We're traced if the PID is not 0 and no other PID starts
  6190. // with 0 digit, so it's enough to check for just a single
  6191. // character.
  6192. return line.length() > PREFIX_LEN && line[PREFIX_LEN] != '0';
  6193. }
  6194. }
  6195. return false;
  6196. }
  6197. } // namespace Catch
  6198. #elif defined(_MSC_VER)
  6199. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  6200. namespace Catch {
  6201. bool isDebuggerActive() {
  6202. return IsDebuggerPresent() != 0;
  6203. }
  6204. }
  6205. #elif defined(__MINGW32__)
  6206. extern "C" __declspec(dllimport) int __stdcall IsDebuggerPresent();
  6207. namespace Catch {
  6208. bool isDebuggerActive() {
  6209. return IsDebuggerPresent() != 0;
  6210. }
  6211. }
  6212. #else
  6213. namespace Catch {
  6214. bool isDebuggerActive() { return false; }
  6215. }
  6216. #endif // Platform
  6217. // end catch_debugger.cpp
  6218. // start catch_decomposer.cpp
  6219. namespace Catch {
  6220. ITransientExpression::~ITransientExpression() = default;
  6221. void formatReconstructedExpression( std::ostream &os, std::string const& lhs, StringRef op, std::string const& rhs ) {
  6222. if( lhs.size() + rhs.size() < 40 &&
  6223. lhs.find('\n') == std::string::npos &&
  6224. rhs.find('\n') == std::string::npos )
  6225. os << lhs << " " << op << " " << rhs;
  6226. else
  6227. os << lhs << "\n" << op << "\n" << rhs;
  6228. }
  6229. }
  6230. // end catch_decomposer.cpp
  6231. // start catch_enforce.cpp
  6232. namespace Catch {
  6233. #if defined(CATCH_CONFIG_DISABLE_EXCEPTIONS) && !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS_CUSTOM_HANDLER)
  6234. [[noreturn]]
  6235. void throw_exception(std::exception const& e) {
  6236. Catch::cerr() << "Catch will terminate because it needed to throw an exception.\n"
  6237. << "The message was: " << e.what() << '\n';
  6238. std::terminate();
  6239. }
  6240. #endif
  6241. } // namespace Catch;
  6242. // end catch_enforce.cpp
  6243. // start catch_errno_guard.cpp
  6244. #include <cerrno>
  6245. namespace Catch {
  6246. ErrnoGuard::ErrnoGuard():m_oldErrno(errno){}
  6247. ErrnoGuard::~ErrnoGuard() { errno = m_oldErrno; }
  6248. }
  6249. // end catch_errno_guard.cpp
  6250. // start catch_exception_translator_registry.cpp
  6251. // start catch_exception_translator_registry.h
  6252. #include <vector>
  6253. #include <string>
  6254. #include <memory>
  6255. namespace Catch {
  6256. class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry {
  6257. public:
  6258. ~ExceptionTranslatorRegistry();
  6259. virtual void registerTranslator( const IExceptionTranslator* translator );
  6260. virtual std::string translateActiveException() const override;
  6261. std::string tryTranslators() const;
  6262. private:
  6263. std::vector<std::unique_ptr<IExceptionTranslator const>> m_translators;
  6264. };
  6265. }
  6266. // end catch_exception_translator_registry.h
  6267. #ifdef __OBJC__
  6268. #import "Foundation/Foundation.h"
  6269. #endif
  6270. namespace Catch {
  6271. ExceptionTranslatorRegistry::~ExceptionTranslatorRegistry() {
  6272. }
  6273. void ExceptionTranslatorRegistry::registerTranslator( const IExceptionTranslator* translator ) {
  6274. m_translators.push_back( std::unique_ptr<const IExceptionTranslator>( translator ) );
  6275. }
  6276. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  6277. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  6278. try {
  6279. #ifdef __OBJC__
  6280. // In Objective-C try objective-c exceptions first
  6281. @try {
  6282. return tryTranslators();
  6283. }
  6284. @catch (NSException *exception) {
  6285. return Catch::Detail::stringify( [exception description] );
  6286. }
  6287. #else
  6288. // Compiling a mixed mode project with MSVC means that CLR
  6289. // exceptions will be caught in (...) as well. However, these
  6290. // do not fill-in std::current_exception and thus lead to crash
  6291. // when attempting rethrow.
  6292. // /EHa switch also causes structured exceptions to be caught
  6293. // here, but they fill-in current_exception properly, so
  6294. // at worst the output should be a little weird, instead of
  6295. // causing a crash.
  6296. if (std::current_exception() == nullptr) {
  6297. return "Non C++ exception. Possibly a CLR exception.";
  6298. }
  6299. return tryTranslators();
  6300. #endif
  6301. }
  6302. catch( TestFailureException& ) {
  6303. std::rethrow_exception(std::current_exception());
  6304. }
  6305. catch( std::exception& ex ) {
  6306. return ex.what();
  6307. }
  6308. catch( std::string& msg ) {
  6309. return msg;
  6310. }
  6311. catch( const char* msg ) {
  6312. return msg;
  6313. }
  6314. catch(...) {
  6315. return "Unknown exception";
  6316. }
  6317. }
  6318. #else // ^^ Exceptions are enabled // Exceptions are disabled vv
  6319. std::string ExceptionTranslatorRegistry::translateActiveException() const {
  6320. CATCH_INTERNAL_ERROR("Attempted to translate active exception under CATCH_CONFIG_DISABLE_EXCEPTIONS!");
  6321. }
  6322. #endif
  6323. std::string ExceptionTranslatorRegistry::tryTranslators() const {
  6324. if( m_translators.empty() )
  6325. std::rethrow_exception(std::current_exception());
  6326. else
  6327. return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() );
  6328. }
  6329. }
  6330. // end catch_exception_translator_registry.cpp
  6331. // start catch_fatal_condition.cpp
  6332. #if defined(__GNUC__)
  6333. # pragma GCC diagnostic push
  6334. # pragma GCC diagnostic ignored "-Wmissing-field-initializers"
  6335. #endif
  6336. #if defined( CATCH_CONFIG_WINDOWS_SEH ) || defined( CATCH_CONFIG_POSIX_SIGNALS )
  6337. namespace {
  6338. // Report the error condition
  6339. void reportFatal( char const * const message ) {
  6340. Catch::getCurrentContext().getResultCapture()->handleFatalErrorCondition( message );
  6341. }
  6342. }
  6343. #endif // signals/SEH handling
  6344. #if defined( CATCH_CONFIG_WINDOWS_SEH )
  6345. namespace Catch {
  6346. struct SignalDefs { DWORD id; const char* name; };
  6347. // There is no 1-1 mapping between signals and windows exceptions.
  6348. // Windows can easily distinguish between SO and SigSegV,
  6349. // but SigInt, SigTerm, etc are handled differently.
  6350. static SignalDefs signalDefs[] = {
  6351. { EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal" },
  6352. { EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow" },
  6353. { EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal" },
  6354. { EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error" },
  6355. };
  6356. LONG CALLBACK FatalConditionHandler::handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) {
  6357. for (auto const& def : signalDefs) {
  6358. if (ExceptionInfo->ExceptionRecord->ExceptionCode == def.id) {
  6359. reportFatal(def.name);
  6360. }
  6361. }
  6362. // If its not an exception we care about, pass it along.
  6363. // This stops us from eating debugger breaks etc.
  6364. return EXCEPTION_CONTINUE_SEARCH;
  6365. }
  6366. FatalConditionHandler::FatalConditionHandler() {
  6367. isSet = true;
  6368. // 32k seems enough for Catch to handle stack overflow,
  6369. // but the value was found experimentally, so there is no strong guarantee
  6370. guaranteeSize = 32 * 1024;
  6371. exceptionHandlerHandle = nullptr;
  6372. // Register as first handler in current chain
  6373. exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException);
  6374. // Pass in guarantee size to be filled
  6375. SetThreadStackGuarantee(&guaranteeSize);
  6376. }
  6377. void FatalConditionHandler::reset() {
  6378. if (isSet) {
  6379. RemoveVectoredExceptionHandler(exceptionHandlerHandle);
  6380. SetThreadStackGuarantee(&guaranteeSize);
  6381. exceptionHandlerHandle = nullptr;
  6382. isSet = false;
  6383. }
  6384. }
  6385. FatalConditionHandler::~FatalConditionHandler() {
  6386. reset();
  6387. }
  6388. bool FatalConditionHandler::isSet = false;
  6389. ULONG FatalConditionHandler::guaranteeSize = 0;
  6390. PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr;
  6391. } // namespace Catch
  6392. #elif defined( CATCH_CONFIG_POSIX_SIGNALS )
  6393. namespace Catch {
  6394. struct SignalDefs {
  6395. int id;
  6396. const char* name;
  6397. };
  6398. // 32kb for the alternate stack seems to be sufficient. However, this value
  6399. // is experimentally determined, so that's not guaranteed.
  6400. constexpr static std::size_t sigStackSize = 32768 >= MINSIGSTKSZ ? 32768 : MINSIGSTKSZ;
  6401. static SignalDefs signalDefs[] = {
  6402. { SIGINT, "SIGINT - Terminal interrupt signal" },
  6403. { SIGILL, "SIGILL - Illegal instruction signal" },
  6404. { SIGFPE, "SIGFPE - Floating point error signal" },
  6405. { SIGSEGV, "SIGSEGV - Segmentation violation signal" },
  6406. { SIGTERM, "SIGTERM - Termination request signal" },
  6407. { SIGABRT, "SIGABRT - Abort (abnormal termination) signal" }
  6408. };
  6409. void FatalConditionHandler::handleSignal( int sig ) {
  6410. char const * name = "<unknown signal>";
  6411. for (auto const& def : signalDefs) {
  6412. if (sig == def.id) {
  6413. name = def.name;
  6414. break;
  6415. }
  6416. }
  6417. reset();
  6418. reportFatal(name);
  6419. raise( sig );
  6420. }
  6421. FatalConditionHandler::FatalConditionHandler() {
  6422. isSet = true;
  6423. stack_t sigStack;
  6424. sigStack.ss_sp = altStackMem;
  6425. sigStack.ss_size = sigStackSize;
  6426. sigStack.ss_flags = 0;
  6427. sigaltstack(&sigStack, &oldSigStack);
  6428. struct sigaction sa = { };
  6429. sa.sa_handler = handleSignal;
  6430. sa.sa_flags = SA_ONSTACK;
  6431. for (std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i) {
  6432. sigaction(signalDefs[i].id, &sa, &oldSigActions[i]);
  6433. }
  6434. }
  6435. FatalConditionHandler::~FatalConditionHandler() {
  6436. reset();
  6437. }
  6438. void FatalConditionHandler::reset() {
  6439. if( isSet ) {
  6440. // Set signals back to previous values -- hopefully nobody overwrote them in the meantime
  6441. for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) {
  6442. sigaction(signalDefs[i].id, &oldSigActions[i], nullptr);
  6443. }
  6444. // Return the old stack
  6445. sigaltstack(&oldSigStack, nullptr);
  6446. isSet = false;
  6447. }
  6448. }
  6449. bool FatalConditionHandler::isSet = false;
  6450. struct sigaction FatalConditionHandler::oldSigActions[sizeof(signalDefs)/sizeof(SignalDefs)] = {};
  6451. stack_t FatalConditionHandler::oldSigStack = {};
  6452. char FatalConditionHandler::altStackMem[sigStackSize] = {};
  6453. } // namespace Catch
  6454. #else
  6455. namespace Catch {
  6456. void FatalConditionHandler::reset() {}
  6457. }
  6458. #endif // signals/SEH handling
  6459. #if defined(__GNUC__)
  6460. # pragma GCC diagnostic pop
  6461. #endif
  6462. // end catch_fatal_condition.cpp
  6463. // start catch_generators.cpp
  6464. // start catch_random_number_generator.h
  6465. #include <algorithm>
  6466. #include <random>
  6467. namespace Catch {
  6468. struct IConfig;
  6469. std::mt19937& rng();
  6470. void seedRng( IConfig const& config );
  6471. unsigned int rngSeed();
  6472. }
  6473. // end catch_random_number_generator.h
  6474. #include <limits>
  6475. #include <set>
  6476. namespace Catch {
  6477. IGeneratorTracker::~IGeneratorTracker() {}
  6478. namespace Generators {
  6479. GeneratorBase::~GeneratorBase() {}
  6480. std::vector<size_t> randomiseIndices( size_t selectionSize, size_t sourceSize ) {
  6481. assert( selectionSize <= sourceSize );
  6482. std::vector<size_t> indices;
  6483. indices.reserve( selectionSize );
  6484. std::uniform_int_distribution<size_t> uid( 0, sourceSize-1 );
  6485. std::set<size_t> seen;
  6486. // !TBD: improve this algorithm
  6487. while( indices.size() < selectionSize ) {
  6488. auto index = uid( rng() );
  6489. if( seen.insert( index ).second )
  6490. indices.push_back( index );
  6491. }
  6492. return indices;
  6493. }
  6494. auto acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  6495. return getResultCapture().acquireGeneratorTracker( lineInfo );
  6496. }
  6497. template<>
  6498. auto all<int>() -> Generator<int> {
  6499. return range( std::numeric_limits<int>::min(), std::numeric_limits<int>::max() );
  6500. }
  6501. } // namespace Generators
  6502. } // namespace Catch
  6503. // end catch_generators.cpp
  6504. // start catch_interfaces_capture.cpp
  6505. namespace Catch {
  6506. IResultCapture::~IResultCapture() = default;
  6507. }
  6508. // end catch_interfaces_capture.cpp
  6509. // start catch_interfaces_config.cpp
  6510. namespace Catch {
  6511. IConfig::~IConfig() = default;
  6512. }
  6513. // end catch_interfaces_config.cpp
  6514. // start catch_interfaces_exception.cpp
  6515. namespace Catch {
  6516. IExceptionTranslator::~IExceptionTranslator() = default;
  6517. IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() = default;
  6518. }
  6519. // end catch_interfaces_exception.cpp
  6520. // start catch_interfaces_registry_hub.cpp
  6521. namespace Catch {
  6522. IRegistryHub::~IRegistryHub() = default;
  6523. IMutableRegistryHub::~IMutableRegistryHub() = default;
  6524. }
  6525. // end catch_interfaces_registry_hub.cpp
  6526. // start catch_interfaces_reporter.cpp
  6527. // start catch_reporter_listening.h
  6528. namespace Catch {
  6529. class ListeningReporter : public IStreamingReporter {
  6530. using Reporters = std::vector<IStreamingReporterPtr>;
  6531. Reporters m_listeners;
  6532. IStreamingReporterPtr m_reporter = nullptr;
  6533. ReporterPreferences m_preferences;
  6534. public:
  6535. ListeningReporter();
  6536. void addListener( IStreamingReporterPtr&& listener );
  6537. void addReporter( IStreamingReporterPtr&& reporter );
  6538. public: // IStreamingReporter
  6539. ReporterPreferences getPreferences() const override;
  6540. void noMatchingTestCases( std::string const& spec ) override;
  6541. static std::set<Verbosity> getSupportedVerbosities();
  6542. void benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) override;
  6543. void benchmarkEnded( BenchmarkStats const& benchmarkStats ) override;
  6544. void testRunStarting( TestRunInfo const& testRunInfo ) override;
  6545. void testGroupStarting( GroupInfo const& groupInfo ) override;
  6546. void testCaseStarting( TestCaseInfo const& testInfo ) override;
  6547. void sectionStarting( SectionInfo const& sectionInfo ) override;
  6548. void assertionStarting( AssertionInfo const& assertionInfo ) override;
  6549. // The return value indicates if the messages buffer should be cleared:
  6550. bool assertionEnded( AssertionStats const& assertionStats ) override;
  6551. void sectionEnded( SectionStats const& sectionStats ) override;
  6552. void testCaseEnded( TestCaseStats const& testCaseStats ) override;
  6553. void testGroupEnded( TestGroupStats const& testGroupStats ) override;
  6554. void testRunEnded( TestRunStats const& testRunStats ) override;
  6555. void skipTest( TestCaseInfo const& testInfo ) override;
  6556. bool isMulti() const override;
  6557. };
  6558. } // end namespace Catch
  6559. // end catch_reporter_listening.h
  6560. namespace Catch {
  6561. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig )
  6562. : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {}
  6563. ReporterConfig::ReporterConfig( IConfigPtr const& _fullConfig, std::ostream& _stream )
  6564. : m_stream( &_stream ), m_fullConfig( _fullConfig ) {}
  6565. std::ostream& ReporterConfig::stream() const { return *m_stream; }
  6566. IConfigPtr ReporterConfig::fullConfig() const { return m_fullConfig; }
  6567. TestRunInfo::TestRunInfo( std::string const& _name ) : name( _name ) {}
  6568. GroupInfo::GroupInfo( std::string const& _name,
  6569. std::size_t _groupIndex,
  6570. std::size_t _groupsCount )
  6571. : name( _name ),
  6572. groupIndex( _groupIndex ),
  6573. groupsCounts( _groupsCount )
  6574. {}
  6575. AssertionStats::AssertionStats( AssertionResult const& _assertionResult,
  6576. std::vector<MessageInfo> const& _infoMessages,
  6577. Totals const& _totals )
  6578. : assertionResult( _assertionResult ),
  6579. infoMessages( _infoMessages ),
  6580. totals( _totals )
  6581. {
  6582. assertionResult.m_resultData.lazyExpression.m_transientExpression = _assertionResult.m_resultData.lazyExpression.m_transientExpression;
  6583. if( assertionResult.hasMessage() ) {
  6584. // Copy message into messages list.
  6585. // !TBD This should have been done earlier, somewhere
  6586. MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() );
  6587. builder << assertionResult.getMessage();
  6588. builder.m_info.message = builder.m_stream.str();
  6589. infoMessages.push_back( builder.m_info );
  6590. }
  6591. }
  6592. AssertionStats::~AssertionStats() = default;
  6593. SectionStats::SectionStats( SectionInfo const& _sectionInfo,
  6594. Counts const& _assertions,
  6595. double _durationInSeconds,
  6596. bool _missingAssertions )
  6597. : sectionInfo( _sectionInfo ),
  6598. assertions( _assertions ),
  6599. durationInSeconds( _durationInSeconds ),
  6600. missingAssertions( _missingAssertions )
  6601. {}
  6602. SectionStats::~SectionStats() = default;
  6603. TestCaseStats::TestCaseStats( TestCaseInfo const& _testInfo,
  6604. Totals const& _totals,
  6605. std::string const& _stdOut,
  6606. std::string const& _stdErr,
  6607. bool _aborting )
  6608. : testInfo( _testInfo ),
  6609. totals( _totals ),
  6610. stdOut( _stdOut ),
  6611. stdErr( _stdErr ),
  6612. aborting( _aborting )
  6613. {}
  6614. TestCaseStats::~TestCaseStats() = default;
  6615. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo,
  6616. Totals const& _totals,
  6617. bool _aborting )
  6618. : groupInfo( _groupInfo ),
  6619. totals( _totals ),
  6620. aborting( _aborting )
  6621. {}
  6622. TestGroupStats::TestGroupStats( GroupInfo const& _groupInfo )
  6623. : groupInfo( _groupInfo ),
  6624. aborting( false )
  6625. {}
  6626. TestGroupStats::~TestGroupStats() = default;
  6627. TestRunStats::TestRunStats( TestRunInfo const& _runInfo,
  6628. Totals const& _totals,
  6629. bool _aborting )
  6630. : runInfo( _runInfo ),
  6631. totals( _totals ),
  6632. aborting( _aborting )
  6633. {}
  6634. TestRunStats::~TestRunStats() = default;
  6635. void IStreamingReporter::fatalErrorEncountered( StringRef ) {}
  6636. bool IStreamingReporter::isMulti() const { return false; }
  6637. IReporterFactory::~IReporterFactory() = default;
  6638. IReporterRegistry::~IReporterRegistry() = default;
  6639. } // end namespace Catch
  6640. // end catch_interfaces_reporter.cpp
  6641. // start catch_interfaces_runner.cpp
  6642. namespace Catch {
  6643. IRunner::~IRunner() = default;
  6644. }
  6645. // end catch_interfaces_runner.cpp
  6646. // start catch_interfaces_testcase.cpp
  6647. namespace Catch {
  6648. ITestInvoker::~ITestInvoker() = default;
  6649. ITestCaseRegistry::~ITestCaseRegistry() = default;
  6650. }
  6651. // end catch_interfaces_testcase.cpp
  6652. // start catch_leak_detector.cpp
  6653. #ifdef CATCH_CONFIG_WINDOWS_CRTDBG
  6654. #include <crtdbg.h>
  6655. namespace Catch {
  6656. LeakDetector::LeakDetector() {
  6657. int flag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
  6658. flag |= _CRTDBG_LEAK_CHECK_DF;
  6659. flag |= _CRTDBG_ALLOC_MEM_DF;
  6660. _CrtSetDbgFlag(flag);
  6661. _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
  6662. _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
  6663. // Change this to leaking allocation's number to break there
  6664. _CrtSetBreakAlloc(-1);
  6665. }
  6666. }
  6667. #else
  6668. Catch::LeakDetector::LeakDetector() {}
  6669. #endif
  6670. Catch::LeakDetector::~LeakDetector() {
  6671. Catch::cleanUp();
  6672. }
  6673. // end catch_leak_detector.cpp
  6674. // start catch_list.cpp
  6675. // start catch_list.h
  6676. #include <set>
  6677. namespace Catch {
  6678. std::size_t listTests( Config const& config );
  6679. std::size_t listTestsNamesOnly( Config const& config );
  6680. struct TagInfo {
  6681. void add( std::string const& spelling );
  6682. std::string all() const;
  6683. std::set<std::string> spellings;
  6684. std::size_t count = 0;
  6685. };
  6686. std::size_t listTags( Config const& config );
  6687. std::size_t listReporters();
  6688. Option<std::size_t> list( Config const& config );
  6689. } // end namespace Catch
  6690. // end catch_list.h
  6691. // start catch_text.h
  6692. namespace Catch {
  6693. using namespace clara::TextFlow;
  6694. }
  6695. // end catch_text.h
  6696. #include <limits>
  6697. #include <algorithm>
  6698. #include <iomanip>
  6699. namespace Catch {
  6700. std::size_t listTests( Config const& config ) {
  6701. TestSpec testSpec = config.testSpec();
  6702. if( config.hasTestFilters() )
  6703. Catch::cout() << "Matching test cases:\n";
  6704. else {
  6705. Catch::cout() << "All available test cases:\n";
  6706. }
  6707. auto matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6708. for( auto const& testCaseInfo : matchedTestCases ) {
  6709. Colour::Code colour = testCaseInfo.isHidden()
  6710. ? Colour::SecondaryText
  6711. : Colour::None;
  6712. Colour colourGuard( colour );
  6713. Catch::cout() << Column( testCaseInfo.name ).initialIndent( 2 ).indent( 4 ) << "\n";
  6714. if( config.verbosity() >= Verbosity::High ) {
  6715. Catch::cout() << Column( Catch::Detail::stringify( testCaseInfo.lineInfo ) ).indent(4) << std::endl;
  6716. std::string description = testCaseInfo.description;
  6717. if( description.empty() )
  6718. description = "(NO DESCRIPTION)";
  6719. Catch::cout() << Column( description ).indent(4) << std::endl;
  6720. }
  6721. if( !testCaseInfo.tags.empty() )
  6722. Catch::cout() << Column( testCaseInfo.tagsAsString() ).indent( 6 ) << "\n";
  6723. }
  6724. if( !config.hasTestFilters() )
  6725. Catch::cout() << pluralise( matchedTestCases.size(), "test case" ) << '\n' << std::endl;
  6726. else
  6727. Catch::cout() << pluralise( matchedTestCases.size(), "matching test case" ) << '\n' << std::endl;
  6728. return matchedTestCases.size();
  6729. }
  6730. std::size_t listTestsNamesOnly( Config const& config ) {
  6731. TestSpec testSpec = config.testSpec();
  6732. std::size_t matchedTests = 0;
  6733. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6734. for( auto const& testCaseInfo : matchedTestCases ) {
  6735. matchedTests++;
  6736. if( startsWith( testCaseInfo.name, '#' ) )
  6737. Catch::cout() << '"' << testCaseInfo.name << '"';
  6738. else
  6739. Catch::cout() << testCaseInfo.name;
  6740. if ( config.verbosity() >= Verbosity::High )
  6741. Catch::cout() << "\t@" << testCaseInfo.lineInfo;
  6742. Catch::cout() << std::endl;
  6743. }
  6744. return matchedTests;
  6745. }
  6746. void TagInfo::add( std::string const& spelling ) {
  6747. ++count;
  6748. spellings.insert( spelling );
  6749. }
  6750. std::string TagInfo::all() const {
  6751. std::string out;
  6752. for( auto const& spelling : spellings )
  6753. out += "[" + spelling + "]";
  6754. return out;
  6755. }
  6756. std::size_t listTags( Config const& config ) {
  6757. TestSpec testSpec = config.testSpec();
  6758. if( config.hasTestFilters() )
  6759. Catch::cout() << "Tags for matching test cases:\n";
  6760. else {
  6761. Catch::cout() << "All available tags:\n";
  6762. }
  6763. std::map<std::string, TagInfo> tagCounts;
  6764. std::vector<TestCase> matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config );
  6765. for( auto const& testCase : matchedTestCases ) {
  6766. for( auto const& tagName : testCase.getTestCaseInfo().tags ) {
  6767. std::string lcaseTagName = toLower( tagName );
  6768. auto countIt = tagCounts.find( lcaseTagName );
  6769. if( countIt == tagCounts.end() )
  6770. countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first;
  6771. countIt->second.add( tagName );
  6772. }
  6773. }
  6774. for( auto const& tagCount : tagCounts ) {
  6775. ReusableStringStream rss;
  6776. rss << " " << std::setw(2) << tagCount.second.count << " ";
  6777. auto str = rss.str();
  6778. auto wrapper = Column( tagCount.second.all() )
  6779. .initialIndent( 0 )
  6780. .indent( str.size() )
  6781. .width( CATCH_CONFIG_CONSOLE_WIDTH-10 );
  6782. Catch::cout() << str << wrapper << '\n';
  6783. }
  6784. Catch::cout() << pluralise( tagCounts.size(), "tag" ) << '\n' << std::endl;
  6785. return tagCounts.size();
  6786. }
  6787. std::size_t listReporters() {
  6788. Catch::cout() << "Available reporters:\n";
  6789. IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories();
  6790. std::size_t maxNameLen = 0;
  6791. for( auto const& factoryKvp : factories )
  6792. maxNameLen = (std::max)( maxNameLen, factoryKvp.first.size() );
  6793. for( auto const& factoryKvp : factories ) {
  6794. Catch::cout()
  6795. << Column( factoryKvp.first + ":" )
  6796. .indent(2)
  6797. .width( 5+maxNameLen )
  6798. + Column( factoryKvp.second->getDescription() )
  6799. .initialIndent(0)
  6800. .indent(2)
  6801. .width( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 )
  6802. << "\n";
  6803. }
  6804. Catch::cout() << std::endl;
  6805. return factories.size();
  6806. }
  6807. Option<std::size_t> list( Config const& config ) {
  6808. Option<std::size_t> listedCount;
  6809. if( config.listTests() )
  6810. listedCount = listedCount.valueOr(0) + listTests( config );
  6811. if( config.listTestNamesOnly() )
  6812. listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config );
  6813. if( config.listTags() )
  6814. listedCount = listedCount.valueOr(0) + listTags( config );
  6815. if( config.listReporters() )
  6816. listedCount = listedCount.valueOr(0) + listReporters();
  6817. return listedCount;
  6818. }
  6819. } // end namespace Catch
  6820. // end catch_list.cpp
  6821. // start catch_matchers.cpp
  6822. namespace Catch {
  6823. namespace Matchers {
  6824. namespace Impl {
  6825. std::string MatcherUntypedBase::toString() const {
  6826. if( m_cachedToString.empty() )
  6827. m_cachedToString = describe();
  6828. return m_cachedToString;
  6829. }
  6830. MatcherUntypedBase::~MatcherUntypedBase() = default;
  6831. } // namespace Impl
  6832. } // namespace Matchers
  6833. using namespace Matchers;
  6834. using Matchers::Impl::MatcherBase;
  6835. } // namespace Catch
  6836. // end catch_matchers.cpp
  6837. // start catch_matchers_floating.cpp
  6838. // start catch_to_string.hpp
  6839. #include <string>
  6840. namespace Catch {
  6841. template <typename T>
  6842. std::string to_string(T const& t) {
  6843. #if defined(CATCH_CONFIG_CPP11_TO_STRING)
  6844. return std::to_string(t);
  6845. #else
  6846. ReusableStringStream rss;
  6847. rss << t;
  6848. return rss.str();
  6849. #endif
  6850. }
  6851. } // end namespace Catch
  6852. // end catch_to_string.hpp
  6853. #include <cstdlib>
  6854. #include <cstdint>
  6855. #include <cstring>
  6856. namespace Catch {
  6857. namespace Matchers {
  6858. namespace Floating {
  6859. enum class FloatingPointKind : uint8_t {
  6860. Float,
  6861. Double
  6862. };
  6863. }
  6864. }
  6865. }
  6866. namespace {
  6867. template <typename T>
  6868. struct Converter;
  6869. template <>
  6870. struct Converter<float> {
  6871. static_assert(sizeof(float) == sizeof(int32_t), "Important ULP matcher assumption violated");
  6872. Converter(float f) {
  6873. std::memcpy(&i, &f, sizeof(f));
  6874. }
  6875. int32_t i;
  6876. };
  6877. template <>
  6878. struct Converter<double> {
  6879. static_assert(sizeof(double) == sizeof(int64_t), "Important ULP matcher assumption violated");
  6880. Converter(double d) {
  6881. std::memcpy(&i, &d, sizeof(d));
  6882. }
  6883. int64_t i;
  6884. };
  6885. template <typename T>
  6886. auto convert(T t) -> Converter<T> {
  6887. return Converter<T>(t);
  6888. }
  6889. template <typename FP>
  6890. bool almostEqualUlps(FP lhs, FP rhs, int maxUlpDiff) {
  6891. // Comparison with NaN should always be false.
  6892. // This way we can rule it out before getting into the ugly details
  6893. if (std::isnan(lhs) || std::isnan(rhs)) {
  6894. return false;
  6895. }
  6896. auto lc = convert(lhs);
  6897. auto rc = convert(rhs);
  6898. if ((lc.i < 0) != (rc.i < 0)) {
  6899. // Potentially we can have +0 and -0
  6900. return lhs == rhs;
  6901. }
  6902. auto ulpDiff = std::abs(lc.i - rc.i);
  6903. return ulpDiff <= maxUlpDiff;
  6904. }
  6905. }
  6906. namespace Catch {
  6907. namespace Matchers {
  6908. namespace Floating {
  6909. WithinAbsMatcher::WithinAbsMatcher(double target, double margin)
  6910. :m_target{ target }, m_margin{ margin } {
  6911. CATCH_ENFORCE(margin >= 0, "Invalid margin: " << margin << '.'
  6912. << " Margin has to be non-negative.");
  6913. }
  6914. // Performs equivalent check of std::fabs(lhs - rhs) <= margin
  6915. // But without the subtraction to allow for INFINITY in comparison
  6916. bool WithinAbsMatcher::match(double const& matchee) const {
  6917. return (matchee + m_margin >= m_target) && (m_target + m_margin >= matchee);
  6918. }
  6919. std::string WithinAbsMatcher::describe() const {
  6920. return "is within " + ::Catch::Detail::stringify(m_margin) + " of " + ::Catch::Detail::stringify(m_target);
  6921. }
  6922. WithinUlpsMatcher::WithinUlpsMatcher(double target, int ulps, FloatingPointKind baseType)
  6923. :m_target{ target }, m_ulps{ ulps }, m_type{ baseType } {
  6924. CATCH_ENFORCE(ulps >= 0, "Invalid ULP setting: " << ulps << '.'
  6925. << " ULPs have to be non-negative.");
  6926. }
  6927. #if defined(__clang__)
  6928. #pragma clang diagnostic push
  6929. // Clang <3.5 reports on the default branch in the switch below
  6930. #pragma clang diagnostic ignored "-Wunreachable-code"
  6931. #endif
  6932. bool WithinUlpsMatcher::match(double const& matchee) const {
  6933. switch (m_type) {
  6934. case FloatingPointKind::Float:
  6935. return almostEqualUlps<float>(static_cast<float>(matchee), static_cast<float>(m_target), m_ulps);
  6936. case FloatingPointKind::Double:
  6937. return almostEqualUlps<double>(matchee, m_target, m_ulps);
  6938. default:
  6939. CATCH_INTERNAL_ERROR( "Unknown FloatingPointKind value" );
  6940. }
  6941. }
  6942. #if defined(__clang__)
  6943. #pragma clang diagnostic pop
  6944. #endif
  6945. std::string WithinUlpsMatcher::describe() const {
  6946. return "is within " + Catch::to_string(m_ulps) + " ULPs of " + ::Catch::Detail::stringify(m_target) + ((m_type == FloatingPointKind::Float)? "f" : "");
  6947. }
  6948. }// namespace Floating
  6949. Floating::WithinUlpsMatcher WithinULP(double target, int maxUlpDiff) {
  6950. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Double);
  6951. }
  6952. Floating::WithinUlpsMatcher WithinULP(float target, int maxUlpDiff) {
  6953. return Floating::WithinUlpsMatcher(target, maxUlpDiff, Floating::FloatingPointKind::Float);
  6954. }
  6955. Floating::WithinAbsMatcher WithinAbs(double target, double margin) {
  6956. return Floating::WithinAbsMatcher(target, margin);
  6957. }
  6958. } // namespace Matchers
  6959. } // namespace Catch
  6960. // end catch_matchers_floating.cpp
  6961. // start catch_matchers_generic.cpp
  6962. std::string Catch::Matchers::Generic::Detail::finalizeDescription(const std::string& desc) {
  6963. if (desc.empty()) {
  6964. return "matches undescribed predicate";
  6965. } else {
  6966. return "matches predicate: \"" + desc + '"';
  6967. }
  6968. }
  6969. // end catch_matchers_generic.cpp
  6970. // start catch_matchers_string.cpp
  6971. #include <regex>
  6972. namespace Catch {
  6973. namespace Matchers {
  6974. namespace StdString {
  6975. CasedString::CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity )
  6976. : m_caseSensitivity( caseSensitivity ),
  6977. m_str( adjustString( str ) )
  6978. {}
  6979. std::string CasedString::adjustString( std::string const& str ) const {
  6980. return m_caseSensitivity == CaseSensitive::No
  6981. ? toLower( str )
  6982. : str;
  6983. }
  6984. std::string CasedString::caseSensitivitySuffix() const {
  6985. return m_caseSensitivity == CaseSensitive::No
  6986. ? " (case insensitive)"
  6987. : std::string();
  6988. }
  6989. StringMatcherBase::StringMatcherBase( std::string const& operation, CasedString const& comparator )
  6990. : m_comparator( comparator ),
  6991. m_operation( operation ) {
  6992. }
  6993. std::string StringMatcherBase::describe() const {
  6994. std::string description;
  6995. description.reserve(5 + m_operation.size() + m_comparator.m_str.size() +
  6996. m_comparator.caseSensitivitySuffix().size());
  6997. description += m_operation;
  6998. description += ": \"";
  6999. description += m_comparator.m_str;
  7000. description += "\"";
  7001. description += m_comparator.caseSensitivitySuffix();
  7002. return description;
  7003. }
  7004. EqualsMatcher::EqualsMatcher( CasedString const& comparator ) : StringMatcherBase( "equals", comparator ) {}
  7005. bool EqualsMatcher::match( std::string const& source ) const {
  7006. return m_comparator.adjustString( source ) == m_comparator.m_str;
  7007. }
  7008. ContainsMatcher::ContainsMatcher( CasedString const& comparator ) : StringMatcherBase( "contains", comparator ) {}
  7009. bool ContainsMatcher::match( std::string const& source ) const {
  7010. return contains( m_comparator.adjustString( source ), m_comparator.m_str );
  7011. }
  7012. StartsWithMatcher::StartsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "starts with", comparator ) {}
  7013. bool StartsWithMatcher::match( std::string const& source ) const {
  7014. return startsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  7015. }
  7016. EndsWithMatcher::EndsWithMatcher( CasedString const& comparator ) : StringMatcherBase( "ends with", comparator ) {}
  7017. bool EndsWithMatcher::match( std::string const& source ) const {
  7018. return endsWith( m_comparator.adjustString( source ), m_comparator.m_str );
  7019. }
  7020. RegexMatcher::RegexMatcher(std::string regex, CaseSensitive::Choice caseSensitivity): m_regex(std::move(regex)), m_caseSensitivity(caseSensitivity) {}
  7021. bool RegexMatcher::match(std::string const& matchee) const {
  7022. auto flags = std::regex::ECMAScript; // ECMAScript is the default syntax option anyway
  7023. if (m_caseSensitivity == CaseSensitive::Choice::No) {
  7024. flags |= std::regex::icase;
  7025. }
  7026. auto reg = std::regex(m_regex, flags);
  7027. return std::regex_match(matchee, reg);
  7028. }
  7029. std::string RegexMatcher::describe() const {
  7030. return "matches " + ::Catch::Detail::stringify(m_regex) + ((m_caseSensitivity == CaseSensitive::Choice::Yes)? " case sensitively" : " case insensitively");
  7031. }
  7032. } // namespace StdString
  7033. StdString::EqualsMatcher Equals( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7034. return StdString::EqualsMatcher( StdString::CasedString( str, caseSensitivity) );
  7035. }
  7036. StdString::ContainsMatcher Contains( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7037. return StdString::ContainsMatcher( StdString::CasedString( str, caseSensitivity) );
  7038. }
  7039. StdString::EndsWithMatcher EndsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7040. return StdString::EndsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  7041. }
  7042. StdString::StartsWithMatcher StartsWith( std::string const& str, CaseSensitive::Choice caseSensitivity ) {
  7043. return StdString::StartsWithMatcher( StdString::CasedString( str, caseSensitivity) );
  7044. }
  7045. StdString::RegexMatcher Matches(std::string const& regex, CaseSensitive::Choice caseSensitivity) {
  7046. return StdString::RegexMatcher(regex, caseSensitivity);
  7047. }
  7048. } // namespace Matchers
  7049. } // namespace Catch
  7050. // end catch_matchers_string.cpp
  7051. // start catch_message.cpp
  7052. // start catch_uncaught_exceptions.h
  7053. namespace Catch {
  7054. bool uncaught_exceptions();
  7055. } // end namespace Catch
  7056. // end catch_uncaught_exceptions.h
  7057. #include <cassert>
  7058. namespace Catch {
  7059. MessageInfo::MessageInfo( StringRef const& _macroName,
  7060. SourceLineInfo const& _lineInfo,
  7061. ResultWas::OfType _type )
  7062. : macroName( _macroName ),
  7063. lineInfo( _lineInfo ),
  7064. type( _type ),
  7065. sequence( ++globalCount )
  7066. {}
  7067. bool MessageInfo::operator==( MessageInfo const& other ) const {
  7068. return sequence == other.sequence;
  7069. }
  7070. bool MessageInfo::operator<( MessageInfo const& other ) const {
  7071. return sequence < other.sequence;
  7072. }
  7073. // This may need protecting if threading support is added
  7074. unsigned int MessageInfo::globalCount = 0;
  7075. ////////////////////////////////////////////////////////////////////////////
  7076. Catch::MessageBuilder::MessageBuilder( StringRef const& macroName,
  7077. SourceLineInfo const& lineInfo,
  7078. ResultWas::OfType type )
  7079. :m_info(macroName, lineInfo, type) {}
  7080. ////////////////////////////////////////////////////////////////////////////
  7081. ScopedMessage::ScopedMessage( MessageBuilder const& builder )
  7082. : m_info( builder.m_info )
  7083. {
  7084. m_info.message = builder.m_stream.str();
  7085. getResultCapture().pushScopedMessage( m_info );
  7086. }
  7087. ScopedMessage::~ScopedMessage() {
  7088. if ( !uncaught_exceptions() ){
  7089. getResultCapture().popScopedMessage(m_info);
  7090. }
  7091. }
  7092. Capturer::Capturer( StringRef macroName, SourceLineInfo const& lineInfo, ResultWas::OfType resultType, StringRef names ) {
  7093. auto start = std::string::npos;
  7094. for( size_t pos = 0; pos <= names.size(); ++pos ) {
  7095. char c = names[pos];
  7096. if( pos == names.size() || c == ' ' || c == '\t' || c == ',' || c == ']' ) {
  7097. if( start != std::string::npos ) {
  7098. m_messages.push_back( MessageInfo( macroName, lineInfo, resultType ) );
  7099. m_messages.back().message = names.substr( start, pos-start) + " := ";
  7100. start = std::string::npos;
  7101. }
  7102. }
  7103. else if( c != '[' && c != ']' && start == std::string::npos )
  7104. start = pos;
  7105. }
  7106. }
  7107. Capturer::~Capturer() {
  7108. if ( !uncaught_exceptions() ){
  7109. assert( m_captured == m_messages.size() );
  7110. for( size_t i = 0; i < m_captured; ++i )
  7111. m_resultCapture.popScopedMessage( m_messages[i] );
  7112. }
  7113. }
  7114. void Capturer::captureValue( size_t index, StringRef value ) {
  7115. assert( index < m_messages.size() );
  7116. m_messages[index].message += value;
  7117. m_resultCapture.pushScopedMessage( m_messages[index] );
  7118. m_captured++;
  7119. }
  7120. } // end namespace Catch
  7121. // end catch_message.cpp
  7122. // start catch_output_redirect.cpp
  7123. // start catch_output_redirect.h
  7124. #ifndef TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7125. #define TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7126. #include <cstdio>
  7127. #include <iosfwd>
  7128. #include <string>
  7129. namespace Catch {
  7130. class RedirectedStream {
  7131. std::ostream& m_originalStream;
  7132. std::ostream& m_redirectionStream;
  7133. std::streambuf* m_prevBuf;
  7134. public:
  7135. RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream );
  7136. ~RedirectedStream();
  7137. };
  7138. class RedirectedStdOut {
  7139. ReusableStringStream m_rss;
  7140. RedirectedStream m_cout;
  7141. public:
  7142. RedirectedStdOut();
  7143. auto str() const -> std::string;
  7144. };
  7145. // StdErr has two constituent streams in C++, std::cerr and std::clog
  7146. // This means that we need to redirect 2 streams into 1 to keep proper
  7147. // order of writes
  7148. class RedirectedStdErr {
  7149. ReusableStringStream m_rss;
  7150. RedirectedStream m_cerr;
  7151. RedirectedStream m_clog;
  7152. public:
  7153. RedirectedStdErr();
  7154. auto str() const -> std::string;
  7155. };
  7156. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7157. // Windows's implementation of std::tmpfile is terrible (it tries
  7158. // to create a file inside system folder, thus requiring elevated
  7159. // privileges for the binary), so we have to use tmpnam(_s) and
  7160. // create the file ourselves there.
  7161. class TempFile {
  7162. public:
  7163. TempFile(TempFile const&) = delete;
  7164. TempFile& operator=(TempFile const&) = delete;
  7165. TempFile(TempFile&&) = delete;
  7166. TempFile& operator=(TempFile&&) = delete;
  7167. TempFile();
  7168. ~TempFile();
  7169. std::FILE* getFile();
  7170. std::string getContents();
  7171. private:
  7172. std::FILE* m_file = nullptr;
  7173. #if defined(_MSC_VER)
  7174. char m_buffer[L_tmpnam] = { 0 };
  7175. #endif
  7176. };
  7177. class OutputRedirect {
  7178. public:
  7179. OutputRedirect(OutputRedirect const&) = delete;
  7180. OutputRedirect& operator=(OutputRedirect const&) = delete;
  7181. OutputRedirect(OutputRedirect&&) = delete;
  7182. OutputRedirect& operator=(OutputRedirect&&) = delete;
  7183. OutputRedirect(std::string& stdout_dest, std::string& stderr_dest);
  7184. ~OutputRedirect();
  7185. private:
  7186. int m_originalStdout = -1;
  7187. int m_originalStderr = -1;
  7188. TempFile m_stdoutFile;
  7189. TempFile m_stderrFile;
  7190. std::string& m_stdoutDest;
  7191. std::string& m_stderrDest;
  7192. };
  7193. #endif
  7194. } // end namespace Catch
  7195. #endif // TWOBLUECUBES_CATCH_OUTPUT_REDIRECT_H
  7196. // end catch_output_redirect.h
  7197. #include <cstdio>
  7198. #include <cstring>
  7199. #include <fstream>
  7200. #include <sstream>
  7201. #include <stdexcept>
  7202. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7203. #if defined(_MSC_VER)
  7204. #include <io.h> //_dup and _dup2
  7205. #define dup _dup
  7206. #define dup2 _dup2
  7207. #define fileno _fileno
  7208. #else
  7209. #include <unistd.h> // dup and dup2
  7210. #endif
  7211. #endif
  7212. namespace Catch {
  7213. RedirectedStream::RedirectedStream( std::ostream& originalStream, std::ostream& redirectionStream )
  7214. : m_originalStream( originalStream ),
  7215. m_redirectionStream( redirectionStream ),
  7216. m_prevBuf( m_originalStream.rdbuf() )
  7217. {
  7218. m_originalStream.rdbuf( m_redirectionStream.rdbuf() );
  7219. }
  7220. RedirectedStream::~RedirectedStream() {
  7221. m_originalStream.rdbuf( m_prevBuf );
  7222. }
  7223. RedirectedStdOut::RedirectedStdOut() : m_cout( Catch::cout(), m_rss.get() ) {}
  7224. auto RedirectedStdOut::str() const -> std::string { return m_rss.str(); }
  7225. RedirectedStdErr::RedirectedStdErr()
  7226. : m_cerr( Catch::cerr(), m_rss.get() ),
  7227. m_clog( Catch::clog(), m_rss.get() )
  7228. {}
  7229. auto RedirectedStdErr::str() const -> std::string { return m_rss.str(); }
  7230. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7231. #if defined(_MSC_VER)
  7232. TempFile::TempFile() {
  7233. if (tmpnam_s(m_buffer)) {
  7234. CATCH_RUNTIME_ERROR("Could not get a temp filename");
  7235. }
  7236. if (fopen_s(&m_file, m_buffer, "w")) {
  7237. char buffer[100];
  7238. if (strerror_s(buffer, errno)) {
  7239. CATCH_RUNTIME_ERROR("Could not translate errno to a string");
  7240. }
  7241. CATCH_RUNTIME_ERROR("Coul dnot open the temp file: '" << m_buffer << "' because: " << buffer);
  7242. }
  7243. }
  7244. #else
  7245. TempFile::TempFile() {
  7246. m_file = std::tmpfile();
  7247. if (!m_file) {
  7248. CATCH_RUNTIME_ERROR("Could not create a temp file.");
  7249. }
  7250. }
  7251. #endif
  7252. TempFile::~TempFile() {
  7253. // TBD: What to do about errors here?
  7254. std::fclose(m_file);
  7255. // We manually create the file on Windows only, on Linux
  7256. // it will be autodeleted
  7257. #if defined(_MSC_VER)
  7258. std::remove(m_buffer);
  7259. #endif
  7260. }
  7261. FILE* TempFile::getFile() {
  7262. return m_file;
  7263. }
  7264. std::string TempFile::getContents() {
  7265. std::stringstream sstr;
  7266. char buffer[100] = {};
  7267. std::rewind(m_file);
  7268. while (std::fgets(buffer, sizeof(buffer), m_file)) {
  7269. sstr << buffer;
  7270. }
  7271. return sstr.str();
  7272. }
  7273. OutputRedirect::OutputRedirect(std::string& stdout_dest, std::string& stderr_dest) :
  7274. m_originalStdout(dup(1)),
  7275. m_originalStderr(dup(2)),
  7276. m_stdoutDest(stdout_dest),
  7277. m_stderrDest(stderr_dest) {
  7278. dup2(fileno(m_stdoutFile.getFile()), 1);
  7279. dup2(fileno(m_stderrFile.getFile()), 2);
  7280. }
  7281. OutputRedirect::~OutputRedirect() {
  7282. Catch::cout() << std::flush;
  7283. fflush(stdout);
  7284. // Since we support overriding these streams, we flush cerr
  7285. // even though std::cerr is unbuffered
  7286. Catch::cerr() << std::flush;
  7287. Catch::clog() << std::flush;
  7288. fflush(stderr);
  7289. dup2(m_originalStdout, 1);
  7290. dup2(m_originalStderr, 2);
  7291. m_stdoutDest += m_stdoutFile.getContents();
  7292. m_stderrDest += m_stderrFile.getContents();
  7293. }
  7294. #endif // CATCH_CONFIG_NEW_CAPTURE
  7295. } // namespace Catch
  7296. #if defined(CATCH_CONFIG_NEW_CAPTURE)
  7297. #if defined(_MSC_VER)
  7298. #undef dup
  7299. #undef dup2
  7300. #undef fileno
  7301. #endif
  7302. #endif
  7303. // end catch_output_redirect.cpp
  7304. // start catch_random_number_generator.cpp
  7305. namespace Catch {
  7306. std::mt19937& rng() {
  7307. static std::mt19937 s_rng;
  7308. return s_rng;
  7309. }
  7310. void seedRng( IConfig const& config ) {
  7311. if( config.rngSeed() != 0 ) {
  7312. std::srand( config.rngSeed() );
  7313. rng().seed( config.rngSeed() );
  7314. }
  7315. }
  7316. unsigned int rngSeed() {
  7317. return getCurrentContext().getConfig()->rngSeed();
  7318. }
  7319. }
  7320. // end catch_random_number_generator.cpp
  7321. // start catch_registry_hub.cpp
  7322. // start catch_test_case_registry_impl.h
  7323. #include <vector>
  7324. #include <set>
  7325. #include <algorithm>
  7326. #include <ios>
  7327. namespace Catch {
  7328. class TestCase;
  7329. struct IConfig;
  7330. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases );
  7331. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config );
  7332. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions );
  7333. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config );
  7334. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config );
  7335. class TestRegistry : public ITestCaseRegistry {
  7336. public:
  7337. virtual ~TestRegistry() = default;
  7338. virtual void registerTest( TestCase const& testCase );
  7339. std::vector<TestCase> const& getAllTests() const override;
  7340. std::vector<TestCase> const& getAllTestsSorted( IConfig const& config ) const override;
  7341. private:
  7342. std::vector<TestCase> m_functions;
  7343. mutable RunTests::InWhatOrder m_currentSortOrder = RunTests::InDeclarationOrder;
  7344. mutable std::vector<TestCase> m_sortedFunctions;
  7345. std::size_t m_unnamedCount = 0;
  7346. std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised
  7347. };
  7348. ///////////////////////////////////////////////////////////////////////////
  7349. class TestInvokerAsFunction : public ITestInvoker {
  7350. void(*m_testAsFunction)();
  7351. public:
  7352. TestInvokerAsFunction( void(*testAsFunction)() ) noexcept;
  7353. void invoke() const override;
  7354. };
  7355. std::string extractClassName( StringRef const& classOrQualifiedMethodName );
  7356. ///////////////////////////////////////////////////////////////////////////
  7357. } // end namespace Catch
  7358. // end catch_test_case_registry_impl.h
  7359. // start catch_reporter_registry.h
  7360. #include <map>
  7361. namespace Catch {
  7362. class ReporterRegistry : public IReporterRegistry {
  7363. public:
  7364. ~ReporterRegistry() override;
  7365. IStreamingReporterPtr create( std::string const& name, IConfigPtr const& config ) const override;
  7366. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory );
  7367. void registerListener( IReporterFactoryPtr const& factory );
  7368. FactoryMap const& getFactories() const override;
  7369. Listeners const& getListeners() const override;
  7370. private:
  7371. FactoryMap m_factories;
  7372. Listeners m_listeners;
  7373. };
  7374. }
  7375. // end catch_reporter_registry.h
  7376. // start catch_tag_alias_registry.h
  7377. // start catch_tag_alias.h
  7378. #include <string>
  7379. namespace Catch {
  7380. struct TagAlias {
  7381. TagAlias(std::string const& _tag, SourceLineInfo _lineInfo);
  7382. std::string tag;
  7383. SourceLineInfo lineInfo;
  7384. };
  7385. } // end namespace Catch
  7386. // end catch_tag_alias.h
  7387. #include <map>
  7388. namespace Catch {
  7389. class TagAliasRegistry : public ITagAliasRegistry {
  7390. public:
  7391. ~TagAliasRegistry() override;
  7392. TagAlias const* find( std::string const& alias ) const override;
  7393. std::string expandAliases( std::string const& unexpandedTestSpec ) const override;
  7394. void add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo );
  7395. private:
  7396. std::map<std::string, TagAlias> m_registry;
  7397. };
  7398. } // end namespace Catch
  7399. // end catch_tag_alias_registry.h
  7400. // start catch_startup_exception_registry.h
  7401. #include <vector>
  7402. #include <exception>
  7403. namespace Catch {
  7404. class StartupExceptionRegistry {
  7405. public:
  7406. void add(std::exception_ptr const& exception) noexcept;
  7407. std::vector<std::exception_ptr> const& getExceptions() const noexcept;
  7408. private:
  7409. std::vector<std::exception_ptr> m_exceptions;
  7410. };
  7411. } // end namespace Catch
  7412. // end catch_startup_exception_registry.h
  7413. // start catch_singletons.hpp
  7414. namespace Catch {
  7415. struct ISingleton {
  7416. virtual ~ISingleton();
  7417. };
  7418. void addSingleton( ISingleton* singleton );
  7419. void cleanupSingletons();
  7420. template<typename SingletonImplT, typename InterfaceT = SingletonImplT, typename MutableInterfaceT = InterfaceT>
  7421. class Singleton : SingletonImplT, public ISingleton {
  7422. static auto getInternal() -> Singleton* {
  7423. static Singleton* s_instance = nullptr;
  7424. if( !s_instance ) {
  7425. s_instance = new Singleton;
  7426. addSingleton( s_instance );
  7427. }
  7428. return s_instance;
  7429. }
  7430. public:
  7431. static auto get() -> InterfaceT const& {
  7432. return *getInternal();
  7433. }
  7434. static auto getMutable() -> MutableInterfaceT& {
  7435. return *getInternal();
  7436. }
  7437. };
  7438. } // namespace Catch
  7439. // end catch_singletons.hpp
  7440. namespace Catch {
  7441. namespace {
  7442. class RegistryHub : public IRegistryHub, public IMutableRegistryHub,
  7443. private NonCopyable {
  7444. public: // IRegistryHub
  7445. RegistryHub() = default;
  7446. IReporterRegistry const& getReporterRegistry() const override {
  7447. return m_reporterRegistry;
  7448. }
  7449. ITestCaseRegistry const& getTestCaseRegistry() const override {
  7450. return m_testCaseRegistry;
  7451. }
  7452. IExceptionTranslatorRegistry const& getExceptionTranslatorRegistry() const override {
  7453. return m_exceptionTranslatorRegistry;
  7454. }
  7455. ITagAliasRegistry const& getTagAliasRegistry() const override {
  7456. return m_tagAliasRegistry;
  7457. }
  7458. StartupExceptionRegistry const& getStartupExceptionRegistry() const override {
  7459. return m_exceptionRegistry;
  7460. }
  7461. public: // IMutableRegistryHub
  7462. void registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) override {
  7463. m_reporterRegistry.registerReporter( name, factory );
  7464. }
  7465. void registerListener( IReporterFactoryPtr const& factory ) override {
  7466. m_reporterRegistry.registerListener( factory );
  7467. }
  7468. void registerTest( TestCase const& testInfo ) override {
  7469. m_testCaseRegistry.registerTest( testInfo );
  7470. }
  7471. void registerTranslator( const IExceptionTranslator* translator ) override {
  7472. m_exceptionTranslatorRegistry.registerTranslator( translator );
  7473. }
  7474. void registerTagAlias( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) override {
  7475. m_tagAliasRegistry.add( alias, tag, lineInfo );
  7476. }
  7477. void registerStartupException() noexcept override {
  7478. m_exceptionRegistry.add(std::current_exception());
  7479. }
  7480. private:
  7481. TestRegistry m_testCaseRegistry;
  7482. ReporterRegistry m_reporterRegistry;
  7483. ExceptionTranslatorRegistry m_exceptionTranslatorRegistry;
  7484. TagAliasRegistry m_tagAliasRegistry;
  7485. StartupExceptionRegistry m_exceptionRegistry;
  7486. };
  7487. }
  7488. using RegistryHubSingleton = Singleton<RegistryHub, IRegistryHub, IMutableRegistryHub>;
  7489. IRegistryHub const& getRegistryHub() {
  7490. return RegistryHubSingleton::get();
  7491. }
  7492. IMutableRegistryHub& getMutableRegistryHub() {
  7493. return RegistryHubSingleton::getMutable();
  7494. }
  7495. void cleanUp() {
  7496. cleanupSingletons();
  7497. cleanUpContext();
  7498. }
  7499. std::string translateActiveException() {
  7500. return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException();
  7501. }
  7502. } // end namespace Catch
  7503. // end catch_registry_hub.cpp
  7504. // start catch_reporter_registry.cpp
  7505. namespace Catch {
  7506. ReporterRegistry::~ReporterRegistry() = default;
  7507. IStreamingReporterPtr ReporterRegistry::create( std::string const& name, IConfigPtr const& config ) const {
  7508. auto it = m_factories.find( name );
  7509. if( it == m_factories.end() )
  7510. return nullptr;
  7511. return it->second->create( ReporterConfig( config ) );
  7512. }
  7513. void ReporterRegistry::registerReporter( std::string const& name, IReporterFactoryPtr const& factory ) {
  7514. m_factories.emplace(name, factory);
  7515. }
  7516. void ReporterRegistry::registerListener( IReporterFactoryPtr const& factory ) {
  7517. m_listeners.push_back( factory );
  7518. }
  7519. IReporterRegistry::FactoryMap const& ReporterRegistry::getFactories() const {
  7520. return m_factories;
  7521. }
  7522. IReporterRegistry::Listeners const& ReporterRegistry::getListeners() const {
  7523. return m_listeners;
  7524. }
  7525. }
  7526. // end catch_reporter_registry.cpp
  7527. // start catch_result_type.cpp
  7528. namespace Catch {
  7529. bool isOk( ResultWas::OfType resultType ) {
  7530. return ( resultType & ResultWas::FailureBit ) == 0;
  7531. }
  7532. bool isJustInfo( int flags ) {
  7533. return flags == ResultWas::Info;
  7534. }
  7535. ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) {
  7536. return static_cast<ResultDisposition::Flags>( static_cast<int>( lhs ) | static_cast<int>( rhs ) );
  7537. }
  7538. bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; }
  7539. bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; }
  7540. } // end namespace Catch
  7541. // end catch_result_type.cpp
  7542. // start catch_run_context.cpp
  7543. #include <cassert>
  7544. #include <algorithm>
  7545. #include <sstream>
  7546. namespace Catch {
  7547. namespace Generators {
  7548. struct GeneratorTracker : TestCaseTracking::TrackerBase, IGeneratorTracker {
  7549. size_t m_index = static_cast<size_t>( -1 );
  7550. GeneratorBasePtr m_generator;
  7551. GeneratorTracker( TestCaseTracking::NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  7552. : TrackerBase( nameAndLocation, ctx, parent )
  7553. {}
  7554. ~GeneratorTracker();
  7555. static GeneratorTracker& acquire( TrackerContext& ctx, TestCaseTracking::NameAndLocation const& nameAndLocation ) {
  7556. std::shared_ptr<GeneratorTracker> tracker;
  7557. ITracker& currentTracker = ctx.currentTracker();
  7558. if( TestCaseTracking::ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  7559. assert( childTracker );
  7560. assert( childTracker->isIndexTracker() );
  7561. tracker = std::static_pointer_cast<GeneratorTracker>( childTracker );
  7562. }
  7563. else {
  7564. tracker = std::make_shared<GeneratorTracker>( nameAndLocation, ctx, &currentTracker );
  7565. currentTracker.addChild( tracker );
  7566. }
  7567. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  7568. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  7569. tracker->moveNext();
  7570. tracker->open();
  7571. }
  7572. return *tracker;
  7573. }
  7574. void moveNext() {
  7575. m_index++;
  7576. m_children.clear();
  7577. }
  7578. // TrackerBase interface
  7579. bool isIndexTracker() const override { return true; }
  7580. auto hasGenerator() const -> bool override {
  7581. return !!m_generator;
  7582. }
  7583. void close() override {
  7584. TrackerBase::close();
  7585. if( m_runState == CompletedSuccessfully && m_index < m_generator->size()-1 )
  7586. m_runState = Executing;
  7587. }
  7588. // IGeneratorTracker interface
  7589. auto getGenerator() const -> GeneratorBasePtr const& override {
  7590. return m_generator;
  7591. }
  7592. void setGenerator( GeneratorBasePtr&& generator ) override {
  7593. m_generator = std::move( generator );
  7594. }
  7595. auto getIndex() const -> size_t override {
  7596. return m_index;
  7597. }
  7598. };
  7599. GeneratorTracker::~GeneratorTracker() {}
  7600. }
  7601. RunContext::RunContext(IConfigPtr const& _config, IStreamingReporterPtr&& reporter)
  7602. : m_runInfo(_config->name()),
  7603. m_context(getCurrentMutableContext()),
  7604. m_config(_config),
  7605. m_reporter(std::move(reporter)),
  7606. m_lastAssertionInfo{ StringRef(), SourceLineInfo("",0), StringRef(), ResultDisposition::Normal },
  7607. m_includeSuccessfulResults( m_config->includeSuccessfulResults() || m_reporter->getPreferences().shouldReportAllAssertions )
  7608. {
  7609. m_context.setRunner(this);
  7610. m_context.setConfig(m_config);
  7611. m_context.setResultCapture(this);
  7612. m_reporter->testRunStarting(m_runInfo);
  7613. }
  7614. RunContext::~RunContext() {
  7615. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, aborting()));
  7616. }
  7617. void RunContext::testGroupStarting(std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount) {
  7618. m_reporter->testGroupStarting(GroupInfo(testSpec, groupIndex, groupsCount));
  7619. }
  7620. void RunContext::testGroupEnded(std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount) {
  7621. m_reporter->testGroupEnded(TestGroupStats(GroupInfo(testSpec, groupIndex, groupsCount), totals, aborting()));
  7622. }
  7623. Totals RunContext::runTest(TestCase const& testCase) {
  7624. Totals prevTotals = m_totals;
  7625. std::string redirectedCout;
  7626. std::string redirectedCerr;
  7627. auto const& testInfo = testCase.getTestCaseInfo();
  7628. m_reporter->testCaseStarting(testInfo);
  7629. m_activeTestCase = &testCase;
  7630. ITracker& rootTracker = m_trackerContext.startRun();
  7631. assert(rootTracker.isSectionTracker());
  7632. static_cast<SectionTracker&>(rootTracker).addInitialFilters(m_config->getSectionsToRun());
  7633. do {
  7634. m_trackerContext.startCycle();
  7635. m_testCaseTracker = &SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(testInfo.name, testInfo.lineInfo));
  7636. runCurrentTest(redirectedCout, redirectedCerr);
  7637. } while (!m_testCaseTracker->isSuccessfullyCompleted() && !aborting());
  7638. Totals deltaTotals = m_totals.delta(prevTotals);
  7639. if (testInfo.expectedToFail() && deltaTotals.testCases.passed > 0) {
  7640. deltaTotals.assertions.failed++;
  7641. deltaTotals.testCases.passed--;
  7642. deltaTotals.testCases.failed++;
  7643. }
  7644. m_totals.testCases += deltaTotals.testCases;
  7645. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  7646. deltaTotals,
  7647. redirectedCout,
  7648. redirectedCerr,
  7649. aborting()));
  7650. m_activeTestCase = nullptr;
  7651. m_testCaseTracker = nullptr;
  7652. return deltaTotals;
  7653. }
  7654. IConfigPtr RunContext::config() const {
  7655. return m_config;
  7656. }
  7657. IStreamingReporter& RunContext::reporter() const {
  7658. return *m_reporter;
  7659. }
  7660. void RunContext::assertionEnded(AssertionResult const & result) {
  7661. if (result.getResultType() == ResultWas::Ok) {
  7662. m_totals.assertions.passed++;
  7663. m_lastAssertionPassed = true;
  7664. } else if (!result.isOk()) {
  7665. m_lastAssertionPassed = false;
  7666. if( m_activeTestCase->getTestCaseInfo().okToFail() )
  7667. m_totals.assertions.failedButOk++;
  7668. else
  7669. m_totals.assertions.failed++;
  7670. }
  7671. else {
  7672. m_lastAssertionPassed = true;
  7673. }
  7674. // We have no use for the return value (whether messages should be cleared), because messages were made scoped
  7675. // and should be let to clear themselves out.
  7676. static_cast<void>(m_reporter->assertionEnded(AssertionStats(result, m_messages, m_totals)));
  7677. // Reset working state
  7678. resetAssertionInfo();
  7679. m_lastResult = result;
  7680. }
  7681. void RunContext::resetAssertionInfo() {
  7682. m_lastAssertionInfo.macroName = StringRef();
  7683. m_lastAssertionInfo.capturedExpression = "{Unknown expression after the reported line}"_sr;
  7684. }
  7685. bool RunContext::sectionStarted(SectionInfo const & sectionInfo, Counts & assertions) {
  7686. ITracker& sectionTracker = SectionTracker::acquire(m_trackerContext, TestCaseTracking::NameAndLocation(sectionInfo.name, sectionInfo.lineInfo));
  7687. if (!sectionTracker.isOpen())
  7688. return false;
  7689. m_activeSections.push_back(&sectionTracker);
  7690. m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo;
  7691. m_reporter->sectionStarting(sectionInfo);
  7692. assertions = m_totals.assertions;
  7693. return true;
  7694. }
  7695. auto RunContext::acquireGeneratorTracker( SourceLineInfo const& lineInfo ) -> IGeneratorTracker& {
  7696. using namespace Generators;
  7697. GeneratorTracker& tracker = GeneratorTracker::acquire( m_trackerContext, TestCaseTracking::NameAndLocation( "generator", lineInfo ) );
  7698. assert( tracker.isOpen() );
  7699. m_lastAssertionInfo.lineInfo = lineInfo;
  7700. return tracker;
  7701. }
  7702. bool RunContext::testForMissingAssertions(Counts& assertions) {
  7703. if (assertions.total() != 0)
  7704. return false;
  7705. if (!m_config->warnAboutMissingAssertions())
  7706. return false;
  7707. if (m_trackerContext.currentTracker().hasChildren())
  7708. return false;
  7709. m_totals.assertions.failed++;
  7710. assertions.failed++;
  7711. return true;
  7712. }
  7713. void RunContext::sectionEnded(SectionEndInfo const & endInfo) {
  7714. Counts assertions = m_totals.assertions - endInfo.prevAssertions;
  7715. bool missingAssertions = testForMissingAssertions(assertions);
  7716. if (!m_activeSections.empty()) {
  7717. m_activeSections.back()->close();
  7718. m_activeSections.pop_back();
  7719. }
  7720. m_reporter->sectionEnded(SectionStats(endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions));
  7721. m_messages.clear();
  7722. }
  7723. void RunContext::sectionEndedEarly(SectionEndInfo const & endInfo) {
  7724. if (m_unfinishedSections.empty())
  7725. m_activeSections.back()->fail();
  7726. else
  7727. m_activeSections.back()->close();
  7728. m_activeSections.pop_back();
  7729. m_unfinishedSections.push_back(endInfo);
  7730. }
  7731. void RunContext::benchmarkStarting( BenchmarkInfo const& info ) {
  7732. m_reporter->benchmarkStarting( info );
  7733. }
  7734. void RunContext::benchmarkEnded( BenchmarkStats const& stats ) {
  7735. m_reporter->benchmarkEnded( stats );
  7736. }
  7737. void RunContext::pushScopedMessage(MessageInfo const & message) {
  7738. m_messages.push_back(message);
  7739. }
  7740. void RunContext::popScopedMessage(MessageInfo const & message) {
  7741. m_messages.erase(std::remove(m_messages.begin(), m_messages.end(), message), m_messages.end());
  7742. }
  7743. std::string RunContext::getCurrentTestName() const {
  7744. return m_activeTestCase
  7745. ? m_activeTestCase->getTestCaseInfo().name
  7746. : std::string();
  7747. }
  7748. const AssertionResult * RunContext::getLastResult() const {
  7749. return &(*m_lastResult);
  7750. }
  7751. void RunContext::exceptionEarlyReported() {
  7752. m_shouldReportUnexpected = false;
  7753. }
  7754. void RunContext::handleFatalErrorCondition( StringRef message ) {
  7755. // First notify reporter that bad things happened
  7756. m_reporter->fatalErrorEncountered(message);
  7757. // Don't rebuild the result -- the stringification itself can cause more fatal errors
  7758. // Instead, fake a result data.
  7759. AssertionResultData tempResult( ResultWas::FatalErrorCondition, { false } );
  7760. tempResult.message = message;
  7761. AssertionResult result(m_lastAssertionInfo, tempResult);
  7762. assertionEnded(result);
  7763. handleUnfinishedSections();
  7764. // Recreate section for test case (as we will lose the one that was in scope)
  7765. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  7766. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  7767. Counts assertions;
  7768. assertions.failed = 1;
  7769. SectionStats testCaseSectionStats(testCaseSection, assertions, 0, false);
  7770. m_reporter->sectionEnded(testCaseSectionStats);
  7771. auto const& testInfo = m_activeTestCase->getTestCaseInfo();
  7772. Totals deltaTotals;
  7773. deltaTotals.testCases.failed = 1;
  7774. deltaTotals.assertions.failed = 1;
  7775. m_reporter->testCaseEnded(TestCaseStats(testInfo,
  7776. deltaTotals,
  7777. std::string(),
  7778. std::string(),
  7779. false));
  7780. m_totals.testCases.failed++;
  7781. testGroupEnded(std::string(), m_totals, 1, 1);
  7782. m_reporter->testRunEnded(TestRunStats(m_runInfo, m_totals, false));
  7783. }
  7784. bool RunContext::lastAssertionPassed() {
  7785. return m_lastAssertionPassed;
  7786. }
  7787. void RunContext::assertionPassed() {
  7788. m_lastAssertionPassed = true;
  7789. ++m_totals.assertions.passed;
  7790. resetAssertionInfo();
  7791. }
  7792. bool RunContext::aborting() const {
  7793. return m_totals.assertions.failed >= static_cast<std::size_t>(m_config->abortAfter());
  7794. }
  7795. void RunContext::runCurrentTest(std::string & redirectedCout, std::string & redirectedCerr) {
  7796. auto const& testCaseInfo = m_activeTestCase->getTestCaseInfo();
  7797. SectionInfo testCaseSection(testCaseInfo.lineInfo, testCaseInfo.name);
  7798. m_reporter->sectionStarting(testCaseSection);
  7799. Counts prevAssertions = m_totals.assertions;
  7800. double duration = 0;
  7801. m_shouldReportUnexpected = true;
  7802. m_lastAssertionInfo = { "TEST_CASE"_sr, testCaseInfo.lineInfo, StringRef(), ResultDisposition::Normal };
  7803. seedRng(*m_config);
  7804. Timer timer;
  7805. CATCH_TRY {
  7806. if (m_reporter->getPreferences().shouldRedirectStdOut) {
  7807. #if !defined(CATCH_CONFIG_EXPERIMENTAL_REDIRECT)
  7808. RedirectedStdOut redirectedStdOut;
  7809. RedirectedStdErr redirectedStdErr;
  7810. timer.start();
  7811. invokeActiveTestCase();
  7812. redirectedCout += redirectedStdOut.str();
  7813. redirectedCerr += redirectedStdErr.str();
  7814. #else
  7815. OutputRedirect r(redirectedCout, redirectedCerr);
  7816. timer.start();
  7817. invokeActiveTestCase();
  7818. #endif
  7819. } else {
  7820. timer.start();
  7821. invokeActiveTestCase();
  7822. }
  7823. duration = timer.getElapsedSeconds();
  7824. } CATCH_CATCH_ANON (TestFailureException&) {
  7825. // This just means the test was aborted due to failure
  7826. } CATCH_CATCH_ALL {
  7827. // Under CATCH_CONFIG_FAST_COMPILE, unexpected exceptions under REQUIRE assertions
  7828. // are reported without translation at the point of origin.
  7829. if( m_shouldReportUnexpected ) {
  7830. AssertionReaction dummyReaction;
  7831. handleUnexpectedInflightException( m_lastAssertionInfo, translateActiveException(), dummyReaction );
  7832. }
  7833. }
  7834. Counts assertions = m_totals.assertions - prevAssertions;
  7835. bool missingAssertions = testForMissingAssertions(assertions);
  7836. m_testCaseTracker->close();
  7837. handleUnfinishedSections();
  7838. m_messages.clear();
  7839. SectionStats testCaseSectionStats(testCaseSection, assertions, duration, missingAssertions);
  7840. m_reporter->sectionEnded(testCaseSectionStats);
  7841. }
  7842. void RunContext::invokeActiveTestCase() {
  7843. FatalConditionHandler fatalConditionHandler; // Handle signals
  7844. m_activeTestCase->invoke();
  7845. fatalConditionHandler.reset();
  7846. }
  7847. void RunContext::handleUnfinishedSections() {
  7848. // If sections ended prematurely due to an exception we stored their
  7849. // infos here so we can tear them down outside the unwind process.
  7850. for (auto it = m_unfinishedSections.rbegin(),
  7851. itEnd = m_unfinishedSections.rend();
  7852. it != itEnd;
  7853. ++it)
  7854. sectionEnded(*it);
  7855. m_unfinishedSections.clear();
  7856. }
  7857. void RunContext::handleExpr(
  7858. AssertionInfo const& info,
  7859. ITransientExpression const& expr,
  7860. AssertionReaction& reaction
  7861. ) {
  7862. m_reporter->assertionStarting( info );
  7863. bool negated = isFalseTest( info.resultDisposition );
  7864. bool result = expr.getResult() != negated;
  7865. if( result ) {
  7866. if (!m_includeSuccessfulResults) {
  7867. assertionPassed();
  7868. }
  7869. else {
  7870. reportExpr(info, ResultWas::Ok, &expr, negated);
  7871. }
  7872. }
  7873. else {
  7874. reportExpr(info, ResultWas::ExpressionFailed, &expr, negated );
  7875. populateReaction( reaction );
  7876. }
  7877. }
  7878. void RunContext::reportExpr(
  7879. AssertionInfo const &info,
  7880. ResultWas::OfType resultType,
  7881. ITransientExpression const *expr,
  7882. bool negated ) {
  7883. m_lastAssertionInfo = info;
  7884. AssertionResultData data( resultType, LazyExpression( negated ) );
  7885. AssertionResult assertionResult{ info, data };
  7886. assertionResult.m_resultData.lazyExpression.m_transientExpression = expr;
  7887. assertionEnded( assertionResult );
  7888. }
  7889. void RunContext::handleMessage(
  7890. AssertionInfo const& info,
  7891. ResultWas::OfType resultType,
  7892. StringRef const& message,
  7893. AssertionReaction& reaction
  7894. ) {
  7895. m_reporter->assertionStarting( info );
  7896. m_lastAssertionInfo = info;
  7897. AssertionResultData data( resultType, LazyExpression( false ) );
  7898. data.message = message;
  7899. AssertionResult assertionResult{ m_lastAssertionInfo, data };
  7900. assertionEnded( assertionResult );
  7901. if( !assertionResult.isOk() )
  7902. populateReaction( reaction );
  7903. }
  7904. void RunContext::handleUnexpectedExceptionNotThrown(
  7905. AssertionInfo const& info,
  7906. AssertionReaction& reaction
  7907. ) {
  7908. handleNonExpr(info, Catch::ResultWas::DidntThrowException, reaction);
  7909. }
  7910. void RunContext::handleUnexpectedInflightException(
  7911. AssertionInfo const& info,
  7912. std::string const& message,
  7913. AssertionReaction& reaction
  7914. ) {
  7915. m_lastAssertionInfo = info;
  7916. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  7917. data.message = message;
  7918. AssertionResult assertionResult{ info, data };
  7919. assertionEnded( assertionResult );
  7920. populateReaction( reaction );
  7921. }
  7922. void RunContext::populateReaction( AssertionReaction& reaction ) {
  7923. reaction.shouldDebugBreak = m_config->shouldDebugBreak();
  7924. reaction.shouldThrow = aborting() || (m_lastAssertionInfo.resultDisposition & ResultDisposition::Normal);
  7925. }
  7926. void RunContext::handleIncomplete(
  7927. AssertionInfo const& info
  7928. ) {
  7929. m_lastAssertionInfo = info;
  7930. AssertionResultData data( ResultWas::ThrewException, LazyExpression( false ) );
  7931. data.message = "Exception translation was disabled by CATCH_CONFIG_FAST_COMPILE";
  7932. AssertionResult assertionResult{ info, data };
  7933. assertionEnded( assertionResult );
  7934. }
  7935. void RunContext::handleNonExpr(
  7936. AssertionInfo const &info,
  7937. ResultWas::OfType resultType,
  7938. AssertionReaction &reaction
  7939. ) {
  7940. m_lastAssertionInfo = info;
  7941. AssertionResultData data( resultType, LazyExpression( false ) );
  7942. AssertionResult assertionResult{ info, data };
  7943. assertionEnded( assertionResult );
  7944. if( !assertionResult.isOk() )
  7945. populateReaction( reaction );
  7946. }
  7947. IResultCapture& getResultCapture() {
  7948. if (auto* capture = getCurrentContext().getResultCapture())
  7949. return *capture;
  7950. else
  7951. CATCH_INTERNAL_ERROR("No result capture instance");
  7952. }
  7953. }
  7954. // end catch_run_context.cpp
  7955. // start catch_section.cpp
  7956. namespace Catch {
  7957. Section::Section( SectionInfo const& info )
  7958. : m_info( info ),
  7959. m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) )
  7960. {
  7961. m_timer.start();
  7962. }
  7963. Section::~Section() {
  7964. if( m_sectionIncluded ) {
  7965. SectionEndInfo endInfo{ m_info, m_assertions, m_timer.getElapsedSeconds() };
  7966. if( uncaught_exceptions() )
  7967. getResultCapture().sectionEndedEarly( endInfo );
  7968. else
  7969. getResultCapture().sectionEnded( endInfo );
  7970. }
  7971. }
  7972. // This indicates whether the section should be executed or not
  7973. Section::operator bool() const {
  7974. return m_sectionIncluded;
  7975. }
  7976. } // end namespace Catch
  7977. // end catch_section.cpp
  7978. // start catch_section_info.cpp
  7979. namespace Catch {
  7980. SectionInfo::SectionInfo
  7981. ( SourceLineInfo const& _lineInfo,
  7982. std::string const& _name )
  7983. : name( _name ),
  7984. lineInfo( _lineInfo )
  7985. {}
  7986. } // end namespace Catch
  7987. // end catch_section_info.cpp
  7988. // start catch_session.cpp
  7989. // start catch_session.h
  7990. #include <memory>
  7991. namespace Catch {
  7992. class Session : NonCopyable {
  7993. public:
  7994. Session();
  7995. ~Session() override;
  7996. void showHelp() const;
  7997. void libIdentify();
  7998. int applyCommandLine( int argc, char const * const * argv );
  7999. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  8000. int applyCommandLine( int argc, wchar_t const * const * argv );
  8001. #endif
  8002. void useConfigData( ConfigData const& configData );
  8003. template<typename CharT>
  8004. int run(int argc, CharT const * const argv[]) {
  8005. if (m_startupExceptions)
  8006. return 1;
  8007. int returnCode = applyCommandLine(argc, argv);
  8008. if (returnCode == 0)
  8009. returnCode = run();
  8010. return returnCode;
  8011. }
  8012. int run();
  8013. clara::Parser const& cli() const;
  8014. void cli( clara::Parser const& newParser );
  8015. ConfigData& configData();
  8016. Config& config();
  8017. private:
  8018. int runInternal();
  8019. clara::Parser m_cli;
  8020. ConfigData m_configData;
  8021. std::shared_ptr<Config> m_config;
  8022. bool m_startupExceptions = false;
  8023. };
  8024. } // end namespace Catch
  8025. // end catch_session.h
  8026. // start catch_version.h
  8027. #include <iosfwd>
  8028. namespace Catch {
  8029. // Versioning information
  8030. struct Version {
  8031. Version( Version const& ) = delete;
  8032. Version& operator=( Version const& ) = delete;
  8033. Version( unsigned int _majorVersion,
  8034. unsigned int _minorVersion,
  8035. unsigned int _patchNumber,
  8036. char const * const _branchName,
  8037. unsigned int _buildNumber );
  8038. unsigned int const majorVersion;
  8039. unsigned int const minorVersion;
  8040. unsigned int const patchNumber;
  8041. // buildNumber is only used if branchName is not null
  8042. char const * const branchName;
  8043. unsigned int const buildNumber;
  8044. friend std::ostream& operator << ( std::ostream& os, Version const& version );
  8045. };
  8046. Version const& libraryVersion();
  8047. }
  8048. // end catch_version.h
  8049. #include <cstdlib>
  8050. #include <iomanip>
  8051. namespace Catch {
  8052. namespace {
  8053. const int MaxExitCode = 255;
  8054. IStreamingReporterPtr createReporter(std::string const& reporterName, IConfigPtr const& config) {
  8055. auto reporter = Catch::getRegistryHub().getReporterRegistry().create(reporterName, config);
  8056. CATCH_ENFORCE(reporter, "No reporter registered with name: '" << reporterName << "'");
  8057. return reporter;
  8058. }
  8059. IStreamingReporterPtr makeReporter(std::shared_ptr<Config> const& config) {
  8060. if (Catch::getRegistryHub().getReporterRegistry().getListeners().empty()) {
  8061. return createReporter(config->getReporterName(), config);
  8062. }
  8063. auto multi = std::unique_ptr<ListeningReporter>(new ListeningReporter);
  8064. auto const& listeners = Catch::getRegistryHub().getReporterRegistry().getListeners();
  8065. for (auto const& listener : listeners) {
  8066. multi->addListener(listener->create(Catch::ReporterConfig(config)));
  8067. }
  8068. multi->addReporter(createReporter(config->getReporterName(), config));
  8069. return std::move(multi);
  8070. }
  8071. Catch::Totals runTests(std::shared_ptr<Config> const& config) {
  8072. // FixMe: Add listeners in order first, then add reporters.
  8073. auto reporter = makeReporter(config);
  8074. RunContext context(config, std::move(reporter));
  8075. Totals totals;
  8076. context.testGroupStarting(config->name(), 1, 1);
  8077. TestSpec testSpec = config->testSpec();
  8078. auto const& allTestCases = getAllTestCasesSorted(*config);
  8079. for (auto const& testCase : allTestCases) {
  8080. if (!context.aborting() && matchTest(testCase, testSpec, *config))
  8081. totals += context.runTest(testCase);
  8082. else
  8083. context.reporter().skipTest(testCase);
  8084. }
  8085. if (config->warnAboutNoTests() && totals.testCases.total() == 0) {
  8086. ReusableStringStream testConfig;
  8087. bool first = true;
  8088. for (const auto& input : config->getTestsOrTags()) {
  8089. if (!first) { testConfig << ' '; }
  8090. first = false;
  8091. testConfig << input;
  8092. }
  8093. context.reporter().noMatchingTestCases(testConfig.str());
  8094. totals.error = -1;
  8095. }
  8096. context.testGroupEnded(config->name(), totals, 1, 1);
  8097. return totals;
  8098. }
  8099. void applyFilenamesAsTags(Catch::IConfig const& config) {
  8100. auto& tests = const_cast<std::vector<TestCase>&>(getAllTestCasesSorted(config));
  8101. for (auto& testCase : tests) {
  8102. auto tags = testCase.tags;
  8103. std::string filename = testCase.lineInfo.file;
  8104. auto lastSlash = filename.find_last_of("\\/");
  8105. if (lastSlash != std::string::npos) {
  8106. filename.erase(0, lastSlash);
  8107. filename[0] = '#';
  8108. }
  8109. auto lastDot = filename.find_last_of('.');
  8110. if (lastDot != std::string::npos) {
  8111. filename.erase(lastDot);
  8112. }
  8113. tags.push_back(std::move(filename));
  8114. setTags(testCase, tags);
  8115. }
  8116. }
  8117. } // anon namespace
  8118. Session::Session() {
  8119. static bool alreadyInstantiated = false;
  8120. if( alreadyInstantiated ) {
  8121. CATCH_TRY { CATCH_INTERNAL_ERROR( "Only one instance of Catch::Session can ever be used" ); }
  8122. CATCH_CATCH_ALL { getMutableRegistryHub().registerStartupException(); }
  8123. }
  8124. // There cannot be exceptions at startup in no-exception mode.
  8125. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8126. const auto& exceptions = getRegistryHub().getStartupExceptionRegistry().getExceptions();
  8127. if ( !exceptions.empty() ) {
  8128. m_startupExceptions = true;
  8129. Colour colourGuard( Colour::Red );
  8130. Catch::cerr() << "Errors occurred during startup!" << '\n';
  8131. // iterate over all exceptions and notify user
  8132. for ( const auto& ex_ptr : exceptions ) {
  8133. try {
  8134. std::rethrow_exception(ex_ptr);
  8135. } catch ( std::exception const& ex ) {
  8136. Catch::cerr() << Column( ex.what() ).indent(2) << '\n';
  8137. }
  8138. }
  8139. }
  8140. #endif
  8141. alreadyInstantiated = true;
  8142. m_cli = makeCommandLineParser( m_configData );
  8143. }
  8144. Session::~Session() {
  8145. Catch::cleanUp();
  8146. }
  8147. void Session::showHelp() const {
  8148. Catch::cout()
  8149. << "\nCatch v" << libraryVersion() << "\n"
  8150. << m_cli << std::endl
  8151. << "For more detailed usage please see the project docs\n" << std::endl;
  8152. }
  8153. void Session::libIdentify() {
  8154. Catch::cout()
  8155. << std::left << std::setw(16) << "description: " << "A Catch test executable\n"
  8156. << std::left << std::setw(16) << "category: " << "testframework\n"
  8157. << std::left << std::setw(16) << "framework: " << "Catch Test\n"
  8158. << std::left << std::setw(16) << "version: " << libraryVersion() << std::endl;
  8159. }
  8160. int Session::applyCommandLine( int argc, char const * const * argv ) {
  8161. if( m_startupExceptions )
  8162. return 1;
  8163. auto result = m_cli.parse( clara::Args( argc, argv ) );
  8164. if( !result ) {
  8165. Catch::cerr()
  8166. << Colour( Colour::Red )
  8167. << "\nError(s) in input:\n"
  8168. << Column( result.errorMessage() ).indent( 2 )
  8169. << "\n\n";
  8170. Catch::cerr() << "Run with -? for usage\n" << std::endl;
  8171. return MaxExitCode;
  8172. }
  8173. if( m_configData.showHelp )
  8174. showHelp();
  8175. if( m_configData.libIdentify )
  8176. libIdentify();
  8177. m_config.reset();
  8178. return 0;
  8179. }
  8180. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(UNICODE)
  8181. int Session::applyCommandLine( int argc, wchar_t const * const * argv ) {
  8182. char **utf8Argv = new char *[ argc ];
  8183. for ( int i = 0; i < argc; ++i ) {
  8184. int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
  8185. utf8Argv[ i ] = new char[ bufSize ];
  8186. WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
  8187. }
  8188. int returnCode = applyCommandLine( argc, utf8Argv );
  8189. for ( int i = 0; i < argc; ++i )
  8190. delete [] utf8Argv[ i ];
  8191. delete [] utf8Argv;
  8192. return returnCode;
  8193. }
  8194. #endif
  8195. void Session::useConfigData( ConfigData const& configData ) {
  8196. m_configData = configData;
  8197. m_config.reset();
  8198. }
  8199. int Session::run() {
  8200. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeStart ) != 0 ) {
  8201. Catch::cout() << "...waiting for enter/ return before starting" << std::endl;
  8202. static_cast<void>(std::getchar());
  8203. }
  8204. int exitCode = runInternal();
  8205. if( ( m_configData.waitForKeypress & WaitForKeypress::BeforeExit ) != 0 ) {
  8206. Catch::cout() << "...waiting for enter/ return before exiting, with code: " << exitCode << std::endl;
  8207. static_cast<void>(std::getchar());
  8208. }
  8209. return exitCode;
  8210. }
  8211. clara::Parser const& Session::cli() const {
  8212. return m_cli;
  8213. }
  8214. void Session::cli( clara::Parser const& newParser ) {
  8215. m_cli = newParser;
  8216. }
  8217. ConfigData& Session::configData() {
  8218. return m_configData;
  8219. }
  8220. Config& Session::config() {
  8221. if( !m_config )
  8222. m_config = std::make_shared<Config>( m_configData );
  8223. return *m_config;
  8224. }
  8225. int Session::runInternal() {
  8226. if( m_startupExceptions )
  8227. return 1;
  8228. if (m_configData.showHelp || m_configData.libIdentify) {
  8229. return 0;
  8230. }
  8231. CATCH_TRY {
  8232. config(); // Force config to be constructed
  8233. seedRng( *m_config );
  8234. if( m_configData.filenamesAsTags )
  8235. applyFilenamesAsTags( *m_config );
  8236. // Handle list request
  8237. if( Option<std::size_t> listed = list( config() ) )
  8238. return static_cast<int>( *listed );
  8239. auto totals = runTests( m_config );
  8240. // Note that on unices only the lower 8 bits are usually used, clamping
  8241. // the return value to 255 prevents false negative when some multiple
  8242. // of 256 tests has failed
  8243. return (std::min) (MaxExitCode, (std::max) (totals.error, static_cast<int>(totals.assertions.failed)));
  8244. }
  8245. #if !defined(CATCH_CONFIG_DISABLE_EXCEPTIONS)
  8246. catch( std::exception& ex ) {
  8247. Catch::cerr() << ex.what() << std::endl;
  8248. return MaxExitCode;
  8249. }
  8250. #endif
  8251. }
  8252. } // end namespace Catch
  8253. // end catch_session.cpp
  8254. // start catch_singletons.cpp
  8255. #include <vector>
  8256. namespace Catch {
  8257. namespace {
  8258. static auto getSingletons() -> std::vector<ISingleton*>*& {
  8259. static std::vector<ISingleton*>* g_singletons = nullptr;
  8260. if( !g_singletons )
  8261. g_singletons = new std::vector<ISingleton*>();
  8262. return g_singletons;
  8263. }
  8264. }
  8265. ISingleton::~ISingleton() {}
  8266. void addSingleton(ISingleton* singleton ) {
  8267. getSingletons()->push_back( singleton );
  8268. }
  8269. void cleanupSingletons() {
  8270. auto& singletons = getSingletons();
  8271. for( auto singleton : *singletons )
  8272. delete singleton;
  8273. delete singletons;
  8274. singletons = nullptr;
  8275. }
  8276. } // namespace Catch
  8277. // end catch_singletons.cpp
  8278. // start catch_startup_exception_registry.cpp
  8279. namespace Catch {
  8280. void StartupExceptionRegistry::add( std::exception_ptr const& exception ) noexcept {
  8281. CATCH_TRY {
  8282. m_exceptions.push_back(exception);
  8283. } CATCH_CATCH_ALL {
  8284. // If we run out of memory during start-up there's really not a lot more we can do about it
  8285. std::terminate();
  8286. }
  8287. }
  8288. std::vector<std::exception_ptr> const& StartupExceptionRegistry::getExceptions() const noexcept {
  8289. return m_exceptions;
  8290. }
  8291. } // end namespace Catch
  8292. // end catch_startup_exception_registry.cpp
  8293. // start catch_stream.cpp
  8294. #include <cstdio>
  8295. #include <iostream>
  8296. #include <fstream>
  8297. #include <sstream>
  8298. #include <vector>
  8299. #include <memory>
  8300. namespace Catch {
  8301. Catch::IStream::~IStream() = default;
  8302. namespace detail { namespace {
  8303. template<typename WriterF, std::size_t bufferSize=256>
  8304. class StreamBufImpl : public std::streambuf {
  8305. char data[bufferSize];
  8306. WriterF m_writer;
  8307. public:
  8308. StreamBufImpl() {
  8309. setp( data, data + sizeof(data) );
  8310. }
  8311. ~StreamBufImpl() noexcept {
  8312. StreamBufImpl::sync();
  8313. }
  8314. private:
  8315. int overflow( int c ) override {
  8316. sync();
  8317. if( c != EOF ) {
  8318. if( pbase() == epptr() )
  8319. m_writer( std::string( 1, static_cast<char>( c ) ) );
  8320. else
  8321. sputc( static_cast<char>( c ) );
  8322. }
  8323. return 0;
  8324. }
  8325. int sync() override {
  8326. if( pbase() != pptr() ) {
  8327. m_writer( std::string( pbase(), static_cast<std::string::size_type>( pptr() - pbase() ) ) );
  8328. setp( pbase(), epptr() );
  8329. }
  8330. return 0;
  8331. }
  8332. };
  8333. ///////////////////////////////////////////////////////////////////////////
  8334. struct OutputDebugWriter {
  8335. void operator()( std::string const&str ) {
  8336. writeToDebugConsole( str );
  8337. }
  8338. };
  8339. ///////////////////////////////////////////////////////////////////////////
  8340. class FileStream : public IStream {
  8341. mutable std::ofstream m_ofs;
  8342. public:
  8343. FileStream( StringRef filename ) {
  8344. m_ofs.open( filename.c_str() );
  8345. CATCH_ENFORCE( !m_ofs.fail(), "Unable to open file: '" << filename << "'" );
  8346. }
  8347. ~FileStream() override = default;
  8348. public: // IStream
  8349. std::ostream& stream() const override {
  8350. return m_ofs;
  8351. }
  8352. };
  8353. ///////////////////////////////////////////////////////////////////////////
  8354. class CoutStream : public IStream {
  8355. mutable std::ostream m_os;
  8356. public:
  8357. // Store the streambuf from cout up-front because
  8358. // cout may get redirected when running tests
  8359. CoutStream() : m_os( Catch::cout().rdbuf() ) {}
  8360. ~CoutStream() override = default;
  8361. public: // IStream
  8362. std::ostream& stream() const override { return m_os; }
  8363. };
  8364. ///////////////////////////////////////////////////////////////////////////
  8365. class DebugOutStream : public IStream {
  8366. std::unique_ptr<StreamBufImpl<OutputDebugWriter>> m_streamBuf;
  8367. mutable std::ostream m_os;
  8368. public:
  8369. DebugOutStream()
  8370. : m_streamBuf( new StreamBufImpl<OutputDebugWriter>() ),
  8371. m_os( m_streamBuf.get() )
  8372. {}
  8373. ~DebugOutStream() override = default;
  8374. public: // IStream
  8375. std::ostream& stream() const override { return m_os; }
  8376. };
  8377. }} // namespace anon::detail
  8378. ///////////////////////////////////////////////////////////////////////////
  8379. auto makeStream( StringRef const &filename ) -> IStream const* {
  8380. if( filename.empty() )
  8381. return new detail::CoutStream();
  8382. else if( filename[0] == '%' ) {
  8383. if( filename == "%debug" )
  8384. return new detail::DebugOutStream();
  8385. else
  8386. CATCH_ERROR( "Unrecognised stream: '" << filename << "'" );
  8387. }
  8388. else
  8389. return new detail::FileStream( filename );
  8390. }
  8391. // This class encapsulates the idea of a pool of ostringstreams that can be reused.
  8392. struct StringStreams {
  8393. std::vector<std::unique_ptr<std::ostringstream>> m_streams;
  8394. std::vector<std::size_t> m_unused;
  8395. std::ostringstream m_referenceStream; // Used for copy state/ flags from
  8396. auto add() -> std::size_t {
  8397. if( m_unused.empty() ) {
  8398. m_streams.push_back( std::unique_ptr<std::ostringstream>( new std::ostringstream ) );
  8399. return m_streams.size()-1;
  8400. }
  8401. else {
  8402. auto index = m_unused.back();
  8403. m_unused.pop_back();
  8404. return index;
  8405. }
  8406. }
  8407. void release( std::size_t index ) {
  8408. m_streams[index]->copyfmt( m_referenceStream ); // Restore initial flags and other state
  8409. m_unused.push_back(index);
  8410. }
  8411. };
  8412. ReusableStringStream::ReusableStringStream()
  8413. : m_index( Singleton<StringStreams>::getMutable().add() ),
  8414. m_oss( Singleton<StringStreams>::getMutable().m_streams[m_index].get() )
  8415. {}
  8416. ReusableStringStream::~ReusableStringStream() {
  8417. static_cast<std::ostringstream*>( m_oss )->str("");
  8418. m_oss->clear();
  8419. Singleton<StringStreams>::getMutable().release( m_index );
  8420. }
  8421. auto ReusableStringStream::str() const -> std::string {
  8422. return static_cast<std::ostringstream*>( m_oss )->str();
  8423. }
  8424. ///////////////////////////////////////////////////////////////////////////
  8425. #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions
  8426. std::ostream& cout() { return std::cout; }
  8427. std::ostream& cerr() { return std::cerr; }
  8428. std::ostream& clog() { return std::clog; }
  8429. #endif
  8430. }
  8431. // end catch_stream.cpp
  8432. // start catch_string_manip.cpp
  8433. #include <algorithm>
  8434. #include <ostream>
  8435. #include <cstring>
  8436. #include <cctype>
  8437. namespace Catch {
  8438. namespace {
  8439. char toLowerCh(char c) {
  8440. return static_cast<char>( std::tolower( c ) );
  8441. }
  8442. }
  8443. bool startsWith( std::string const& s, std::string const& prefix ) {
  8444. return s.size() >= prefix.size() && std::equal(prefix.begin(), prefix.end(), s.begin());
  8445. }
  8446. bool startsWith( std::string const& s, char prefix ) {
  8447. return !s.empty() && s[0] == prefix;
  8448. }
  8449. bool endsWith( std::string const& s, std::string const& suffix ) {
  8450. return s.size() >= suffix.size() && std::equal(suffix.rbegin(), suffix.rend(), s.rbegin());
  8451. }
  8452. bool endsWith( std::string const& s, char suffix ) {
  8453. return !s.empty() && s[s.size()-1] == suffix;
  8454. }
  8455. bool contains( std::string const& s, std::string const& infix ) {
  8456. return s.find( infix ) != std::string::npos;
  8457. }
  8458. void toLowerInPlace( std::string& s ) {
  8459. std::transform( s.begin(), s.end(), s.begin(), toLowerCh );
  8460. }
  8461. std::string toLower( std::string const& s ) {
  8462. std::string lc = s;
  8463. toLowerInPlace( lc );
  8464. return lc;
  8465. }
  8466. std::string trim( std::string const& str ) {
  8467. static char const* whitespaceChars = "\n\r\t ";
  8468. std::string::size_type start = str.find_first_not_of( whitespaceChars );
  8469. std::string::size_type end = str.find_last_not_of( whitespaceChars );
  8470. return start != std::string::npos ? str.substr( start, 1+end-start ) : std::string();
  8471. }
  8472. bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) {
  8473. bool replaced = false;
  8474. std::size_t i = str.find( replaceThis );
  8475. while( i != std::string::npos ) {
  8476. replaced = true;
  8477. str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() );
  8478. if( i < str.size()-withThis.size() )
  8479. i = str.find( replaceThis, i+withThis.size() );
  8480. else
  8481. i = std::string::npos;
  8482. }
  8483. return replaced;
  8484. }
  8485. pluralise::pluralise( std::size_t count, std::string const& label )
  8486. : m_count( count ),
  8487. m_label( label )
  8488. {}
  8489. std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) {
  8490. os << pluraliser.m_count << ' ' << pluraliser.m_label;
  8491. if( pluraliser.m_count != 1 )
  8492. os << 's';
  8493. return os;
  8494. }
  8495. }
  8496. // end catch_string_manip.cpp
  8497. // start catch_stringref.cpp
  8498. #if defined(__clang__)
  8499. # pragma clang diagnostic push
  8500. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8501. #endif
  8502. #include <ostream>
  8503. #include <cstring>
  8504. #include <cstdint>
  8505. namespace {
  8506. const uint32_t byte_2_lead = 0xC0;
  8507. const uint32_t byte_3_lead = 0xE0;
  8508. const uint32_t byte_4_lead = 0xF0;
  8509. }
  8510. namespace Catch {
  8511. StringRef::StringRef( char const* rawChars ) noexcept
  8512. : StringRef( rawChars, static_cast<StringRef::size_type>(std::strlen(rawChars) ) )
  8513. {}
  8514. StringRef::operator std::string() const {
  8515. return std::string( m_start, m_size );
  8516. }
  8517. void StringRef::swap( StringRef& other ) noexcept {
  8518. std::swap( m_start, other.m_start );
  8519. std::swap( m_size, other.m_size );
  8520. std::swap( m_data, other.m_data );
  8521. }
  8522. auto StringRef::c_str() const -> char const* {
  8523. if( isSubstring() )
  8524. const_cast<StringRef*>( this )->takeOwnership();
  8525. return m_start;
  8526. }
  8527. auto StringRef::currentData() const noexcept -> char const* {
  8528. return m_start;
  8529. }
  8530. auto StringRef::isOwned() const noexcept -> bool {
  8531. return m_data != nullptr;
  8532. }
  8533. auto StringRef::isSubstring() const noexcept -> bool {
  8534. return m_start[m_size] != '\0';
  8535. }
  8536. void StringRef::takeOwnership() {
  8537. if( !isOwned() ) {
  8538. m_data = new char[m_size+1];
  8539. memcpy( m_data, m_start, m_size );
  8540. m_data[m_size] = '\0';
  8541. m_start = m_data;
  8542. }
  8543. }
  8544. auto StringRef::substr( size_type start, size_type size ) const noexcept -> StringRef {
  8545. if( start < m_size )
  8546. return StringRef( m_start+start, size );
  8547. else
  8548. return StringRef();
  8549. }
  8550. auto StringRef::operator == ( StringRef const& other ) const noexcept -> bool {
  8551. return
  8552. size() == other.size() &&
  8553. (std::strncmp( m_start, other.m_start, size() ) == 0);
  8554. }
  8555. auto StringRef::operator != ( StringRef const& other ) const noexcept -> bool {
  8556. return !operator==( other );
  8557. }
  8558. auto StringRef::operator[](size_type index) const noexcept -> char {
  8559. return m_start[index];
  8560. }
  8561. auto StringRef::numberOfCharacters() const noexcept -> size_type {
  8562. size_type noChars = m_size;
  8563. // Make adjustments for uft encodings
  8564. for( size_type i=0; i < m_size; ++i ) {
  8565. char c = m_start[i];
  8566. if( ( c & byte_2_lead ) == byte_2_lead ) {
  8567. noChars--;
  8568. if (( c & byte_3_lead ) == byte_3_lead )
  8569. noChars--;
  8570. if( ( c & byte_4_lead ) == byte_4_lead )
  8571. noChars--;
  8572. }
  8573. }
  8574. return noChars;
  8575. }
  8576. auto operator + ( StringRef const& lhs, StringRef const& rhs ) -> std::string {
  8577. std::string str;
  8578. str.reserve( lhs.size() + rhs.size() );
  8579. str += lhs;
  8580. str += rhs;
  8581. return str;
  8582. }
  8583. auto operator + ( StringRef const& lhs, const char* rhs ) -> std::string {
  8584. return std::string( lhs ) + std::string( rhs );
  8585. }
  8586. auto operator + ( char const* lhs, StringRef const& rhs ) -> std::string {
  8587. return std::string( lhs ) + std::string( rhs );
  8588. }
  8589. auto operator << ( std::ostream& os, StringRef const& str ) -> std::ostream& {
  8590. return os.write(str.currentData(), str.size());
  8591. }
  8592. auto operator+=( std::string& lhs, StringRef const& rhs ) -> std::string& {
  8593. lhs.append(rhs.currentData(), rhs.size());
  8594. return lhs;
  8595. }
  8596. } // namespace Catch
  8597. #if defined(__clang__)
  8598. # pragma clang diagnostic pop
  8599. #endif
  8600. // end catch_stringref.cpp
  8601. // start catch_tag_alias.cpp
  8602. namespace Catch {
  8603. TagAlias::TagAlias(std::string const & _tag, SourceLineInfo _lineInfo): tag(_tag), lineInfo(_lineInfo) {}
  8604. }
  8605. // end catch_tag_alias.cpp
  8606. // start catch_tag_alias_autoregistrar.cpp
  8607. namespace Catch {
  8608. RegistrarForTagAliases::RegistrarForTagAliases(char const* alias, char const* tag, SourceLineInfo const& lineInfo) {
  8609. CATCH_TRY {
  8610. getMutableRegistryHub().registerTagAlias(alias, tag, lineInfo);
  8611. } CATCH_CATCH_ALL {
  8612. // Do not throw when constructing global objects, instead register the exception to be processed later
  8613. getMutableRegistryHub().registerStartupException();
  8614. }
  8615. }
  8616. }
  8617. // end catch_tag_alias_autoregistrar.cpp
  8618. // start catch_tag_alias_registry.cpp
  8619. #include <sstream>
  8620. namespace Catch {
  8621. TagAliasRegistry::~TagAliasRegistry() {}
  8622. TagAlias const* TagAliasRegistry::find( std::string const& alias ) const {
  8623. auto it = m_registry.find( alias );
  8624. if( it != m_registry.end() )
  8625. return &(it->second);
  8626. else
  8627. return nullptr;
  8628. }
  8629. std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const {
  8630. std::string expandedTestSpec = unexpandedTestSpec;
  8631. for( auto const& registryKvp : m_registry ) {
  8632. std::size_t pos = expandedTestSpec.find( registryKvp.first );
  8633. if( pos != std::string::npos ) {
  8634. expandedTestSpec = expandedTestSpec.substr( 0, pos ) +
  8635. registryKvp.second.tag +
  8636. expandedTestSpec.substr( pos + registryKvp.first.size() );
  8637. }
  8638. }
  8639. return expandedTestSpec;
  8640. }
  8641. void TagAliasRegistry::add( std::string const& alias, std::string const& tag, SourceLineInfo const& lineInfo ) {
  8642. CATCH_ENFORCE( startsWith(alias, "[@") && endsWith(alias, ']'),
  8643. "error: tag alias, '" << alias << "' is not of the form [@alias name].\n" << lineInfo );
  8644. CATCH_ENFORCE( m_registry.insert(std::make_pair(alias, TagAlias(tag, lineInfo))).second,
  8645. "error: tag alias, '" << alias << "' already registered.\n"
  8646. << "\tFirst seen at: " << find(alias)->lineInfo << "\n"
  8647. << "\tRedefined at: " << lineInfo );
  8648. }
  8649. ITagAliasRegistry::~ITagAliasRegistry() {}
  8650. ITagAliasRegistry const& ITagAliasRegistry::get() {
  8651. return getRegistryHub().getTagAliasRegistry();
  8652. }
  8653. } // end namespace Catch
  8654. // end catch_tag_alias_registry.cpp
  8655. // start catch_test_case_info.cpp
  8656. #include <cctype>
  8657. #include <exception>
  8658. #include <algorithm>
  8659. #include <sstream>
  8660. namespace Catch {
  8661. namespace {
  8662. TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) {
  8663. if( startsWith( tag, '.' ) ||
  8664. tag == "!hide" )
  8665. return TestCaseInfo::IsHidden;
  8666. else if( tag == "!throws" )
  8667. return TestCaseInfo::Throws;
  8668. else if( tag == "!shouldfail" )
  8669. return TestCaseInfo::ShouldFail;
  8670. else if( tag == "!mayfail" )
  8671. return TestCaseInfo::MayFail;
  8672. else if( tag == "!nonportable" )
  8673. return TestCaseInfo::NonPortable;
  8674. else if( tag == "!benchmark" )
  8675. return static_cast<TestCaseInfo::SpecialProperties>( TestCaseInfo::Benchmark | TestCaseInfo::IsHidden );
  8676. else
  8677. return TestCaseInfo::None;
  8678. }
  8679. bool isReservedTag( std::string const& tag ) {
  8680. return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !std::isalnum( static_cast<unsigned char>(tag[0]) );
  8681. }
  8682. void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) {
  8683. CATCH_ENFORCE( !isReservedTag(tag),
  8684. "Tag name: [" << tag << "] is not allowed.\n"
  8685. << "Tag names starting with non alpha-numeric characters are reserved\n"
  8686. << _lineInfo );
  8687. }
  8688. }
  8689. TestCase makeTestCase( ITestInvoker* _testCase,
  8690. std::string const& _className,
  8691. NameAndTags const& nameAndTags,
  8692. SourceLineInfo const& _lineInfo )
  8693. {
  8694. bool isHidden = false;
  8695. // Parse out tags
  8696. std::vector<std::string> tags;
  8697. std::string desc, tag;
  8698. bool inTag = false;
  8699. std::string _descOrTags = nameAndTags.tags;
  8700. for (char c : _descOrTags) {
  8701. if( !inTag ) {
  8702. if( c == '[' )
  8703. inTag = true;
  8704. else
  8705. desc += c;
  8706. }
  8707. else {
  8708. if( c == ']' ) {
  8709. TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag );
  8710. if( ( prop & TestCaseInfo::IsHidden ) != 0 )
  8711. isHidden = true;
  8712. else if( prop == TestCaseInfo::None )
  8713. enforceNotReservedTag( tag, _lineInfo );
  8714. tags.push_back( tag );
  8715. tag.clear();
  8716. inTag = false;
  8717. }
  8718. else
  8719. tag += c;
  8720. }
  8721. }
  8722. if( isHidden ) {
  8723. tags.push_back( "." );
  8724. }
  8725. TestCaseInfo info( nameAndTags.name, _className, desc, tags, _lineInfo );
  8726. return TestCase( _testCase, std::move(info) );
  8727. }
  8728. void setTags( TestCaseInfo& testCaseInfo, std::vector<std::string> tags ) {
  8729. std::sort(begin(tags), end(tags));
  8730. tags.erase(std::unique(begin(tags), end(tags)), end(tags));
  8731. testCaseInfo.lcaseTags.clear();
  8732. for( auto const& tag : tags ) {
  8733. std::string lcaseTag = toLower( tag );
  8734. testCaseInfo.properties = static_cast<TestCaseInfo::SpecialProperties>( testCaseInfo.properties | parseSpecialTag( lcaseTag ) );
  8735. testCaseInfo.lcaseTags.push_back( lcaseTag );
  8736. }
  8737. testCaseInfo.tags = std::move(tags);
  8738. }
  8739. TestCaseInfo::TestCaseInfo( std::string const& _name,
  8740. std::string const& _className,
  8741. std::string const& _description,
  8742. std::vector<std::string> const& _tags,
  8743. SourceLineInfo const& _lineInfo )
  8744. : name( _name ),
  8745. className( _className ),
  8746. description( _description ),
  8747. lineInfo( _lineInfo ),
  8748. properties( None )
  8749. {
  8750. setTags( *this, _tags );
  8751. }
  8752. bool TestCaseInfo::isHidden() const {
  8753. return ( properties & IsHidden ) != 0;
  8754. }
  8755. bool TestCaseInfo::throws() const {
  8756. return ( properties & Throws ) != 0;
  8757. }
  8758. bool TestCaseInfo::okToFail() const {
  8759. return ( properties & (ShouldFail | MayFail ) ) != 0;
  8760. }
  8761. bool TestCaseInfo::expectedToFail() const {
  8762. return ( properties & (ShouldFail ) ) != 0;
  8763. }
  8764. std::string TestCaseInfo::tagsAsString() const {
  8765. std::string ret;
  8766. // '[' and ']' per tag
  8767. std::size_t full_size = 2 * tags.size();
  8768. for (const auto& tag : tags) {
  8769. full_size += tag.size();
  8770. }
  8771. ret.reserve(full_size);
  8772. for (const auto& tag : tags) {
  8773. ret.push_back('[');
  8774. ret.append(tag);
  8775. ret.push_back(']');
  8776. }
  8777. return ret;
  8778. }
  8779. TestCase::TestCase( ITestInvoker* testCase, TestCaseInfo&& info ) : TestCaseInfo( std::move(info) ), test( testCase ) {}
  8780. TestCase TestCase::withName( std::string const& _newName ) const {
  8781. TestCase other( *this );
  8782. other.name = _newName;
  8783. return other;
  8784. }
  8785. void TestCase::invoke() const {
  8786. test->invoke();
  8787. }
  8788. bool TestCase::operator == ( TestCase const& other ) const {
  8789. return test.get() == other.test.get() &&
  8790. name == other.name &&
  8791. className == other.className;
  8792. }
  8793. bool TestCase::operator < ( TestCase const& other ) const {
  8794. return name < other.name;
  8795. }
  8796. TestCaseInfo const& TestCase::getTestCaseInfo() const
  8797. {
  8798. return *this;
  8799. }
  8800. } // end namespace Catch
  8801. // end catch_test_case_info.cpp
  8802. // start catch_test_case_registry_impl.cpp
  8803. #include <sstream>
  8804. namespace Catch {
  8805. std::vector<TestCase> sortTests( IConfig const& config, std::vector<TestCase> const& unsortedTestCases ) {
  8806. std::vector<TestCase> sorted = unsortedTestCases;
  8807. switch( config.runOrder() ) {
  8808. case RunTests::InLexicographicalOrder:
  8809. std::sort( sorted.begin(), sorted.end() );
  8810. break;
  8811. case RunTests::InRandomOrder:
  8812. seedRng( config );
  8813. std::shuffle( sorted.begin(), sorted.end(), rng() );
  8814. break;
  8815. case RunTests::InDeclarationOrder:
  8816. // already in declaration order
  8817. break;
  8818. }
  8819. return sorted;
  8820. }
  8821. bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) {
  8822. return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() );
  8823. }
  8824. void enforceNoDuplicateTestCases( std::vector<TestCase> const& functions ) {
  8825. std::set<TestCase> seenFunctions;
  8826. for( auto const& function : functions ) {
  8827. auto prev = seenFunctions.insert( function );
  8828. CATCH_ENFORCE( prev.second,
  8829. "error: TEST_CASE( \"" << function.name << "\" ) already defined.\n"
  8830. << "\tFirst seen at " << prev.first->getTestCaseInfo().lineInfo << "\n"
  8831. << "\tRedefined at " << function.getTestCaseInfo().lineInfo );
  8832. }
  8833. }
  8834. std::vector<TestCase> filterTests( std::vector<TestCase> const& testCases, TestSpec const& testSpec, IConfig const& config ) {
  8835. std::vector<TestCase> filtered;
  8836. filtered.reserve( testCases.size() );
  8837. for( auto const& testCase : testCases )
  8838. if( matchTest( testCase, testSpec, config ) )
  8839. filtered.push_back( testCase );
  8840. return filtered;
  8841. }
  8842. std::vector<TestCase> const& getAllTestCasesSorted( IConfig const& config ) {
  8843. return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config );
  8844. }
  8845. void TestRegistry::registerTest( TestCase const& testCase ) {
  8846. std::string name = testCase.getTestCaseInfo().name;
  8847. if( name.empty() ) {
  8848. ReusableStringStream rss;
  8849. rss << "Anonymous test case " << ++m_unnamedCount;
  8850. return registerTest( testCase.withName( rss.str() ) );
  8851. }
  8852. m_functions.push_back( testCase );
  8853. }
  8854. std::vector<TestCase> const& TestRegistry::getAllTests() const {
  8855. return m_functions;
  8856. }
  8857. std::vector<TestCase> const& TestRegistry::getAllTestsSorted( IConfig const& config ) const {
  8858. if( m_sortedFunctions.empty() )
  8859. enforceNoDuplicateTestCases( m_functions );
  8860. if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) {
  8861. m_sortedFunctions = sortTests( config, m_functions );
  8862. m_currentSortOrder = config.runOrder();
  8863. }
  8864. return m_sortedFunctions;
  8865. }
  8866. ///////////////////////////////////////////////////////////////////////////
  8867. TestInvokerAsFunction::TestInvokerAsFunction( void(*testAsFunction)() ) noexcept : m_testAsFunction( testAsFunction ) {}
  8868. void TestInvokerAsFunction::invoke() const {
  8869. m_testAsFunction();
  8870. }
  8871. std::string extractClassName( StringRef const& classOrQualifiedMethodName ) {
  8872. std::string className = classOrQualifiedMethodName;
  8873. if( startsWith( className, '&' ) )
  8874. {
  8875. std::size_t lastColons = className.rfind( "::" );
  8876. std::size_t penultimateColons = className.rfind( "::", lastColons-1 );
  8877. if( penultimateColons == std::string::npos )
  8878. penultimateColons = 1;
  8879. className = className.substr( penultimateColons, lastColons-penultimateColons );
  8880. }
  8881. return className;
  8882. }
  8883. } // end namespace Catch
  8884. // end catch_test_case_registry_impl.cpp
  8885. // start catch_test_case_tracker.cpp
  8886. #include <algorithm>
  8887. #include <cassert>
  8888. #include <stdexcept>
  8889. #include <memory>
  8890. #include <sstream>
  8891. #if defined(__clang__)
  8892. # pragma clang diagnostic push
  8893. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  8894. #endif
  8895. namespace Catch {
  8896. namespace TestCaseTracking {
  8897. NameAndLocation::NameAndLocation( std::string const& _name, SourceLineInfo const& _location )
  8898. : name( _name ),
  8899. location( _location )
  8900. {}
  8901. ITracker::~ITracker() = default;
  8902. TrackerContext& TrackerContext::instance() {
  8903. static TrackerContext s_instance;
  8904. return s_instance;
  8905. }
  8906. ITracker& TrackerContext::startRun() {
  8907. m_rootTracker = std::make_shared<SectionTracker>( NameAndLocation( "{root}", CATCH_INTERNAL_LINEINFO ), *this, nullptr );
  8908. m_currentTracker = nullptr;
  8909. m_runState = Executing;
  8910. return *m_rootTracker;
  8911. }
  8912. void TrackerContext::endRun() {
  8913. m_rootTracker.reset();
  8914. m_currentTracker = nullptr;
  8915. m_runState = NotStarted;
  8916. }
  8917. void TrackerContext::startCycle() {
  8918. m_currentTracker = m_rootTracker.get();
  8919. m_runState = Executing;
  8920. }
  8921. void TrackerContext::completeCycle() {
  8922. m_runState = CompletedCycle;
  8923. }
  8924. bool TrackerContext::completedCycle() const {
  8925. return m_runState == CompletedCycle;
  8926. }
  8927. ITracker& TrackerContext::currentTracker() {
  8928. return *m_currentTracker;
  8929. }
  8930. void TrackerContext::setCurrentTracker( ITracker* tracker ) {
  8931. m_currentTracker = tracker;
  8932. }
  8933. TrackerBase::TrackerBase( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  8934. : m_nameAndLocation( nameAndLocation ),
  8935. m_ctx( ctx ),
  8936. m_parent( parent )
  8937. {}
  8938. NameAndLocation const& TrackerBase::nameAndLocation() const {
  8939. return m_nameAndLocation;
  8940. }
  8941. bool TrackerBase::isComplete() const {
  8942. return m_runState == CompletedSuccessfully || m_runState == Failed;
  8943. }
  8944. bool TrackerBase::isSuccessfullyCompleted() const {
  8945. return m_runState == CompletedSuccessfully;
  8946. }
  8947. bool TrackerBase::isOpen() const {
  8948. return m_runState != NotStarted && !isComplete();
  8949. }
  8950. bool TrackerBase::hasChildren() const {
  8951. return !m_children.empty();
  8952. }
  8953. void TrackerBase::addChild( ITrackerPtr const& child ) {
  8954. m_children.push_back( child );
  8955. }
  8956. ITrackerPtr TrackerBase::findChild( NameAndLocation const& nameAndLocation ) {
  8957. auto it = std::find_if( m_children.begin(), m_children.end(),
  8958. [&nameAndLocation]( ITrackerPtr const& tracker ){
  8959. return
  8960. tracker->nameAndLocation().location == nameAndLocation.location &&
  8961. tracker->nameAndLocation().name == nameAndLocation.name;
  8962. } );
  8963. return( it != m_children.end() )
  8964. ? *it
  8965. : nullptr;
  8966. }
  8967. ITracker& TrackerBase::parent() {
  8968. assert( m_parent ); // Should always be non-null except for root
  8969. return *m_parent;
  8970. }
  8971. void TrackerBase::openChild() {
  8972. if( m_runState != ExecutingChildren ) {
  8973. m_runState = ExecutingChildren;
  8974. if( m_parent )
  8975. m_parent->openChild();
  8976. }
  8977. }
  8978. bool TrackerBase::isSectionTracker() const { return false; }
  8979. bool TrackerBase::isIndexTracker() const { return false; }
  8980. void TrackerBase::open() {
  8981. m_runState = Executing;
  8982. moveToThis();
  8983. if( m_parent )
  8984. m_parent->openChild();
  8985. }
  8986. void TrackerBase::close() {
  8987. // Close any still open children (e.g. generators)
  8988. while( &m_ctx.currentTracker() != this )
  8989. m_ctx.currentTracker().close();
  8990. switch( m_runState ) {
  8991. case NeedsAnotherRun:
  8992. break;
  8993. case Executing:
  8994. m_runState = CompletedSuccessfully;
  8995. break;
  8996. case ExecutingChildren:
  8997. if( m_children.empty() || m_children.back()->isComplete() )
  8998. m_runState = CompletedSuccessfully;
  8999. break;
  9000. case NotStarted:
  9001. case CompletedSuccessfully:
  9002. case Failed:
  9003. CATCH_INTERNAL_ERROR( "Illogical state: " << m_runState );
  9004. default:
  9005. CATCH_INTERNAL_ERROR( "Unknown state: " << m_runState );
  9006. }
  9007. moveToParent();
  9008. m_ctx.completeCycle();
  9009. }
  9010. void TrackerBase::fail() {
  9011. m_runState = Failed;
  9012. if( m_parent )
  9013. m_parent->markAsNeedingAnotherRun();
  9014. moveToParent();
  9015. m_ctx.completeCycle();
  9016. }
  9017. void TrackerBase::markAsNeedingAnotherRun() {
  9018. m_runState = NeedsAnotherRun;
  9019. }
  9020. void TrackerBase::moveToParent() {
  9021. assert( m_parent );
  9022. m_ctx.setCurrentTracker( m_parent );
  9023. }
  9024. void TrackerBase::moveToThis() {
  9025. m_ctx.setCurrentTracker( this );
  9026. }
  9027. SectionTracker::SectionTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent )
  9028. : TrackerBase( nameAndLocation, ctx, parent )
  9029. {
  9030. if( parent ) {
  9031. while( !parent->isSectionTracker() )
  9032. parent = &parent->parent();
  9033. SectionTracker& parentSection = static_cast<SectionTracker&>( *parent );
  9034. addNextFilters( parentSection.m_filters );
  9035. }
  9036. }
  9037. bool SectionTracker::isSectionTracker() const { return true; }
  9038. SectionTracker& SectionTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation ) {
  9039. std::shared_ptr<SectionTracker> section;
  9040. ITracker& currentTracker = ctx.currentTracker();
  9041. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  9042. assert( childTracker );
  9043. assert( childTracker->isSectionTracker() );
  9044. section = std::static_pointer_cast<SectionTracker>( childTracker );
  9045. }
  9046. else {
  9047. section = std::make_shared<SectionTracker>( nameAndLocation, ctx, &currentTracker );
  9048. currentTracker.addChild( section );
  9049. }
  9050. if( !ctx.completedCycle() )
  9051. section->tryOpen();
  9052. return *section;
  9053. }
  9054. void SectionTracker::tryOpen() {
  9055. if( !isComplete() && (m_filters.empty() || m_filters[0].empty() || m_filters[0] == m_nameAndLocation.name ) )
  9056. open();
  9057. }
  9058. void SectionTracker::addInitialFilters( std::vector<std::string> const& filters ) {
  9059. if( !filters.empty() ) {
  9060. m_filters.push_back(""); // Root - should never be consulted
  9061. m_filters.push_back(""); // Test Case - not a section filter
  9062. m_filters.insert( m_filters.end(), filters.begin(), filters.end() );
  9063. }
  9064. }
  9065. void SectionTracker::addNextFilters( std::vector<std::string> const& filters ) {
  9066. if( filters.size() > 1 )
  9067. m_filters.insert( m_filters.end(), ++filters.begin(), filters.end() );
  9068. }
  9069. IndexTracker::IndexTracker( NameAndLocation const& nameAndLocation, TrackerContext& ctx, ITracker* parent, int size )
  9070. : TrackerBase( nameAndLocation, ctx, parent ),
  9071. m_size( size )
  9072. {}
  9073. bool IndexTracker::isIndexTracker() const { return true; }
  9074. IndexTracker& IndexTracker::acquire( TrackerContext& ctx, NameAndLocation const& nameAndLocation, int size ) {
  9075. std::shared_ptr<IndexTracker> tracker;
  9076. ITracker& currentTracker = ctx.currentTracker();
  9077. if( ITrackerPtr childTracker = currentTracker.findChild( nameAndLocation ) ) {
  9078. assert( childTracker );
  9079. assert( childTracker->isIndexTracker() );
  9080. tracker = std::static_pointer_cast<IndexTracker>( childTracker );
  9081. }
  9082. else {
  9083. tracker = std::make_shared<IndexTracker>( nameAndLocation, ctx, &currentTracker, size );
  9084. currentTracker.addChild( tracker );
  9085. }
  9086. if( !ctx.completedCycle() && !tracker->isComplete() ) {
  9087. if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun )
  9088. tracker->moveNext();
  9089. tracker->open();
  9090. }
  9091. return *tracker;
  9092. }
  9093. int IndexTracker::index() const { return m_index; }
  9094. void IndexTracker::moveNext() {
  9095. m_index++;
  9096. m_children.clear();
  9097. }
  9098. void IndexTracker::close() {
  9099. TrackerBase::close();
  9100. if( m_runState == CompletedSuccessfully && m_index < m_size-1 )
  9101. m_runState = Executing;
  9102. }
  9103. } // namespace TestCaseTracking
  9104. using TestCaseTracking::ITracker;
  9105. using TestCaseTracking::TrackerContext;
  9106. using TestCaseTracking::SectionTracker;
  9107. using TestCaseTracking::IndexTracker;
  9108. } // namespace Catch
  9109. #if defined(__clang__)
  9110. # pragma clang diagnostic pop
  9111. #endif
  9112. // end catch_test_case_tracker.cpp
  9113. // start catch_test_registry.cpp
  9114. namespace Catch {
  9115. auto makeTestInvoker( void(*testAsFunction)() ) noexcept -> ITestInvoker* {
  9116. return new(std::nothrow) TestInvokerAsFunction( testAsFunction );
  9117. }
  9118. NameAndTags::NameAndTags( StringRef const& name_ , StringRef const& tags_ ) noexcept : name( name_ ), tags( tags_ ) {}
  9119. AutoReg::AutoReg( ITestInvoker* invoker, SourceLineInfo const& lineInfo, StringRef const& classOrMethod, NameAndTags const& nameAndTags ) noexcept {
  9120. CATCH_TRY {
  9121. getMutableRegistryHub()
  9122. .registerTest(
  9123. makeTestCase(
  9124. invoker,
  9125. extractClassName( classOrMethod ),
  9126. nameAndTags,
  9127. lineInfo));
  9128. } CATCH_CATCH_ALL {
  9129. // Do not throw when constructing global objects, instead register the exception to be processed later
  9130. getMutableRegistryHub().registerStartupException();
  9131. }
  9132. }
  9133. AutoReg::~AutoReg() = default;
  9134. }
  9135. // end catch_test_registry.cpp
  9136. // start catch_test_spec.cpp
  9137. #include <algorithm>
  9138. #include <string>
  9139. #include <vector>
  9140. #include <memory>
  9141. namespace Catch {
  9142. TestSpec::Pattern::~Pattern() = default;
  9143. TestSpec::NamePattern::~NamePattern() = default;
  9144. TestSpec::TagPattern::~TagPattern() = default;
  9145. TestSpec::ExcludedPattern::~ExcludedPattern() = default;
  9146. TestSpec::NamePattern::NamePattern( std::string const& name )
  9147. : m_wildcardPattern( toLower( name ), CaseSensitive::No )
  9148. {}
  9149. bool TestSpec::NamePattern::matches( TestCaseInfo const& testCase ) const {
  9150. return m_wildcardPattern.matches( toLower( testCase.name ) );
  9151. }
  9152. TestSpec::TagPattern::TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {}
  9153. bool TestSpec::TagPattern::matches( TestCaseInfo const& testCase ) const {
  9154. return std::find(begin(testCase.lcaseTags),
  9155. end(testCase.lcaseTags),
  9156. m_tag) != end(testCase.lcaseTags);
  9157. }
  9158. TestSpec::ExcludedPattern::ExcludedPattern( PatternPtr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {}
  9159. bool TestSpec::ExcludedPattern::matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); }
  9160. bool TestSpec::Filter::matches( TestCaseInfo const& testCase ) const {
  9161. // All patterns in a filter must match for the filter to be a match
  9162. for( auto const& pattern : m_patterns ) {
  9163. if( !pattern->matches( testCase ) )
  9164. return false;
  9165. }
  9166. return true;
  9167. }
  9168. bool TestSpec::hasFilters() const {
  9169. return !m_filters.empty();
  9170. }
  9171. bool TestSpec::matches( TestCaseInfo const& testCase ) const {
  9172. // A TestSpec matches if any filter matches
  9173. for( auto const& filter : m_filters )
  9174. if( filter.matches( testCase ) )
  9175. return true;
  9176. return false;
  9177. }
  9178. }
  9179. // end catch_test_spec.cpp
  9180. // start catch_test_spec_parser.cpp
  9181. namespace Catch {
  9182. TestSpecParser::TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {}
  9183. TestSpecParser& TestSpecParser::parse( std::string const& arg ) {
  9184. m_mode = None;
  9185. m_exclusion = false;
  9186. m_start = std::string::npos;
  9187. m_arg = m_tagAliases->expandAliases( arg );
  9188. m_escapeChars.clear();
  9189. for( m_pos = 0; m_pos < m_arg.size(); ++m_pos )
  9190. visitChar( m_arg[m_pos] );
  9191. if( m_mode == Name )
  9192. addPattern<TestSpec::NamePattern>();
  9193. return *this;
  9194. }
  9195. TestSpec TestSpecParser::testSpec() {
  9196. addFilter();
  9197. return m_testSpec;
  9198. }
  9199. void TestSpecParser::visitChar( char c ) {
  9200. if( m_mode == None ) {
  9201. switch( c ) {
  9202. case ' ': return;
  9203. case '~': m_exclusion = true; return;
  9204. case '[': return startNewMode( Tag, ++m_pos );
  9205. case '"': return startNewMode( QuotedName, ++m_pos );
  9206. case '\\': return escape();
  9207. default: startNewMode( Name, m_pos ); break;
  9208. }
  9209. }
  9210. if( m_mode == Name ) {
  9211. if( c == ',' ) {
  9212. addPattern<TestSpec::NamePattern>();
  9213. addFilter();
  9214. }
  9215. else if( c == '[' ) {
  9216. if( subString() == "exclude:" )
  9217. m_exclusion = true;
  9218. else
  9219. addPattern<TestSpec::NamePattern>();
  9220. startNewMode( Tag, ++m_pos );
  9221. }
  9222. else if( c == '\\' )
  9223. escape();
  9224. }
  9225. else if( m_mode == EscapedName )
  9226. m_mode = Name;
  9227. else if( m_mode == QuotedName && c == '"' )
  9228. addPattern<TestSpec::NamePattern>();
  9229. else if( m_mode == Tag && c == ']' )
  9230. addPattern<TestSpec::TagPattern>();
  9231. }
  9232. void TestSpecParser::startNewMode( Mode mode, std::size_t start ) {
  9233. m_mode = mode;
  9234. m_start = start;
  9235. }
  9236. void TestSpecParser::escape() {
  9237. if( m_mode == None )
  9238. m_start = m_pos;
  9239. m_mode = EscapedName;
  9240. m_escapeChars.push_back( m_pos );
  9241. }
  9242. std::string TestSpecParser::subString() const { return m_arg.substr( m_start, m_pos - m_start ); }
  9243. void TestSpecParser::addFilter() {
  9244. if( !m_currentFilter.m_patterns.empty() ) {
  9245. m_testSpec.m_filters.push_back( m_currentFilter );
  9246. m_currentFilter = TestSpec::Filter();
  9247. }
  9248. }
  9249. TestSpec parseTestSpec( std::string const& arg ) {
  9250. return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec();
  9251. }
  9252. } // namespace Catch
  9253. // end catch_test_spec_parser.cpp
  9254. // start catch_timer.cpp
  9255. #include <chrono>
  9256. static const uint64_t nanosecondsInSecond = 1000000000;
  9257. namespace Catch {
  9258. auto getCurrentNanosecondsSinceEpoch() -> uint64_t {
  9259. return std::chrono::duration_cast<std::chrono::nanoseconds>( std::chrono::high_resolution_clock::now().time_since_epoch() ).count();
  9260. }
  9261. namespace {
  9262. auto estimateClockResolution() -> uint64_t {
  9263. uint64_t sum = 0;
  9264. static const uint64_t iterations = 1000000;
  9265. auto startTime = getCurrentNanosecondsSinceEpoch();
  9266. for( std::size_t i = 0; i < iterations; ++i ) {
  9267. uint64_t ticks;
  9268. uint64_t baseTicks = getCurrentNanosecondsSinceEpoch();
  9269. do {
  9270. ticks = getCurrentNanosecondsSinceEpoch();
  9271. } while( ticks == baseTicks );
  9272. auto delta = ticks - baseTicks;
  9273. sum += delta;
  9274. // If we have been calibrating for over 3 seconds -- the clock
  9275. // is terrible and we should move on.
  9276. // TBD: How to signal that the measured resolution is probably wrong?
  9277. if (ticks > startTime + 3 * nanosecondsInSecond) {
  9278. return sum / i;
  9279. }
  9280. }
  9281. // We're just taking the mean, here. To do better we could take the std. dev and exclude outliers
  9282. // - and potentially do more iterations if there's a high variance.
  9283. return sum/iterations;
  9284. }
  9285. }
  9286. auto getEstimatedClockResolution() -> uint64_t {
  9287. static auto s_resolution = estimateClockResolution();
  9288. return s_resolution;
  9289. }
  9290. void Timer::start() {
  9291. m_nanoseconds = getCurrentNanosecondsSinceEpoch();
  9292. }
  9293. auto Timer::getElapsedNanoseconds() const -> uint64_t {
  9294. return getCurrentNanosecondsSinceEpoch() - m_nanoseconds;
  9295. }
  9296. auto Timer::getElapsedMicroseconds() const -> uint64_t {
  9297. return getElapsedNanoseconds()/1000;
  9298. }
  9299. auto Timer::getElapsedMilliseconds() const -> unsigned int {
  9300. return static_cast<unsigned int>(getElapsedMicroseconds()/1000);
  9301. }
  9302. auto Timer::getElapsedSeconds() const -> double {
  9303. return getElapsedMicroseconds()/1000000.0;
  9304. }
  9305. } // namespace Catch
  9306. // end catch_timer.cpp
  9307. // start catch_tostring.cpp
  9308. #if defined(__clang__)
  9309. # pragma clang diagnostic push
  9310. # pragma clang diagnostic ignored "-Wexit-time-destructors"
  9311. # pragma clang diagnostic ignored "-Wglobal-constructors"
  9312. #endif
  9313. // Enable specific decls locally
  9314. #if !defined(CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER)
  9315. #define CATCH_CONFIG_ENABLE_CHRONO_STRINGMAKER
  9316. #endif
  9317. #include <cmath>
  9318. #include <iomanip>
  9319. namespace Catch {
  9320. namespace Detail {
  9321. const std::string unprintableString = "{?}";
  9322. namespace {
  9323. const int hexThreshold = 255;
  9324. struct Endianness {
  9325. enum Arch { Big, Little };
  9326. static Arch which() {
  9327. union _{
  9328. int asInt;
  9329. char asChar[sizeof (int)];
  9330. } u;
  9331. u.asInt = 1;
  9332. return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little;
  9333. }
  9334. };
  9335. }
  9336. std::string rawMemoryToString( const void *object, std::size_t size ) {
  9337. // Reverse order for little endian architectures
  9338. int i = 0, end = static_cast<int>( size ), inc = 1;
  9339. if( Endianness::which() == Endianness::Little ) {
  9340. i = end-1;
  9341. end = inc = -1;
  9342. }
  9343. unsigned char const *bytes = static_cast<unsigned char const *>(object);
  9344. ReusableStringStream rss;
  9345. rss << "0x" << std::setfill('0') << std::hex;
  9346. for( ; i != end; i += inc )
  9347. rss << std::setw(2) << static_cast<unsigned>(bytes[i]);
  9348. return rss.str();
  9349. }
  9350. }
  9351. template<typename T>
  9352. std::string fpToString( T value, int precision ) {
  9353. if (std::isnan(value)) {
  9354. return "nan";
  9355. }
  9356. ReusableStringStream rss;
  9357. rss << std::setprecision( precision )
  9358. << std::fixed
  9359. << value;
  9360. std::string d = rss.str();
  9361. std::size_t i = d.find_last_not_of( '0' );
  9362. if( i != std::string::npos && i != d.size()-1 ) {
  9363. if( d[i] == '.' )
  9364. i++;
  9365. d = d.substr( 0, i+1 );
  9366. }
  9367. return d;
  9368. }
  9369. //// ======================================================= ////
  9370. //
  9371. // Out-of-line defs for full specialization of StringMaker
  9372. //
  9373. //// ======================================================= ////
  9374. std::string StringMaker<std::string>::convert(const std::string& str) {
  9375. if (!getCurrentContext().getConfig()->showInvisibles()) {
  9376. return '"' + str + '"';
  9377. }
  9378. std::string s("\"");
  9379. for (char c : str) {
  9380. switch (c) {
  9381. case '\n':
  9382. s.append("\\n");
  9383. break;
  9384. case '\t':
  9385. s.append("\\t");
  9386. break;
  9387. default:
  9388. s.push_back(c);
  9389. break;
  9390. }
  9391. }
  9392. s.append("\"");
  9393. return s;
  9394. }
  9395. #ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  9396. std::string StringMaker<std::string_view>::convert(std::string_view str) {
  9397. return ::Catch::Detail::stringify(std::string{ str });
  9398. }
  9399. #endif
  9400. std::string StringMaker<char const*>::convert(char const* str) {
  9401. if (str) {
  9402. return ::Catch::Detail::stringify(std::string{ str });
  9403. } else {
  9404. return{ "{null string}" };
  9405. }
  9406. }
  9407. std::string StringMaker<char*>::convert(char* str) {
  9408. if (str) {
  9409. return ::Catch::Detail::stringify(std::string{ str });
  9410. } else {
  9411. return{ "{null string}" };
  9412. }
  9413. }
  9414. #ifdef CATCH_CONFIG_WCHAR
  9415. std::string StringMaker<std::wstring>::convert(const std::wstring& wstr) {
  9416. std::string s;
  9417. s.reserve(wstr.size());
  9418. for (auto c : wstr) {
  9419. s += (c <= 0xff) ? static_cast<char>(c) : '?';
  9420. }
  9421. return ::Catch::Detail::stringify(s);
  9422. }
  9423. # ifdef CATCH_CONFIG_CPP17_STRING_VIEW
  9424. std::string StringMaker<std::wstring_view>::convert(std::wstring_view str) {
  9425. return StringMaker<std::wstring>::convert(std::wstring(str));
  9426. }
  9427. # endif
  9428. std::string StringMaker<wchar_t const*>::convert(wchar_t const * str) {
  9429. if (str) {
  9430. return ::Catch::Detail::stringify(std::wstring{ str });
  9431. } else {
  9432. return{ "{null string}" };
  9433. }
  9434. }
  9435. std::string StringMaker<wchar_t *>::convert(wchar_t * str) {
  9436. if (str) {
  9437. return ::Catch::Detail::stringify(std::wstring{ str });
  9438. } else {
  9439. return{ "{null string}" };
  9440. }
  9441. }
  9442. #endif
  9443. std::string StringMaker<int>::convert(int value) {
  9444. return ::Catch::Detail::stringify(static_cast<long long>(value));
  9445. }
  9446. std::string StringMaker<long>::convert(long value) {
  9447. return ::Catch::Detail::stringify(static_cast<long long>(value));
  9448. }
  9449. std::string StringMaker<long long>::convert(long long value) {
  9450. ReusableStringStream rss;
  9451. rss << value;
  9452. if (value > Detail::hexThreshold) {
  9453. rss << " (0x" << std::hex << value << ')';
  9454. }
  9455. return rss.str();
  9456. }
  9457. std::string StringMaker<unsigned int>::convert(unsigned int value) {
  9458. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  9459. }
  9460. std::string StringMaker<unsigned long>::convert(unsigned long value) {
  9461. return ::Catch::Detail::stringify(static_cast<unsigned long long>(value));
  9462. }
  9463. std::string StringMaker<unsigned long long>::convert(unsigned long long value) {
  9464. ReusableStringStream rss;
  9465. rss << value;
  9466. if (value > Detail::hexThreshold) {
  9467. rss << " (0x" << std::hex << value << ')';
  9468. }
  9469. return rss.str();
  9470. }
  9471. std::string StringMaker<bool>::convert(bool b) {
  9472. return b ? "true" : "false";
  9473. }
  9474. std::string StringMaker<signed char>::convert(signed char value) {
  9475. if (value == '\r') {
  9476. return "'\\r'";
  9477. } else if (value == '\f') {
  9478. return "'\\f'";
  9479. } else if (value == '\n') {
  9480. return "'\\n'";
  9481. } else if (value == '\t') {
  9482. return "'\\t'";
  9483. } else if ('\0' <= value && value < ' ') {
  9484. return ::Catch::Detail::stringify(static_cast<unsigned int>(value));
  9485. } else {
  9486. char chstr[] = "' '";
  9487. chstr[1] = value;
  9488. return chstr;
  9489. }
  9490. }
  9491. std::string StringMaker<char>::convert(char c) {
  9492. return ::Catch::Detail::stringify(static_cast<signed char>(c));
  9493. }
  9494. std::string StringMaker<unsigned char>::convert(unsigned char c) {
  9495. return ::Catch::Detail::stringify(static_cast<char>(c));
  9496. }
  9497. std::string StringMaker<std::nullptr_t>::convert(std::nullptr_t) {
  9498. return "nullptr";
  9499. }
  9500. std::string StringMaker<float>::convert(float value) {
  9501. return fpToString(value, 5) + 'f';
  9502. }
  9503. std::string StringMaker<double>::convert(double value) {
  9504. return fpToString(value, 10);
  9505. }
  9506. std::string ratio_string<std::atto>::symbol() { return "a"; }
  9507. std::string ratio_string<std::femto>::symbol() { return "f"; }
  9508. std::string ratio_string<std::pico>::symbol() { return "p"; }
  9509. std::string ratio_string<std::nano>::symbol() { return "n"; }
  9510. std::string ratio_string<std::micro>::symbol() { return "u"; }
  9511. std::string ratio_string<std::milli>::symbol() { return "m"; }
  9512. } // end namespace Catch
  9513. #if defined(__clang__)
  9514. # pragma clang diagnostic pop
  9515. #endif
  9516. // end catch_tostring.cpp
  9517. // start catch_totals.cpp
  9518. namespace Catch {
  9519. Counts Counts::operator - ( Counts const& other ) const {
  9520. Counts diff;
  9521. diff.passed = passed - other.passed;
  9522. diff.failed = failed - other.failed;
  9523. diff.failedButOk = failedButOk - other.failedButOk;
  9524. return diff;
  9525. }
  9526. Counts& Counts::operator += ( Counts const& other ) {
  9527. passed += other.passed;
  9528. failed += other.failed;
  9529. failedButOk += other.failedButOk;
  9530. return *this;
  9531. }
  9532. std::size_t Counts::total() const {
  9533. return passed + failed + failedButOk;
  9534. }
  9535. bool Counts::allPassed() const {
  9536. return failed == 0 && failedButOk == 0;
  9537. }
  9538. bool Counts::allOk() const {
  9539. return failed == 0;
  9540. }
  9541. Totals Totals::operator - ( Totals const& other ) const {
  9542. Totals diff;
  9543. diff.assertions = assertions - other.assertions;
  9544. diff.testCases = testCases - other.testCases;
  9545. return diff;
  9546. }
  9547. Totals& Totals::operator += ( Totals const& other ) {
  9548. assertions += other.assertions;
  9549. testCases += other.testCases;
  9550. return *this;
  9551. }
  9552. Totals Totals::delta( Totals const& prevTotals ) const {
  9553. Totals diff = *this - prevTotals;
  9554. if( diff.assertions.failed > 0 )
  9555. ++diff.testCases.failed;
  9556. else if( diff.assertions.failedButOk > 0 )
  9557. ++diff.testCases.failedButOk;
  9558. else
  9559. ++diff.testCases.passed;
  9560. return diff;
  9561. }
  9562. }
  9563. // end catch_totals.cpp
  9564. // start catch_uncaught_exceptions.cpp
  9565. #include <exception>
  9566. namespace Catch {
  9567. bool uncaught_exceptions() {
  9568. #if defined(CATCH_CONFIG_CPP17_UNCAUGHT_EXCEPTIONS)
  9569. return std::uncaught_exceptions() > 0;
  9570. #else
  9571. return std::uncaught_exception();
  9572. #endif
  9573. }
  9574. } // end namespace Catch
  9575. // end catch_uncaught_exceptions.cpp
  9576. // start catch_version.cpp
  9577. #include <ostream>
  9578. namespace Catch {
  9579. Version::Version
  9580. ( unsigned int _majorVersion,
  9581. unsigned int _minorVersion,
  9582. unsigned int _patchNumber,
  9583. char const * const _branchName,
  9584. unsigned int _buildNumber )
  9585. : majorVersion( _majorVersion ),
  9586. minorVersion( _minorVersion ),
  9587. patchNumber( _patchNumber ),
  9588. branchName( _branchName ),
  9589. buildNumber( _buildNumber )
  9590. {}
  9591. std::ostream& operator << ( std::ostream& os, Version const& version ) {
  9592. os << version.majorVersion << '.'
  9593. << version.minorVersion << '.'
  9594. << version.patchNumber;
  9595. // branchName is never null -> 0th char is \0 if it is empty
  9596. if (version.branchName[0]) {
  9597. os << '-' << version.branchName
  9598. << '.' << version.buildNumber;
  9599. }
  9600. return os;
  9601. }
  9602. Version const& libraryVersion() {
  9603. static Version version( 2, 4, 2, "", 0 );
  9604. return version;
  9605. }
  9606. }
  9607. // end catch_version.cpp
  9608. // start catch_wildcard_pattern.cpp
  9609. #include <sstream>
  9610. namespace Catch {
  9611. WildcardPattern::WildcardPattern( std::string const& pattern,
  9612. CaseSensitive::Choice caseSensitivity )
  9613. : m_caseSensitivity( caseSensitivity ),
  9614. m_pattern( adjustCase( pattern ) )
  9615. {
  9616. if( startsWith( m_pattern, '*' ) ) {
  9617. m_pattern = m_pattern.substr( 1 );
  9618. m_wildcard = WildcardAtStart;
  9619. }
  9620. if( endsWith( m_pattern, '*' ) ) {
  9621. m_pattern = m_pattern.substr( 0, m_pattern.size()-1 );
  9622. m_wildcard = static_cast<WildcardPosition>( m_wildcard | WildcardAtEnd );
  9623. }
  9624. }
  9625. bool WildcardPattern::matches( std::string const& str ) const {
  9626. switch( m_wildcard ) {
  9627. case NoWildcard:
  9628. return m_pattern == adjustCase( str );
  9629. case WildcardAtStart:
  9630. return endsWith( adjustCase( str ), m_pattern );
  9631. case WildcardAtEnd:
  9632. return startsWith( adjustCase( str ), m_pattern );
  9633. case WildcardAtBothEnds:
  9634. return contains( adjustCase( str ), m_pattern );
  9635. default:
  9636. CATCH_INTERNAL_ERROR( "Unknown enum" );
  9637. }
  9638. }
  9639. std::string WildcardPattern::adjustCase( std::string const& str ) const {
  9640. return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str;
  9641. }
  9642. }
  9643. // end catch_wildcard_pattern.cpp
  9644. // start catch_xmlwriter.cpp
  9645. #include <iomanip>
  9646. using uchar = unsigned char;
  9647. namespace Catch {
  9648. namespace {
  9649. size_t trailingBytes(unsigned char c) {
  9650. if ((c & 0xE0) == 0xC0) {
  9651. return 2;
  9652. }
  9653. if ((c & 0xF0) == 0xE0) {
  9654. return 3;
  9655. }
  9656. if ((c & 0xF8) == 0xF0) {
  9657. return 4;
  9658. }
  9659. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  9660. }
  9661. uint32_t headerValue(unsigned char c) {
  9662. if ((c & 0xE0) == 0xC0) {
  9663. return c & 0x1F;
  9664. }
  9665. if ((c & 0xF0) == 0xE0) {
  9666. return c & 0x0F;
  9667. }
  9668. if ((c & 0xF8) == 0xF0) {
  9669. return c & 0x07;
  9670. }
  9671. CATCH_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered");
  9672. }
  9673. void hexEscapeChar(std::ostream& os, unsigned char c) {
  9674. os << "\\x"
  9675. << std::uppercase << std::hex << std::setfill('0') << std::setw(2)
  9676. << static_cast<int>(c);
  9677. }
  9678. } // anonymous namespace
  9679. XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat )
  9680. : m_str( str ),
  9681. m_forWhat( forWhat )
  9682. {}
  9683. void XmlEncode::encodeTo( std::ostream& os ) const {
  9684. // Apostrophe escaping not necessary if we always use " to write attributes
  9685. // (see: http://www.w3.org/TR/xml/#syntax)
  9686. for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) {
  9687. uchar c = m_str[idx];
  9688. switch (c) {
  9689. case '<': os << "&lt;"; break;
  9690. case '&': os << "&amp;"; break;
  9691. case '>':
  9692. // See: http://www.w3.org/TR/xml/#syntax
  9693. if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']')
  9694. os << "&gt;";
  9695. else
  9696. os << c;
  9697. break;
  9698. case '\"':
  9699. if (m_forWhat == ForAttributes)
  9700. os << "&quot;";
  9701. else
  9702. os << c;
  9703. break;
  9704. default:
  9705. // Check for control characters and invalid utf-8
  9706. // Escape control characters in standard ascii
  9707. // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0
  9708. if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) {
  9709. hexEscapeChar(os, c);
  9710. break;
  9711. }
  9712. // Plain ASCII: Write it to stream
  9713. if (c < 0x7F) {
  9714. os << c;
  9715. break;
  9716. }
  9717. // UTF-8 territory
  9718. // Check if the encoding is valid and if it is not, hex escape bytes.
  9719. // Important: We do not check the exact decoded values for validity, only the encoding format
  9720. // First check that this bytes is a valid lead byte:
  9721. // This means that it is not encoded as 1111 1XXX
  9722. // Or as 10XX XXXX
  9723. if (c < 0xC0 ||
  9724. c >= 0xF8) {
  9725. hexEscapeChar(os, c);
  9726. break;
  9727. }
  9728. auto encBytes = trailingBytes(c);
  9729. // Are there enough bytes left to avoid accessing out-of-bounds memory?
  9730. if (idx + encBytes - 1 >= m_str.size()) {
  9731. hexEscapeChar(os, c);
  9732. break;
  9733. }
  9734. // The header is valid, check data
  9735. // The next encBytes bytes must together be a valid utf-8
  9736. // This means: bitpattern 10XX XXXX and the extracted value is sane (ish)
  9737. bool valid = true;
  9738. uint32_t value = headerValue(c);
  9739. for (std::size_t n = 1; n < encBytes; ++n) {
  9740. uchar nc = m_str[idx + n];
  9741. valid &= ((nc & 0xC0) == 0x80);
  9742. value = (value << 6) | (nc & 0x3F);
  9743. }
  9744. if (
  9745. // Wrong bit pattern of following bytes
  9746. (!valid) ||
  9747. // Overlong encodings
  9748. (value < 0x80) ||
  9749. (0x80 <= value && value < 0x800 && encBytes > 2) ||
  9750. (0x800 < value && value < 0x10000 && encBytes > 3) ||
  9751. // Encoded value out of range
  9752. (value >= 0x110000)
  9753. ) {
  9754. hexEscapeChar(os, c);
  9755. break;
  9756. }
  9757. // If we got here, this is in fact a valid(ish) utf-8 sequence
  9758. for (std::size_t n = 0; n < encBytes; ++n) {
  9759. os << m_str[idx + n];
  9760. }
  9761. idx += encBytes - 1;
  9762. break;
  9763. }
  9764. }
  9765. }
  9766. std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) {
  9767. xmlEncode.encodeTo( os );
  9768. return os;
  9769. }
  9770. XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer )
  9771. : m_writer( writer )
  9772. {}
  9773. XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept
  9774. : m_writer( other.m_writer ){
  9775. other.m_writer = nullptr;
  9776. }
  9777. XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept {
  9778. if ( m_writer ) {
  9779. m_writer->endElement();
  9780. }
  9781. m_writer = other.m_writer;
  9782. other.m_writer = nullptr;
  9783. return *this;
  9784. }
  9785. XmlWriter::ScopedElement::~ScopedElement() {
  9786. if( m_writer )
  9787. m_writer->endElement();
  9788. }
  9789. XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) {
  9790. m_writer->writeText( text, indent );
  9791. return *this;
  9792. }
  9793. XmlWriter::XmlWriter( std::ostream& os ) : m_os( os )
  9794. {
  9795. writeDeclaration();
  9796. }
  9797. XmlWriter::~XmlWriter() {
  9798. while( !m_tags.empty() )
  9799. endElement();
  9800. }
  9801. XmlWriter& XmlWriter::startElement( std::string const& name ) {
  9802. ensureTagClosed();
  9803. newlineIfNecessary();
  9804. m_os << m_indent << '<' << name;
  9805. m_tags.push_back( name );
  9806. m_indent += " ";
  9807. m_tagIsOpen = true;
  9808. return *this;
  9809. }
  9810. XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) {
  9811. ScopedElement scoped( this );
  9812. startElement( name );
  9813. return scoped;
  9814. }
  9815. XmlWriter& XmlWriter::endElement() {
  9816. newlineIfNecessary();
  9817. m_indent = m_indent.substr( 0, m_indent.size()-2 );
  9818. if( m_tagIsOpen ) {
  9819. m_os << "/>";
  9820. m_tagIsOpen = false;
  9821. }
  9822. else {
  9823. m_os << m_indent << "</" << m_tags.back() << ">";
  9824. }
  9825. m_os << std::endl;
  9826. m_tags.pop_back();
  9827. return *this;
  9828. }
  9829. XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) {
  9830. if( !name.empty() && !attribute.empty() )
  9831. m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"';
  9832. return *this;
  9833. }
  9834. XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) {
  9835. m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"';
  9836. return *this;
  9837. }
  9838. XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) {
  9839. if( !text.empty() ){
  9840. bool tagWasOpen = m_tagIsOpen;
  9841. ensureTagClosed();
  9842. if( tagWasOpen && indent )
  9843. m_os << m_indent;
  9844. m_os << XmlEncode( text );
  9845. m_needsNewline = true;
  9846. }
  9847. return *this;
  9848. }
  9849. XmlWriter& XmlWriter::writeComment( std::string const& text ) {
  9850. ensureTagClosed();
  9851. m_os << m_indent << "<!--" << text << "-->";
  9852. m_needsNewline = true;
  9853. return *this;
  9854. }
  9855. void XmlWriter::writeStylesheetRef( std::string const& url ) {
  9856. m_os << "<?xml-stylesheet type=\"text/xsl\" href=\"" << url << "\"?>\n";
  9857. }
  9858. XmlWriter& XmlWriter::writeBlankLine() {
  9859. ensureTagClosed();
  9860. m_os << '\n';
  9861. return *this;
  9862. }
  9863. void XmlWriter::ensureTagClosed() {
  9864. if( m_tagIsOpen ) {
  9865. m_os << ">" << std::endl;
  9866. m_tagIsOpen = false;
  9867. }
  9868. }
  9869. void XmlWriter::writeDeclaration() {
  9870. m_os << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
  9871. }
  9872. void XmlWriter::newlineIfNecessary() {
  9873. if( m_needsNewline ) {
  9874. m_os << std::endl;
  9875. m_needsNewline = false;
  9876. }
  9877. }
  9878. }
  9879. // end catch_xmlwriter.cpp
  9880. // start catch_reporter_bases.cpp
  9881. #include <cstring>
  9882. #include <cfloat>
  9883. #include <cstdio>
  9884. #include <cassert>
  9885. #include <memory>
  9886. namespace Catch {
  9887. void prepareExpandedExpression(AssertionResult& result) {
  9888. result.getExpandedExpression();
  9889. }
  9890. // Because formatting using c++ streams is stateful, drop down to C is required
  9891. // Alternatively we could use stringstream, but its performance is... not good.
  9892. std::string getFormattedDuration( double duration ) {
  9893. // Max exponent + 1 is required to represent the whole part
  9894. // + 1 for decimal point
  9895. // + 3 for the 3 decimal places
  9896. // + 1 for null terminator
  9897. const std::size_t maxDoubleSize = DBL_MAX_10_EXP + 1 + 1 + 3 + 1;
  9898. char buffer[maxDoubleSize];
  9899. // Save previous errno, to prevent sprintf from overwriting it
  9900. ErrnoGuard guard;
  9901. #ifdef _MSC_VER
  9902. sprintf_s(buffer, "%.3f", duration);
  9903. #else
  9904. sprintf(buffer, "%.3f", duration);
  9905. #endif
  9906. return std::string(buffer);
  9907. }
  9908. TestEventListenerBase::TestEventListenerBase(ReporterConfig const & _config)
  9909. :StreamingReporterBase(_config) {}
  9910. void TestEventListenerBase::assertionStarting(AssertionInfo const &) {}
  9911. bool TestEventListenerBase::assertionEnded(AssertionStats const &) {
  9912. return false;
  9913. }
  9914. } // end namespace Catch
  9915. // end catch_reporter_bases.cpp
  9916. // start catch_reporter_compact.cpp
  9917. namespace {
  9918. #ifdef CATCH_PLATFORM_MAC
  9919. const char* failedString() { return "FAILED"; }
  9920. const char* passedString() { return "PASSED"; }
  9921. #else
  9922. const char* failedString() { return "failed"; }
  9923. const char* passedString() { return "passed"; }
  9924. #endif
  9925. // Colour::LightGrey
  9926. Catch::Colour::Code dimColour() { return Catch::Colour::FileName; }
  9927. std::string bothOrAll( std::size_t count ) {
  9928. return count == 1 ? std::string() :
  9929. count == 2 ? "both " : "all " ;
  9930. }
  9931. } // anon namespace
  9932. namespace Catch {
  9933. namespace {
  9934. // Colour, message variants:
  9935. // - white: No tests ran.
  9936. // - red: Failed [both/all] N test cases, failed [both/all] M assertions.
  9937. // - white: Passed [both/all] N test cases (no assertions).
  9938. // - red: Failed N tests cases, failed M assertions.
  9939. // - green: Passed [both/all] N tests cases with M assertions.
  9940. void printTotals(std::ostream& out, const Totals& totals) {
  9941. if (totals.testCases.total() == 0) {
  9942. out << "No tests ran.";
  9943. } else if (totals.testCases.failed == totals.testCases.total()) {
  9944. Colour colour(Colour::ResultError);
  9945. const std::string qualify_assertions_failed =
  9946. totals.assertions.failed == totals.assertions.total() ?
  9947. bothOrAll(totals.assertions.failed) : std::string();
  9948. out <<
  9949. "Failed " << bothOrAll(totals.testCases.failed)
  9950. << pluralise(totals.testCases.failed, "test case") << ", "
  9951. "failed " << qualify_assertions_failed <<
  9952. pluralise(totals.assertions.failed, "assertion") << '.';
  9953. } else if (totals.assertions.total() == 0) {
  9954. out <<
  9955. "Passed " << bothOrAll(totals.testCases.total())
  9956. << pluralise(totals.testCases.total(), "test case")
  9957. << " (no assertions).";
  9958. } else if (totals.assertions.failed) {
  9959. Colour colour(Colour::ResultError);
  9960. out <<
  9961. "Failed " << pluralise(totals.testCases.failed, "test case") << ", "
  9962. "failed " << pluralise(totals.assertions.failed, "assertion") << '.';
  9963. } else {
  9964. Colour colour(Colour::ResultSuccess);
  9965. out <<
  9966. "Passed " << bothOrAll(totals.testCases.passed)
  9967. << pluralise(totals.testCases.passed, "test case") <<
  9968. " with " << pluralise(totals.assertions.passed, "assertion") << '.';
  9969. }
  9970. }
  9971. // Implementation of CompactReporter formatting
  9972. class AssertionPrinter {
  9973. public:
  9974. AssertionPrinter& operator= (AssertionPrinter const&) = delete;
  9975. AssertionPrinter(AssertionPrinter const&) = delete;
  9976. AssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  9977. : stream(_stream)
  9978. , result(_stats.assertionResult)
  9979. , messages(_stats.infoMessages)
  9980. , itMessage(_stats.infoMessages.begin())
  9981. , printInfoMessages(_printInfoMessages) {}
  9982. void print() {
  9983. printSourceInfo();
  9984. itMessage = messages.begin();
  9985. switch (result.getResultType()) {
  9986. case ResultWas::Ok:
  9987. printResultType(Colour::ResultSuccess, passedString());
  9988. printOriginalExpression();
  9989. printReconstructedExpression();
  9990. if (!result.hasExpression())
  9991. printRemainingMessages(Colour::None);
  9992. else
  9993. printRemainingMessages();
  9994. break;
  9995. case ResultWas::ExpressionFailed:
  9996. if (result.isOk())
  9997. printResultType(Colour::ResultSuccess, failedString() + std::string(" - but was ok"));
  9998. else
  9999. printResultType(Colour::Error, failedString());
  10000. printOriginalExpression();
  10001. printReconstructedExpression();
  10002. printRemainingMessages();
  10003. break;
  10004. case ResultWas::ThrewException:
  10005. printResultType(Colour::Error, failedString());
  10006. printIssue("unexpected exception with message:");
  10007. printMessage();
  10008. printExpressionWas();
  10009. printRemainingMessages();
  10010. break;
  10011. case ResultWas::FatalErrorCondition:
  10012. printResultType(Colour::Error, failedString());
  10013. printIssue("fatal error condition with message:");
  10014. printMessage();
  10015. printExpressionWas();
  10016. printRemainingMessages();
  10017. break;
  10018. case ResultWas::DidntThrowException:
  10019. printResultType(Colour::Error, failedString());
  10020. printIssue("expected exception, got none");
  10021. printExpressionWas();
  10022. printRemainingMessages();
  10023. break;
  10024. case ResultWas::Info:
  10025. printResultType(Colour::None, "info");
  10026. printMessage();
  10027. printRemainingMessages();
  10028. break;
  10029. case ResultWas::Warning:
  10030. printResultType(Colour::None, "warning");
  10031. printMessage();
  10032. printRemainingMessages();
  10033. break;
  10034. case ResultWas::ExplicitFailure:
  10035. printResultType(Colour::Error, failedString());
  10036. printIssue("explicitly");
  10037. printRemainingMessages(Colour::None);
  10038. break;
  10039. // These cases are here to prevent compiler warnings
  10040. case ResultWas::Unknown:
  10041. case ResultWas::FailureBit:
  10042. case ResultWas::Exception:
  10043. printResultType(Colour::Error, "** internal error **");
  10044. break;
  10045. }
  10046. }
  10047. private:
  10048. void printSourceInfo() const {
  10049. Colour colourGuard(Colour::FileName);
  10050. stream << result.getSourceInfo() << ':';
  10051. }
  10052. void printResultType(Colour::Code colour, std::string const& passOrFail) const {
  10053. if (!passOrFail.empty()) {
  10054. {
  10055. Colour colourGuard(colour);
  10056. stream << ' ' << passOrFail;
  10057. }
  10058. stream << ':';
  10059. }
  10060. }
  10061. void printIssue(std::string const& issue) const {
  10062. stream << ' ' << issue;
  10063. }
  10064. void printExpressionWas() {
  10065. if (result.hasExpression()) {
  10066. stream << ';';
  10067. {
  10068. Colour colour(dimColour());
  10069. stream << " expression was:";
  10070. }
  10071. printOriginalExpression();
  10072. }
  10073. }
  10074. void printOriginalExpression() const {
  10075. if (result.hasExpression()) {
  10076. stream << ' ' << result.getExpression();
  10077. }
  10078. }
  10079. void printReconstructedExpression() const {
  10080. if (result.hasExpandedExpression()) {
  10081. {
  10082. Colour colour(dimColour());
  10083. stream << " for: ";
  10084. }
  10085. stream << result.getExpandedExpression();
  10086. }
  10087. }
  10088. void printMessage() {
  10089. if (itMessage != messages.end()) {
  10090. stream << " '" << itMessage->message << '\'';
  10091. ++itMessage;
  10092. }
  10093. }
  10094. void printRemainingMessages(Colour::Code colour = dimColour()) {
  10095. if (itMessage == messages.end())
  10096. return;
  10097. // using messages.end() directly yields (or auto) compilation error:
  10098. std::vector<MessageInfo>::const_iterator itEnd = messages.end();
  10099. const std::size_t N = static_cast<std::size_t>(std::distance(itMessage, itEnd));
  10100. {
  10101. Colour colourGuard(colour);
  10102. stream << " with " << pluralise(N, "message") << ':';
  10103. }
  10104. for (; itMessage != itEnd; ) {
  10105. // If this assertion is a warning ignore any INFO messages
  10106. if (printInfoMessages || itMessage->type != ResultWas::Info) {
  10107. stream << " '" << itMessage->message << '\'';
  10108. if (++itMessage != itEnd) {
  10109. Colour colourGuard(dimColour());
  10110. stream << " and";
  10111. }
  10112. }
  10113. }
  10114. }
  10115. private:
  10116. std::ostream& stream;
  10117. AssertionResult const& result;
  10118. std::vector<MessageInfo> messages;
  10119. std::vector<MessageInfo>::const_iterator itMessage;
  10120. bool printInfoMessages;
  10121. };
  10122. } // anon namespace
  10123. std::string CompactReporter::getDescription() {
  10124. return "Reports test results on a single line, suitable for IDEs";
  10125. }
  10126. ReporterPreferences CompactReporter::getPreferences() const {
  10127. return m_reporterPrefs;
  10128. }
  10129. void CompactReporter::noMatchingTestCases( std::string const& spec ) {
  10130. stream << "No test cases matched '" << spec << '\'' << std::endl;
  10131. }
  10132. void CompactReporter::assertionStarting( AssertionInfo const& ) {}
  10133. bool CompactReporter::assertionEnded( AssertionStats const& _assertionStats ) {
  10134. AssertionResult const& result = _assertionStats.assertionResult;
  10135. bool printInfoMessages = true;
  10136. // Drop out if result was successful and we're not printing those
  10137. if( !m_config->includeSuccessfulResults() && result.isOk() ) {
  10138. if( result.getResultType() != ResultWas::Warning )
  10139. return false;
  10140. printInfoMessages = false;
  10141. }
  10142. AssertionPrinter printer( stream, _assertionStats, printInfoMessages );
  10143. printer.print();
  10144. stream << std::endl;
  10145. return true;
  10146. }
  10147. void CompactReporter::sectionEnded(SectionStats const& _sectionStats) {
  10148. if (m_config->showDurations() == ShowDurations::Always) {
  10149. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  10150. }
  10151. }
  10152. void CompactReporter::testRunEnded( TestRunStats const& _testRunStats ) {
  10153. printTotals( stream, _testRunStats.totals );
  10154. stream << '\n' << std::endl;
  10155. StreamingReporterBase::testRunEnded( _testRunStats );
  10156. }
  10157. CompactReporter::~CompactReporter() {}
  10158. CATCH_REGISTER_REPORTER( "compact", CompactReporter )
  10159. } // end namespace Catch
  10160. // end catch_reporter_compact.cpp
  10161. // start catch_reporter_console.cpp
  10162. #include <cfloat>
  10163. #include <cstdio>
  10164. #if defined(_MSC_VER)
  10165. #pragma warning(push)
  10166. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  10167. // Note that 4062 (not all labels are handled
  10168. // and default is missing) is enabled
  10169. #endif
  10170. namespace Catch {
  10171. namespace {
  10172. // Formatter impl for ConsoleReporter
  10173. class ConsoleAssertionPrinter {
  10174. public:
  10175. ConsoleAssertionPrinter& operator= (ConsoleAssertionPrinter const&) = delete;
  10176. ConsoleAssertionPrinter(ConsoleAssertionPrinter const&) = delete;
  10177. ConsoleAssertionPrinter(std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages)
  10178. : stream(_stream),
  10179. stats(_stats),
  10180. result(_stats.assertionResult),
  10181. colour(Colour::None),
  10182. message(result.getMessage()),
  10183. messages(_stats.infoMessages),
  10184. printInfoMessages(_printInfoMessages) {
  10185. switch (result.getResultType()) {
  10186. case ResultWas::Ok:
  10187. colour = Colour::Success;
  10188. passOrFail = "PASSED";
  10189. //if( result.hasMessage() )
  10190. if (_stats.infoMessages.size() == 1)
  10191. messageLabel = "with message";
  10192. if (_stats.infoMessages.size() > 1)
  10193. messageLabel = "with messages";
  10194. break;
  10195. case ResultWas::ExpressionFailed:
  10196. if (result.isOk()) {
  10197. colour = Colour::Success;
  10198. passOrFail = "FAILED - but was ok";
  10199. } else {
  10200. colour = Colour::Error;
  10201. passOrFail = "FAILED";
  10202. }
  10203. if (_stats.infoMessages.size() == 1)
  10204. messageLabel = "with message";
  10205. if (_stats.infoMessages.size() > 1)
  10206. messageLabel = "with messages";
  10207. break;
  10208. case ResultWas::ThrewException:
  10209. colour = Colour::Error;
  10210. passOrFail = "FAILED";
  10211. messageLabel = "due to unexpected exception with ";
  10212. if (_stats.infoMessages.size() == 1)
  10213. messageLabel += "message";
  10214. if (_stats.infoMessages.size() > 1)
  10215. messageLabel += "messages";
  10216. break;
  10217. case ResultWas::FatalErrorCondition:
  10218. colour = Colour::Error;
  10219. passOrFail = "FAILED";
  10220. messageLabel = "due to a fatal error condition";
  10221. break;
  10222. case ResultWas::DidntThrowException:
  10223. colour = Colour::Error;
  10224. passOrFail = "FAILED";
  10225. messageLabel = "because no exception was thrown where one was expected";
  10226. break;
  10227. case ResultWas::Info:
  10228. messageLabel = "info";
  10229. break;
  10230. case ResultWas::Warning:
  10231. messageLabel = "warning";
  10232. break;
  10233. case ResultWas::ExplicitFailure:
  10234. passOrFail = "FAILED";
  10235. colour = Colour::Error;
  10236. if (_stats.infoMessages.size() == 1)
  10237. messageLabel = "explicitly with message";
  10238. if (_stats.infoMessages.size() > 1)
  10239. messageLabel = "explicitly with messages";
  10240. break;
  10241. // These cases are here to prevent compiler warnings
  10242. case ResultWas::Unknown:
  10243. case ResultWas::FailureBit:
  10244. case ResultWas::Exception:
  10245. passOrFail = "** internal error **";
  10246. colour = Colour::Error;
  10247. break;
  10248. }
  10249. }
  10250. void print() const {
  10251. printSourceInfo();
  10252. if (stats.totals.assertions.total() > 0) {
  10253. if (result.isOk())
  10254. stream << '\n';
  10255. printResultType();
  10256. printOriginalExpression();
  10257. printReconstructedExpression();
  10258. } else {
  10259. stream << '\n';
  10260. }
  10261. printMessage();
  10262. }
  10263. private:
  10264. void printResultType() const {
  10265. if (!passOrFail.empty()) {
  10266. Colour colourGuard(colour);
  10267. stream << passOrFail << ":\n";
  10268. }
  10269. }
  10270. void printOriginalExpression() const {
  10271. if (result.hasExpression()) {
  10272. Colour colourGuard(Colour::OriginalExpression);
  10273. stream << " ";
  10274. stream << result.getExpressionInMacro();
  10275. stream << '\n';
  10276. }
  10277. }
  10278. void printReconstructedExpression() const {
  10279. if (result.hasExpandedExpression()) {
  10280. stream << "with expansion:\n";
  10281. Colour colourGuard(Colour::ReconstructedExpression);
  10282. stream << Column(result.getExpandedExpression()).indent(2) << '\n';
  10283. }
  10284. }
  10285. void printMessage() const {
  10286. if (!messageLabel.empty())
  10287. stream << messageLabel << ':' << '\n';
  10288. for (auto const& msg : messages) {
  10289. // If this assertion is a warning ignore any INFO messages
  10290. if (printInfoMessages || msg.type != ResultWas::Info)
  10291. stream << Column(msg.message).indent(2) << '\n';
  10292. }
  10293. }
  10294. void printSourceInfo() const {
  10295. Colour colourGuard(Colour::FileName);
  10296. stream << result.getSourceInfo() << ": ";
  10297. }
  10298. std::ostream& stream;
  10299. AssertionStats const& stats;
  10300. AssertionResult const& result;
  10301. Colour::Code colour;
  10302. std::string passOrFail;
  10303. std::string messageLabel;
  10304. std::string message;
  10305. std::vector<MessageInfo> messages;
  10306. bool printInfoMessages;
  10307. };
  10308. std::size_t makeRatio(std::size_t number, std::size_t total) {
  10309. std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number / total : 0;
  10310. return (ratio == 0 && number > 0) ? 1 : ratio;
  10311. }
  10312. std::size_t& findMax(std::size_t& i, std::size_t& j, std::size_t& k) {
  10313. if (i > j && i > k)
  10314. return i;
  10315. else if (j > k)
  10316. return j;
  10317. else
  10318. return k;
  10319. }
  10320. struct ColumnInfo {
  10321. enum Justification { Left, Right };
  10322. std::string name;
  10323. int width;
  10324. Justification justification;
  10325. };
  10326. struct ColumnBreak {};
  10327. struct RowBreak {};
  10328. class Duration {
  10329. enum class Unit {
  10330. Auto,
  10331. Nanoseconds,
  10332. Microseconds,
  10333. Milliseconds,
  10334. Seconds,
  10335. Minutes
  10336. };
  10337. static const uint64_t s_nanosecondsInAMicrosecond = 1000;
  10338. static const uint64_t s_nanosecondsInAMillisecond = 1000 * s_nanosecondsInAMicrosecond;
  10339. static const uint64_t s_nanosecondsInASecond = 1000 * s_nanosecondsInAMillisecond;
  10340. static const uint64_t s_nanosecondsInAMinute = 60 * s_nanosecondsInASecond;
  10341. uint64_t m_inNanoseconds;
  10342. Unit m_units;
  10343. public:
  10344. explicit Duration(uint64_t inNanoseconds, Unit units = Unit::Auto)
  10345. : m_inNanoseconds(inNanoseconds),
  10346. m_units(units) {
  10347. if (m_units == Unit::Auto) {
  10348. if (m_inNanoseconds < s_nanosecondsInAMicrosecond)
  10349. m_units = Unit::Nanoseconds;
  10350. else if (m_inNanoseconds < s_nanosecondsInAMillisecond)
  10351. m_units = Unit::Microseconds;
  10352. else if (m_inNanoseconds < s_nanosecondsInASecond)
  10353. m_units = Unit::Milliseconds;
  10354. else if (m_inNanoseconds < s_nanosecondsInAMinute)
  10355. m_units = Unit::Seconds;
  10356. else
  10357. m_units = Unit::Minutes;
  10358. }
  10359. }
  10360. auto value() const -> double {
  10361. switch (m_units) {
  10362. case Unit::Microseconds:
  10363. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMicrosecond);
  10364. case Unit::Milliseconds:
  10365. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMillisecond);
  10366. case Unit::Seconds:
  10367. return m_inNanoseconds / static_cast<double>(s_nanosecondsInASecond);
  10368. case Unit::Minutes:
  10369. return m_inNanoseconds / static_cast<double>(s_nanosecondsInAMinute);
  10370. default:
  10371. return static_cast<double>(m_inNanoseconds);
  10372. }
  10373. }
  10374. auto unitsAsString() const -> std::string {
  10375. switch (m_units) {
  10376. case Unit::Nanoseconds:
  10377. return "ns";
  10378. case Unit::Microseconds:
  10379. return "µs";
  10380. case Unit::Milliseconds:
  10381. return "ms";
  10382. case Unit::Seconds:
  10383. return "s";
  10384. case Unit::Minutes:
  10385. return "m";
  10386. default:
  10387. return "** internal error **";
  10388. }
  10389. }
  10390. friend auto operator << (std::ostream& os, Duration const& duration) -> std::ostream& {
  10391. return os << duration.value() << " " << duration.unitsAsString();
  10392. }
  10393. };
  10394. } // end anon namespace
  10395. class TablePrinter {
  10396. std::ostream& m_os;
  10397. std::vector<ColumnInfo> m_columnInfos;
  10398. std::ostringstream m_oss;
  10399. int m_currentColumn = -1;
  10400. bool m_isOpen = false;
  10401. public:
  10402. TablePrinter( std::ostream& os, std::vector<ColumnInfo> columnInfos )
  10403. : m_os( os ),
  10404. m_columnInfos( std::move( columnInfos ) ) {}
  10405. auto columnInfos() const -> std::vector<ColumnInfo> const& {
  10406. return m_columnInfos;
  10407. }
  10408. void open() {
  10409. if (!m_isOpen) {
  10410. m_isOpen = true;
  10411. *this << RowBreak();
  10412. for (auto const& info : m_columnInfos)
  10413. *this << info.name << ColumnBreak();
  10414. *this << RowBreak();
  10415. m_os << Catch::getLineOfChars<'-'>() << "\n";
  10416. }
  10417. }
  10418. void close() {
  10419. if (m_isOpen) {
  10420. *this << RowBreak();
  10421. m_os << std::endl;
  10422. m_isOpen = false;
  10423. }
  10424. }
  10425. template<typename T>
  10426. friend TablePrinter& operator << (TablePrinter& tp, T const& value) {
  10427. tp.m_oss << value;
  10428. return tp;
  10429. }
  10430. friend TablePrinter& operator << (TablePrinter& tp, ColumnBreak) {
  10431. auto colStr = tp.m_oss.str();
  10432. // This takes account of utf8 encodings
  10433. auto strSize = Catch::StringRef(colStr).numberOfCharacters();
  10434. tp.m_oss.str("");
  10435. tp.open();
  10436. if (tp.m_currentColumn == static_cast<int>(tp.m_columnInfos.size() - 1)) {
  10437. tp.m_currentColumn = -1;
  10438. tp.m_os << "\n";
  10439. }
  10440. tp.m_currentColumn++;
  10441. auto colInfo = tp.m_columnInfos[tp.m_currentColumn];
  10442. auto padding = (strSize + 2 < static_cast<std::size_t>(colInfo.width))
  10443. ? std::string(colInfo.width - (strSize + 2), ' ')
  10444. : std::string();
  10445. if (colInfo.justification == ColumnInfo::Left)
  10446. tp.m_os << colStr << padding << " ";
  10447. else
  10448. tp.m_os << padding << colStr << " ";
  10449. return tp;
  10450. }
  10451. friend TablePrinter& operator << (TablePrinter& tp, RowBreak) {
  10452. if (tp.m_currentColumn > 0) {
  10453. tp.m_os << "\n";
  10454. tp.m_currentColumn = -1;
  10455. }
  10456. return tp;
  10457. }
  10458. };
  10459. ConsoleReporter::ConsoleReporter(ReporterConfig const& config)
  10460. : StreamingReporterBase(config),
  10461. m_tablePrinter(new TablePrinter(config.stream(),
  10462. {
  10463. { "benchmark name", CATCH_CONFIG_CONSOLE_WIDTH - 32, ColumnInfo::Left },
  10464. { "iters", 8, ColumnInfo::Right },
  10465. { "elapsed ns", 14, ColumnInfo::Right },
  10466. { "average", 14, ColumnInfo::Right }
  10467. })) {}
  10468. ConsoleReporter::~ConsoleReporter() = default;
  10469. std::string ConsoleReporter::getDescription() {
  10470. return "Reports test results as plain lines of text";
  10471. }
  10472. void ConsoleReporter::noMatchingTestCases(std::string const& spec) {
  10473. stream << "No test cases matched '" << spec << '\'' << std::endl;
  10474. }
  10475. void ConsoleReporter::assertionStarting(AssertionInfo const&) {}
  10476. bool ConsoleReporter::assertionEnded(AssertionStats const& _assertionStats) {
  10477. AssertionResult const& result = _assertionStats.assertionResult;
  10478. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  10479. // Drop out if result was successful but we're not printing them.
  10480. if (!includeResults && result.getResultType() != ResultWas::Warning)
  10481. return false;
  10482. lazyPrint();
  10483. ConsoleAssertionPrinter printer(stream, _assertionStats, includeResults);
  10484. printer.print();
  10485. stream << std::endl;
  10486. return true;
  10487. }
  10488. void ConsoleReporter::sectionStarting(SectionInfo const& _sectionInfo) {
  10489. m_headerPrinted = false;
  10490. StreamingReporterBase::sectionStarting(_sectionInfo);
  10491. }
  10492. void ConsoleReporter::sectionEnded(SectionStats const& _sectionStats) {
  10493. m_tablePrinter->close();
  10494. if (_sectionStats.missingAssertions) {
  10495. lazyPrint();
  10496. Colour colour(Colour::ResultError);
  10497. if (m_sectionStack.size() > 1)
  10498. stream << "\nNo assertions in section";
  10499. else
  10500. stream << "\nNo assertions in test case";
  10501. stream << " '" << _sectionStats.sectionInfo.name << "'\n" << std::endl;
  10502. }
  10503. if (m_config->showDurations() == ShowDurations::Always) {
  10504. stream << getFormattedDuration(_sectionStats.durationInSeconds) << " s: " << _sectionStats.sectionInfo.name << std::endl;
  10505. }
  10506. if (m_headerPrinted) {
  10507. m_headerPrinted = false;
  10508. }
  10509. StreamingReporterBase::sectionEnded(_sectionStats);
  10510. }
  10511. void ConsoleReporter::benchmarkStarting(BenchmarkInfo const& info) {
  10512. lazyPrintWithoutClosingBenchmarkTable();
  10513. auto nameCol = Column( info.name ).width( static_cast<std::size_t>( m_tablePrinter->columnInfos()[0].width - 2 ) );
  10514. bool firstLine = true;
  10515. for (auto line : nameCol) {
  10516. if (!firstLine)
  10517. (*m_tablePrinter) << ColumnBreak() << ColumnBreak() << ColumnBreak();
  10518. else
  10519. firstLine = false;
  10520. (*m_tablePrinter) << line << ColumnBreak();
  10521. }
  10522. }
  10523. void ConsoleReporter::benchmarkEnded(BenchmarkStats const& stats) {
  10524. Duration average(stats.elapsedTimeInNanoseconds / stats.iterations);
  10525. (*m_tablePrinter)
  10526. << stats.iterations << ColumnBreak()
  10527. << stats.elapsedTimeInNanoseconds << ColumnBreak()
  10528. << average << ColumnBreak();
  10529. }
  10530. void ConsoleReporter::testCaseEnded(TestCaseStats const& _testCaseStats) {
  10531. m_tablePrinter->close();
  10532. StreamingReporterBase::testCaseEnded(_testCaseStats);
  10533. m_headerPrinted = false;
  10534. }
  10535. void ConsoleReporter::testGroupEnded(TestGroupStats const& _testGroupStats) {
  10536. if (currentGroupInfo.used) {
  10537. printSummaryDivider();
  10538. stream << "Summary for group '" << _testGroupStats.groupInfo.name << "':\n";
  10539. printTotals(_testGroupStats.totals);
  10540. stream << '\n' << std::endl;
  10541. }
  10542. StreamingReporterBase::testGroupEnded(_testGroupStats);
  10543. }
  10544. void ConsoleReporter::testRunEnded(TestRunStats const& _testRunStats) {
  10545. printTotalsDivider(_testRunStats.totals);
  10546. printTotals(_testRunStats.totals);
  10547. stream << std::endl;
  10548. StreamingReporterBase::testRunEnded(_testRunStats);
  10549. }
  10550. void ConsoleReporter::lazyPrint() {
  10551. m_tablePrinter->close();
  10552. lazyPrintWithoutClosingBenchmarkTable();
  10553. }
  10554. void ConsoleReporter::lazyPrintWithoutClosingBenchmarkTable() {
  10555. if (!currentTestRunInfo.used)
  10556. lazyPrintRunInfo();
  10557. if (!currentGroupInfo.used)
  10558. lazyPrintGroupInfo();
  10559. if (!m_headerPrinted) {
  10560. printTestCaseAndSectionHeader();
  10561. m_headerPrinted = true;
  10562. }
  10563. }
  10564. void ConsoleReporter::lazyPrintRunInfo() {
  10565. stream << '\n' << getLineOfChars<'~'>() << '\n';
  10566. Colour colour(Colour::SecondaryText);
  10567. stream << currentTestRunInfo->name
  10568. << " is a Catch v" << libraryVersion() << " host application.\n"
  10569. << "Run with -? for options\n\n";
  10570. if (m_config->rngSeed() != 0)
  10571. stream << "Randomness seeded to: " << m_config->rngSeed() << "\n\n";
  10572. currentTestRunInfo.used = true;
  10573. }
  10574. void ConsoleReporter::lazyPrintGroupInfo() {
  10575. if (!currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1) {
  10576. printClosedHeader("Group: " + currentGroupInfo->name);
  10577. currentGroupInfo.used = true;
  10578. }
  10579. }
  10580. void ConsoleReporter::printTestCaseAndSectionHeader() {
  10581. assert(!m_sectionStack.empty());
  10582. printOpenHeader(currentTestCaseInfo->name);
  10583. if (m_sectionStack.size() > 1) {
  10584. Colour colourGuard(Colour::Headers);
  10585. auto
  10586. it = m_sectionStack.begin() + 1, // Skip first section (test case)
  10587. itEnd = m_sectionStack.end();
  10588. for (; it != itEnd; ++it)
  10589. printHeaderString(it->name, 2);
  10590. }
  10591. SourceLineInfo lineInfo = m_sectionStack.back().lineInfo;
  10592. if (!lineInfo.empty()) {
  10593. stream << getLineOfChars<'-'>() << '\n';
  10594. Colour colourGuard(Colour::FileName);
  10595. stream << lineInfo << '\n';
  10596. }
  10597. stream << getLineOfChars<'.'>() << '\n' << std::endl;
  10598. }
  10599. void ConsoleReporter::printClosedHeader(std::string const& _name) {
  10600. printOpenHeader(_name);
  10601. stream << getLineOfChars<'.'>() << '\n';
  10602. }
  10603. void ConsoleReporter::printOpenHeader(std::string const& _name) {
  10604. stream << getLineOfChars<'-'>() << '\n';
  10605. {
  10606. Colour colourGuard(Colour::Headers);
  10607. printHeaderString(_name);
  10608. }
  10609. }
  10610. // if string has a : in first line will set indent to follow it on
  10611. // subsequent lines
  10612. void ConsoleReporter::printHeaderString(std::string const& _string, std::size_t indent) {
  10613. std::size_t i = _string.find(": ");
  10614. if (i != std::string::npos)
  10615. i += 2;
  10616. else
  10617. i = 0;
  10618. stream << Column(_string).indent(indent + i).initialIndent(indent) << '\n';
  10619. }
  10620. struct SummaryColumn {
  10621. SummaryColumn( std::string _label, Colour::Code _colour )
  10622. : label( std::move( _label ) ),
  10623. colour( _colour ) {}
  10624. SummaryColumn addRow( std::size_t count ) {
  10625. ReusableStringStream rss;
  10626. rss << count;
  10627. std::string row = rss.str();
  10628. for (auto& oldRow : rows) {
  10629. while (oldRow.size() < row.size())
  10630. oldRow = ' ' + oldRow;
  10631. while (oldRow.size() > row.size())
  10632. row = ' ' + row;
  10633. }
  10634. rows.push_back(row);
  10635. return *this;
  10636. }
  10637. std::string label;
  10638. Colour::Code colour;
  10639. std::vector<std::string> rows;
  10640. };
  10641. void ConsoleReporter::printTotals( Totals const& totals ) {
  10642. if (totals.testCases.total() == 0) {
  10643. stream << Colour(Colour::Warning) << "No tests ran\n";
  10644. } else if (totals.assertions.total() > 0 && totals.testCases.allPassed()) {
  10645. stream << Colour(Colour::ResultSuccess) << "All tests passed";
  10646. stream << " ("
  10647. << pluralise(totals.assertions.passed, "assertion") << " in "
  10648. << pluralise(totals.testCases.passed, "test case") << ')'
  10649. << '\n';
  10650. } else {
  10651. std::vector<SummaryColumn> columns;
  10652. columns.push_back(SummaryColumn("", Colour::None)
  10653. .addRow(totals.testCases.total())
  10654. .addRow(totals.assertions.total()));
  10655. columns.push_back(SummaryColumn("passed", Colour::Success)
  10656. .addRow(totals.testCases.passed)
  10657. .addRow(totals.assertions.passed));
  10658. columns.push_back(SummaryColumn("failed", Colour::ResultError)
  10659. .addRow(totals.testCases.failed)
  10660. .addRow(totals.assertions.failed));
  10661. columns.push_back(SummaryColumn("failed as expected", Colour::ResultExpectedFailure)
  10662. .addRow(totals.testCases.failedButOk)
  10663. .addRow(totals.assertions.failedButOk));
  10664. printSummaryRow("test cases", columns, 0);
  10665. printSummaryRow("assertions", columns, 1);
  10666. }
  10667. }
  10668. void ConsoleReporter::printSummaryRow(std::string const& label, std::vector<SummaryColumn> const& cols, std::size_t row) {
  10669. for (auto col : cols) {
  10670. std::string value = col.rows[row];
  10671. if (col.label.empty()) {
  10672. stream << label << ": ";
  10673. if (value != "0")
  10674. stream << value;
  10675. else
  10676. stream << Colour(Colour::Warning) << "- none -";
  10677. } else if (value != "0") {
  10678. stream << Colour(Colour::LightGrey) << " | ";
  10679. stream << Colour(col.colour)
  10680. << value << ' ' << col.label;
  10681. }
  10682. }
  10683. stream << '\n';
  10684. }
  10685. void ConsoleReporter::printTotalsDivider(Totals const& totals) {
  10686. if (totals.testCases.total() > 0) {
  10687. std::size_t failedRatio = makeRatio(totals.testCases.failed, totals.testCases.total());
  10688. std::size_t failedButOkRatio = makeRatio(totals.testCases.failedButOk, totals.testCases.total());
  10689. std::size_t passedRatio = makeRatio(totals.testCases.passed, totals.testCases.total());
  10690. while (failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH - 1)
  10691. findMax(failedRatio, failedButOkRatio, passedRatio)++;
  10692. while (failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH - 1)
  10693. findMax(failedRatio, failedButOkRatio, passedRatio)--;
  10694. stream << Colour(Colour::Error) << std::string(failedRatio, '=');
  10695. stream << Colour(Colour::ResultExpectedFailure) << std::string(failedButOkRatio, '=');
  10696. if (totals.testCases.allPassed())
  10697. stream << Colour(Colour::ResultSuccess) << std::string(passedRatio, '=');
  10698. else
  10699. stream << Colour(Colour::Success) << std::string(passedRatio, '=');
  10700. } else {
  10701. stream << Colour(Colour::Warning) << std::string(CATCH_CONFIG_CONSOLE_WIDTH - 1, '=');
  10702. }
  10703. stream << '\n';
  10704. }
  10705. void ConsoleReporter::printSummaryDivider() {
  10706. stream << getLineOfChars<'-'>() << '\n';
  10707. }
  10708. CATCH_REGISTER_REPORTER("console", ConsoleReporter)
  10709. } // end namespace Catch
  10710. #if defined(_MSC_VER)
  10711. #pragma warning(pop)
  10712. #endif
  10713. // end catch_reporter_console.cpp
  10714. // start catch_reporter_junit.cpp
  10715. #include <cassert>
  10716. #include <sstream>
  10717. #include <ctime>
  10718. #include <algorithm>
  10719. namespace Catch {
  10720. namespace {
  10721. std::string getCurrentTimestamp() {
  10722. // Beware, this is not reentrant because of backward compatibility issues
  10723. // Also, UTC only, again because of backward compatibility (%z is C++11)
  10724. time_t rawtime;
  10725. std::time(&rawtime);
  10726. auto const timeStampSize = sizeof("2017-01-16T17:06:45Z");
  10727. #ifdef _MSC_VER
  10728. std::tm timeInfo = {};
  10729. gmtime_s(&timeInfo, &rawtime);
  10730. #else
  10731. std::tm* timeInfo;
  10732. timeInfo = std::gmtime(&rawtime);
  10733. #endif
  10734. char timeStamp[timeStampSize];
  10735. const char * const fmt = "%Y-%m-%dT%H:%M:%SZ";
  10736. #ifdef _MSC_VER
  10737. std::strftime(timeStamp, timeStampSize, fmt, &timeInfo);
  10738. #else
  10739. std::strftime(timeStamp, timeStampSize, fmt, timeInfo);
  10740. #endif
  10741. return std::string(timeStamp);
  10742. }
  10743. std::string fileNameTag(const std::vector<std::string> &tags) {
  10744. auto it = std::find_if(begin(tags),
  10745. end(tags),
  10746. [] (std::string const& tag) {return tag.front() == '#'; });
  10747. if (it != tags.end())
  10748. return it->substr(1);
  10749. return std::string();
  10750. }
  10751. } // anonymous namespace
  10752. JunitReporter::JunitReporter( ReporterConfig const& _config )
  10753. : CumulativeReporterBase( _config ),
  10754. xml( _config.stream() )
  10755. {
  10756. m_reporterPrefs.shouldRedirectStdOut = true;
  10757. m_reporterPrefs.shouldReportAllAssertions = true;
  10758. }
  10759. JunitReporter::~JunitReporter() {}
  10760. std::string JunitReporter::getDescription() {
  10761. return "Reports test results in an XML format that looks like Ant's junitreport target";
  10762. }
  10763. void JunitReporter::noMatchingTestCases( std::string const& /*spec*/ ) {}
  10764. void JunitReporter::testRunStarting( TestRunInfo const& runInfo ) {
  10765. CumulativeReporterBase::testRunStarting( runInfo );
  10766. xml.startElement( "testsuites" );
  10767. }
  10768. void JunitReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  10769. suiteTimer.start();
  10770. stdOutForSuite.clear();
  10771. stdErrForSuite.clear();
  10772. unexpectedExceptions = 0;
  10773. CumulativeReporterBase::testGroupStarting( groupInfo );
  10774. }
  10775. void JunitReporter::testCaseStarting( TestCaseInfo const& testCaseInfo ) {
  10776. m_okToFail = testCaseInfo.okToFail();
  10777. }
  10778. bool JunitReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10779. if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException && !m_okToFail )
  10780. unexpectedExceptions++;
  10781. return CumulativeReporterBase::assertionEnded( assertionStats );
  10782. }
  10783. void JunitReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10784. stdOutForSuite += testCaseStats.stdOut;
  10785. stdErrForSuite += testCaseStats.stdErr;
  10786. CumulativeReporterBase::testCaseEnded( testCaseStats );
  10787. }
  10788. void JunitReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10789. double suiteTime = suiteTimer.getElapsedSeconds();
  10790. CumulativeReporterBase::testGroupEnded( testGroupStats );
  10791. writeGroup( *m_testGroups.back(), suiteTime );
  10792. }
  10793. void JunitReporter::testRunEndedCumulative() {
  10794. xml.endElement();
  10795. }
  10796. void JunitReporter::writeGroup( TestGroupNode const& groupNode, double suiteTime ) {
  10797. XmlWriter::ScopedElement e = xml.scopedElement( "testsuite" );
  10798. TestGroupStats const& stats = groupNode.value;
  10799. xml.writeAttribute( "name", stats.groupInfo.name );
  10800. xml.writeAttribute( "errors", unexpectedExceptions );
  10801. xml.writeAttribute( "failures", stats.totals.assertions.failed-unexpectedExceptions );
  10802. xml.writeAttribute( "tests", stats.totals.assertions.total() );
  10803. xml.writeAttribute( "hostname", "tbd" ); // !TBD
  10804. if( m_config->showDurations() == ShowDurations::Never )
  10805. xml.writeAttribute( "time", "" );
  10806. else
  10807. xml.writeAttribute( "time", suiteTime );
  10808. xml.writeAttribute( "timestamp", getCurrentTimestamp() );
  10809. // Write test cases
  10810. for( auto const& child : groupNode.children )
  10811. writeTestCase( *child );
  10812. xml.scopedElement( "system-out" ).writeText( trim( stdOutForSuite ), false );
  10813. xml.scopedElement( "system-err" ).writeText( trim( stdErrForSuite ), false );
  10814. }
  10815. void JunitReporter::writeTestCase( TestCaseNode const& testCaseNode ) {
  10816. TestCaseStats const& stats = testCaseNode.value;
  10817. // All test cases have exactly one section - which represents the
  10818. // test case itself. That section may have 0-n nested sections
  10819. assert( testCaseNode.children.size() == 1 );
  10820. SectionNode const& rootSection = *testCaseNode.children.front();
  10821. std::string className = stats.testInfo.className;
  10822. if( className.empty() ) {
  10823. className = fileNameTag(stats.testInfo.tags);
  10824. if ( className.empty() )
  10825. className = "global";
  10826. }
  10827. if ( !m_config->name().empty() )
  10828. className = m_config->name() + "." + className;
  10829. writeSection( className, "", rootSection );
  10830. }
  10831. void JunitReporter::writeSection( std::string const& className,
  10832. std::string const& rootName,
  10833. SectionNode const& sectionNode ) {
  10834. std::string name = trim( sectionNode.stats.sectionInfo.name );
  10835. if( !rootName.empty() )
  10836. name = rootName + '/' + name;
  10837. if( !sectionNode.assertions.empty() ||
  10838. !sectionNode.stdOut.empty() ||
  10839. !sectionNode.stdErr.empty() ) {
  10840. XmlWriter::ScopedElement e = xml.scopedElement( "testcase" );
  10841. if( className.empty() ) {
  10842. xml.writeAttribute( "classname", name );
  10843. xml.writeAttribute( "name", "root" );
  10844. }
  10845. else {
  10846. xml.writeAttribute( "classname", className );
  10847. xml.writeAttribute( "name", name );
  10848. }
  10849. xml.writeAttribute( "time", ::Catch::Detail::stringify( sectionNode.stats.durationInSeconds ) );
  10850. writeAssertions( sectionNode );
  10851. if( !sectionNode.stdOut.empty() )
  10852. xml.scopedElement( "system-out" ).writeText( trim( sectionNode.stdOut ), false );
  10853. if( !sectionNode.stdErr.empty() )
  10854. xml.scopedElement( "system-err" ).writeText( trim( sectionNode.stdErr ), false );
  10855. }
  10856. for( auto const& childNode : sectionNode.childSections )
  10857. if( className.empty() )
  10858. writeSection( name, "", *childNode );
  10859. else
  10860. writeSection( className, name, *childNode );
  10861. }
  10862. void JunitReporter::writeAssertions( SectionNode const& sectionNode ) {
  10863. for( auto const& assertion : sectionNode.assertions )
  10864. writeAssertion( assertion );
  10865. }
  10866. void JunitReporter::writeAssertion( AssertionStats const& stats ) {
  10867. AssertionResult const& result = stats.assertionResult;
  10868. if( !result.isOk() ) {
  10869. std::string elementName;
  10870. switch( result.getResultType() ) {
  10871. case ResultWas::ThrewException:
  10872. case ResultWas::FatalErrorCondition:
  10873. elementName = "error";
  10874. break;
  10875. case ResultWas::ExplicitFailure:
  10876. elementName = "failure";
  10877. break;
  10878. case ResultWas::ExpressionFailed:
  10879. elementName = "failure";
  10880. break;
  10881. case ResultWas::DidntThrowException:
  10882. elementName = "failure";
  10883. break;
  10884. // We should never see these here:
  10885. case ResultWas::Info:
  10886. case ResultWas::Warning:
  10887. case ResultWas::Ok:
  10888. case ResultWas::Unknown:
  10889. case ResultWas::FailureBit:
  10890. case ResultWas::Exception:
  10891. elementName = "internalError";
  10892. break;
  10893. }
  10894. XmlWriter::ScopedElement e = xml.scopedElement( elementName );
  10895. xml.writeAttribute( "message", result.getExpandedExpression() );
  10896. xml.writeAttribute( "type", result.getTestMacroName() );
  10897. ReusableStringStream rss;
  10898. if( !result.getMessage().empty() )
  10899. rss << result.getMessage() << '\n';
  10900. for( auto const& msg : stats.infoMessages )
  10901. if( msg.type == ResultWas::Info )
  10902. rss << msg.message << '\n';
  10903. rss << "at " << result.getSourceInfo();
  10904. xml.writeText( rss.str(), false );
  10905. }
  10906. }
  10907. CATCH_REGISTER_REPORTER( "junit", JunitReporter )
  10908. } // end namespace Catch
  10909. // end catch_reporter_junit.cpp
  10910. // start catch_reporter_listening.cpp
  10911. #include <cassert>
  10912. namespace Catch {
  10913. ListeningReporter::ListeningReporter() {
  10914. // We will assume that listeners will always want all assertions
  10915. m_preferences.shouldReportAllAssertions = true;
  10916. }
  10917. void ListeningReporter::addListener( IStreamingReporterPtr&& listener ) {
  10918. m_listeners.push_back( std::move( listener ) );
  10919. }
  10920. void ListeningReporter::addReporter(IStreamingReporterPtr&& reporter) {
  10921. assert(!m_reporter && "Listening reporter can wrap only 1 real reporter");
  10922. m_reporter = std::move( reporter );
  10923. m_preferences.shouldRedirectStdOut = m_reporter->getPreferences().shouldRedirectStdOut;
  10924. }
  10925. ReporterPreferences ListeningReporter::getPreferences() const {
  10926. return m_preferences;
  10927. }
  10928. std::set<Verbosity> ListeningReporter::getSupportedVerbosities() {
  10929. return std::set<Verbosity>{ };
  10930. }
  10931. void ListeningReporter::noMatchingTestCases( std::string const& spec ) {
  10932. for ( auto const& listener : m_listeners ) {
  10933. listener->noMatchingTestCases( spec );
  10934. }
  10935. m_reporter->noMatchingTestCases( spec );
  10936. }
  10937. void ListeningReporter::benchmarkStarting( BenchmarkInfo const& benchmarkInfo ) {
  10938. for ( auto const& listener : m_listeners ) {
  10939. listener->benchmarkStarting( benchmarkInfo );
  10940. }
  10941. m_reporter->benchmarkStarting( benchmarkInfo );
  10942. }
  10943. void ListeningReporter::benchmarkEnded( BenchmarkStats const& benchmarkStats ) {
  10944. for ( auto const& listener : m_listeners ) {
  10945. listener->benchmarkEnded( benchmarkStats );
  10946. }
  10947. m_reporter->benchmarkEnded( benchmarkStats );
  10948. }
  10949. void ListeningReporter::testRunStarting( TestRunInfo const& testRunInfo ) {
  10950. for ( auto const& listener : m_listeners ) {
  10951. listener->testRunStarting( testRunInfo );
  10952. }
  10953. m_reporter->testRunStarting( testRunInfo );
  10954. }
  10955. void ListeningReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  10956. for ( auto const& listener : m_listeners ) {
  10957. listener->testGroupStarting( groupInfo );
  10958. }
  10959. m_reporter->testGroupStarting( groupInfo );
  10960. }
  10961. void ListeningReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  10962. for ( auto const& listener : m_listeners ) {
  10963. listener->testCaseStarting( testInfo );
  10964. }
  10965. m_reporter->testCaseStarting( testInfo );
  10966. }
  10967. void ListeningReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  10968. for ( auto const& listener : m_listeners ) {
  10969. listener->sectionStarting( sectionInfo );
  10970. }
  10971. m_reporter->sectionStarting( sectionInfo );
  10972. }
  10973. void ListeningReporter::assertionStarting( AssertionInfo const& assertionInfo ) {
  10974. for ( auto const& listener : m_listeners ) {
  10975. listener->assertionStarting( assertionInfo );
  10976. }
  10977. m_reporter->assertionStarting( assertionInfo );
  10978. }
  10979. // The return value indicates if the messages buffer should be cleared:
  10980. bool ListeningReporter::assertionEnded( AssertionStats const& assertionStats ) {
  10981. for( auto const& listener : m_listeners ) {
  10982. static_cast<void>( listener->assertionEnded( assertionStats ) );
  10983. }
  10984. return m_reporter->assertionEnded( assertionStats );
  10985. }
  10986. void ListeningReporter::sectionEnded( SectionStats const& sectionStats ) {
  10987. for ( auto const& listener : m_listeners ) {
  10988. listener->sectionEnded( sectionStats );
  10989. }
  10990. m_reporter->sectionEnded( sectionStats );
  10991. }
  10992. void ListeningReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  10993. for ( auto const& listener : m_listeners ) {
  10994. listener->testCaseEnded( testCaseStats );
  10995. }
  10996. m_reporter->testCaseEnded( testCaseStats );
  10997. }
  10998. void ListeningReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  10999. for ( auto const& listener : m_listeners ) {
  11000. listener->testGroupEnded( testGroupStats );
  11001. }
  11002. m_reporter->testGroupEnded( testGroupStats );
  11003. }
  11004. void ListeningReporter::testRunEnded( TestRunStats const& testRunStats ) {
  11005. for ( auto const& listener : m_listeners ) {
  11006. listener->testRunEnded( testRunStats );
  11007. }
  11008. m_reporter->testRunEnded( testRunStats );
  11009. }
  11010. void ListeningReporter::skipTest( TestCaseInfo const& testInfo ) {
  11011. for ( auto const& listener : m_listeners ) {
  11012. listener->skipTest( testInfo );
  11013. }
  11014. m_reporter->skipTest( testInfo );
  11015. }
  11016. bool ListeningReporter::isMulti() const {
  11017. return true;
  11018. }
  11019. } // end namespace Catch
  11020. // end catch_reporter_listening.cpp
  11021. // start catch_reporter_xml.cpp
  11022. #if defined(_MSC_VER)
  11023. #pragma warning(push)
  11024. #pragma warning(disable:4061) // Not all labels are EXPLICITLY handled in switch
  11025. // Note that 4062 (not all labels are handled
  11026. // and default is missing) is enabled
  11027. #endif
  11028. namespace Catch {
  11029. XmlReporter::XmlReporter( ReporterConfig const& _config )
  11030. : StreamingReporterBase( _config ),
  11031. m_xml(_config.stream())
  11032. {
  11033. m_reporterPrefs.shouldRedirectStdOut = true;
  11034. m_reporterPrefs.shouldReportAllAssertions = true;
  11035. }
  11036. XmlReporter::~XmlReporter() = default;
  11037. std::string XmlReporter::getDescription() {
  11038. return "Reports test results as an XML document";
  11039. }
  11040. std::string XmlReporter::getStylesheetRef() const {
  11041. return std::string();
  11042. }
  11043. void XmlReporter::writeSourceInfo( SourceLineInfo const& sourceInfo ) {
  11044. m_xml
  11045. .writeAttribute( "filename", sourceInfo.file )
  11046. .writeAttribute( "line", sourceInfo.line );
  11047. }
  11048. void XmlReporter::noMatchingTestCases( std::string const& s ) {
  11049. StreamingReporterBase::noMatchingTestCases( s );
  11050. }
  11051. void XmlReporter::testRunStarting( TestRunInfo const& testInfo ) {
  11052. StreamingReporterBase::testRunStarting( testInfo );
  11053. std::string stylesheetRef = getStylesheetRef();
  11054. if( !stylesheetRef.empty() )
  11055. m_xml.writeStylesheetRef( stylesheetRef );
  11056. m_xml.startElement( "Catch" );
  11057. if( !m_config->name().empty() )
  11058. m_xml.writeAttribute( "name", m_config->name() );
  11059. if( m_config->rngSeed() != 0 )
  11060. m_xml.scopedElement( "Randomness" )
  11061. .writeAttribute( "seed", m_config->rngSeed() );
  11062. }
  11063. void XmlReporter::testGroupStarting( GroupInfo const& groupInfo ) {
  11064. StreamingReporterBase::testGroupStarting( groupInfo );
  11065. m_xml.startElement( "Group" )
  11066. .writeAttribute( "name", groupInfo.name );
  11067. }
  11068. void XmlReporter::testCaseStarting( TestCaseInfo const& testInfo ) {
  11069. StreamingReporterBase::testCaseStarting(testInfo);
  11070. m_xml.startElement( "TestCase" )
  11071. .writeAttribute( "name", trim( testInfo.name ) )
  11072. .writeAttribute( "description", testInfo.description )
  11073. .writeAttribute( "tags", testInfo.tagsAsString() );
  11074. writeSourceInfo( testInfo.lineInfo );
  11075. if ( m_config->showDurations() == ShowDurations::Always )
  11076. m_testCaseTimer.start();
  11077. m_xml.ensureTagClosed();
  11078. }
  11079. void XmlReporter::sectionStarting( SectionInfo const& sectionInfo ) {
  11080. StreamingReporterBase::sectionStarting( sectionInfo );
  11081. if( m_sectionDepth++ > 0 ) {
  11082. m_xml.startElement( "Section" )
  11083. .writeAttribute( "name", trim( sectionInfo.name ) );
  11084. writeSourceInfo( sectionInfo.lineInfo );
  11085. m_xml.ensureTagClosed();
  11086. }
  11087. }
  11088. void XmlReporter::assertionStarting( AssertionInfo const& ) { }
  11089. bool XmlReporter::assertionEnded( AssertionStats const& assertionStats ) {
  11090. AssertionResult const& result = assertionStats.assertionResult;
  11091. bool includeResults = m_config->includeSuccessfulResults() || !result.isOk();
  11092. if( includeResults || result.getResultType() == ResultWas::Warning ) {
  11093. // Print any info messages in <Info> tags.
  11094. for( auto const& msg : assertionStats.infoMessages ) {
  11095. if( msg.type == ResultWas::Info && includeResults ) {
  11096. m_xml.scopedElement( "Info" )
  11097. .writeText( msg.message );
  11098. } else if ( msg.type == ResultWas::Warning ) {
  11099. m_xml.scopedElement( "Warning" )
  11100. .writeText( msg.message );
  11101. }
  11102. }
  11103. }
  11104. // Drop out if result was successful but we're not printing them.
  11105. if( !includeResults && result.getResultType() != ResultWas::Warning )
  11106. return true;
  11107. // Print the expression if there is one.
  11108. if( result.hasExpression() ) {
  11109. m_xml.startElement( "Expression" )
  11110. .writeAttribute( "success", result.succeeded() )
  11111. .writeAttribute( "type", result.getTestMacroName() );
  11112. writeSourceInfo( result.getSourceInfo() );
  11113. m_xml.scopedElement( "Original" )
  11114. .writeText( result.getExpression() );
  11115. m_xml.scopedElement( "Expanded" )
  11116. .writeText( result.getExpandedExpression() );
  11117. }
  11118. // And... Print a result applicable to each result type.
  11119. switch( result.getResultType() ) {
  11120. case ResultWas::ThrewException:
  11121. m_xml.startElement( "Exception" );
  11122. writeSourceInfo( result.getSourceInfo() );
  11123. m_xml.writeText( result.getMessage() );
  11124. m_xml.endElement();
  11125. break;
  11126. case ResultWas::FatalErrorCondition:
  11127. m_xml.startElement( "FatalErrorCondition" );
  11128. writeSourceInfo( result.getSourceInfo() );
  11129. m_xml.writeText( result.getMessage() );
  11130. m_xml.endElement();
  11131. break;
  11132. case ResultWas::Info:
  11133. m_xml.scopedElement( "Info" )
  11134. .writeText( result.getMessage() );
  11135. break;
  11136. case ResultWas::Warning:
  11137. // Warning will already have been written
  11138. break;
  11139. case ResultWas::ExplicitFailure:
  11140. m_xml.startElement( "Failure" );
  11141. writeSourceInfo( result.getSourceInfo() );
  11142. m_xml.writeText( result.getMessage() );
  11143. m_xml.endElement();
  11144. break;
  11145. default:
  11146. break;
  11147. }
  11148. if( result.hasExpression() )
  11149. m_xml.endElement();
  11150. return true;
  11151. }
  11152. void XmlReporter::sectionEnded( SectionStats const& sectionStats ) {
  11153. StreamingReporterBase::sectionEnded( sectionStats );
  11154. if( --m_sectionDepth > 0 ) {
  11155. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResults" );
  11156. e.writeAttribute( "successes", sectionStats.assertions.passed );
  11157. e.writeAttribute( "failures", sectionStats.assertions.failed );
  11158. e.writeAttribute( "expectedFailures", sectionStats.assertions.failedButOk );
  11159. if ( m_config->showDurations() == ShowDurations::Always )
  11160. e.writeAttribute( "durationInSeconds", sectionStats.durationInSeconds );
  11161. m_xml.endElement();
  11162. }
  11163. }
  11164. void XmlReporter::testCaseEnded( TestCaseStats const& testCaseStats ) {
  11165. StreamingReporterBase::testCaseEnded( testCaseStats );
  11166. XmlWriter::ScopedElement e = m_xml.scopedElement( "OverallResult" );
  11167. e.writeAttribute( "success", testCaseStats.totals.assertions.allOk() );
  11168. if ( m_config->showDurations() == ShowDurations::Always )
  11169. e.writeAttribute( "durationInSeconds", m_testCaseTimer.getElapsedSeconds() );
  11170. if( !testCaseStats.stdOut.empty() )
  11171. m_xml.scopedElement( "StdOut" ).writeText( trim( testCaseStats.stdOut ), false );
  11172. if( !testCaseStats.stdErr.empty() )
  11173. m_xml.scopedElement( "StdErr" ).writeText( trim( testCaseStats.stdErr ), false );
  11174. m_xml.endElement();
  11175. }
  11176. void XmlReporter::testGroupEnded( TestGroupStats const& testGroupStats ) {
  11177. StreamingReporterBase::testGroupEnded( testGroupStats );
  11178. // TODO: Check testGroupStats.aborting and act accordingly.
  11179. m_xml.scopedElement( "OverallResults" )
  11180. .writeAttribute( "successes", testGroupStats.totals.assertions.passed )
  11181. .writeAttribute( "failures", testGroupStats.totals.assertions.failed )
  11182. .writeAttribute( "expectedFailures", testGroupStats.totals.assertions.failedButOk );
  11183. m_xml.endElement();
  11184. }
  11185. void XmlReporter::testRunEnded( TestRunStats const& testRunStats ) {
  11186. StreamingReporterBase::testRunEnded( testRunStats );
  11187. m_xml.scopedElement( "OverallResults" )
  11188. .writeAttribute( "successes", testRunStats.totals.assertions.passed )
  11189. .writeAttribute( "failures", testRunStats.totals.assertions.failed )
  11190. .writeAttribute( "expectedFailures", testRunStats.totals.assertions.failedButOk );
  11191. m_xml.endElement();
  11192. }
  11193. CATCH_REGISTER_REPORTER( "xml", XmlReporter )
  11194. } // end namespace Catch
  11195. #if defined(_MSC_VER)
  11196. #pragma warning(pop)
  11197. #endif
  11198. // end catch_reporter_xml.cpp
  11199. namespace Catch {
  11200. LeakDetector leakDetector;
  11201. }
  11202. #ifdef __clang__
  11203. #pragma clang diagnostic pop
  11204. #endif
  11205. // end catch_impl.hpp
  11206. #endif
  11207. #ifdef CATCH_CONFIG_MAIN
  11208. // start catch_default_main.hpp
  11209. #ifndef __OBJC__
  11210. #if defined(CATCH_CONFIG_WCHAR) && defined(WIN32) && defined(_UNICODE) && !defined(DO_NOT_USE_WMAIN)
  11211. // Standard C/C++ Win32 Unicode wmain entry point
  11212. extern "C" int wmain (int argc, wchar_t * argv[], wchar_t * []) {
  11213. #else
  11214. // Standard C/C++ main entry point
  11215. int main (int argc, char * argv[]) {
  11216. #endif
  11217. return Catch::Session().run( argc, argv );
  11218. }
  11219. #else // __OBJC__
  11220. // Objective-C entry point
  11221. int main (int argc, char * const argv[]) {
  11222. #if !CATCH_ARC_ENABLED
  11223. NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
  11224. #endif
  11225. Catch::registerTestMethods();
  11226. int result = Catch::Session().run( argc, (char**)argv );
  11227. #if !CATCH_ARC_ENABLED
  11228. [pool drain];
  11229. #endif
  11230. return result;
  11231. }
  11232. #endif // __OBJC__
  11233. // end catch_default_main.hpp
  11234. #endif
  11235. #if !defined(CATCH_CONFIG_IMPL_ONLY)
  11236. #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED
  11237. # undef CLARA_CONFIG_MAIN
  11238. #endif
  11239. #if !defined(CATCH_CONFIG_DISABLE)
  11240. //////
  11241. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  11242. #ifdef CATCH_CONFIG_PREFIX_ALL
  11243. #define CATCH_REQUIRE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11244. #define CATCH_REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11245. #define CATCH_REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_REQUIRE_THROWS", Catch::ResultDisposition::Normal, "", __VA_ARGS__ )
  11246. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  11247. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  11248. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11249. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  11250. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  11251. #define CATCH_REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11252. #define CATCH_CHECK( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11253. #define CATCH_CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11254. #define CATCH_CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CATCH_CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11255. #define CATCH_CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CATCH_CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11256. #define CATCH_CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CATCH_CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  11257. #define CATCH_CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CATCH_CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, "", __VA_ARGS__ )
  11258. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CATCH_CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  11259. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CATCH_CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11260. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11261. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CATCH_CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11262. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11263. #define CATCH_CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CATCH_CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11264. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11265. #define CATCH_CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  11266. #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CATCH_REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  11267. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11268. #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( "CATCH_INFO", msg )
  11269. #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( "CATCH_WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  11270. #define CATCH_CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CATCH_CAPTURE",__VA_ARGS__ )
  11271. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  11272. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11273. #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  11274. #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  11275. #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  11276. #define CATCH_DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  11277. #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11278. #define CATCH_FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "CATCH_FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11279. #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( "CATCH_SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11280. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  11281. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  11282. #define CATCH_STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__ , #__VA_ARGS__ ); CATCH_SUCCEED( #__VA_ARGS__ )
  11283. #define CATCH_STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); CATCH_SUCCEED( #__VA_ARGS__ )
  11284. #else
  11285. #define CATCH_STATIC_REQUIRE( ... ) CATCH_REQUIRE( __VA_ARGS__ )
  11286. #define CATCH_STATIC_REQUIRE_FALSE( ... ) CATCH_REQUIRE_FALSE( __VA_ARGS__ )
  11287. #endif
  11288. // "BDD-style" convenience wrappers
  11289. #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( "Scenario: " __VA_ARGS__ )
  11290. #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  11291. #define CATCH_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  11292. #define CATCH_AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  11293. #define CATCH_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  11294. #define CATCH_AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  11295. #define CATCH_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  11296. #define CATCH_AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  11297. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  11298. #else
  11299. #define REQUIRE( ... ) INTERNAL_CATCH_TEST( "REQUIRE", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11300. #define REQUIRE_FALSE( ... ) INTERNAL_CATCH_TEST( "REQUIRE_FALSE", Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11301. #define REQUIRE_THROWS( ... ) INTERNAL_CATCH_THROWS( "REQUIRE_THROWS", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11302. #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "REQUIRE_THROWS_AS", exceptionType, Catch::ResultDisposition::Normal, expr )
  11303. #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "REQUIRE_THROWS_WITH", Catch::ResultDisposition::Normal, matcher, expr )
  11304. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11305. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "REQUIRE_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::Normal, matcher, expr )
  11306. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11307. #define REQUIRE_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "REQUIRE_NOTHROW", Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11308. #define CHECK( ... ) INTERNAL_CATCH_TEST( "CHECK", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11309. #define CHECK_FALSE( ... ) INTERNAL_CATCH_TEST( "CHECK_FALSE", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, __VA_ARGS__ )
  11310. #define CHECKED_IF( ... ) INTERNAL_CATCH_IF( "CHECKED_IF", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11311. #define CHECKED_ELSE( ... ) INTERNAL_CATCH_ELSE( "CHECKED_ELSE", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11312. #define CHECK_NOFAIL( ... ) INTERNAL_CATCH_TEST( "CHECK_NOFAIL", Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, __VA_ARGS__ )
  11313. #define CHECK_THROWS( ... ) INTERNAL_CATCH_THROWS( "CHECK_THROWS", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11314. #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( "CHECK_THROWS_AS", exceptionType, Catch::ResultDisposition::ContinueOnFailure, expr )
  11315. #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS_STR_MATCHES( "CHECK_THROWS_WITH", Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11316. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11317. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) INTERNAL_CATCH_THROWS_MATCHES( "CHECK_THROWS_MATCHES", exceptionType, Catch::ResultDisposition::ContinueOnFailure, matcher, expr )
  11318. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11319. #define CHECK_NOTHROW( ... ) INTERNAL_CATCH_NO_THROW( "CHECK_NOTHROW", Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11320. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11321. #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "CHECK_THAT", matcher, Catch::ResultDisposition::ContinueOnFailure, arg )
  11322. #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( "REQUIRE_THAT", matcher, Catch::ResultDisposition::Normal, arg )
  11323. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11324. #define INFO( msg ) INTERNAL_CATCH_INFO( "INFO", msg )
  11325. #define WARN( msg ) INTERNAL_CATCH_MSG( "WARN", Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, msg )
  11326. #define CAPTURE( ... ) INTERNAL_CATCH_CAPTURE( INTERNAL_CATCH_UNIQUE_NAME(capturer), "CAPTURE",__VA_ARGS__ )
  11327. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ )
  11328. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ )
  11329. #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ )
  11330. #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ )
  11331. #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ )
  11332. #define DYNAMIC_SECTION( ... ) INTERNAL_CATCH_DYNAMIC_SECTION( __VA_ARGS__ )
  11333. #define FAIL( ... ) INTERNAL_CATCH_MSG( "FAIL", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, __VA_ARGS__ )
  11334. #define FAIL_CHECK( ... ) INTERNAL_CATCH_MSG( "FAIL_CHECK", Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11335. #define SUCCEED( ... ) INTERNAL_CATCH_MSG( "SUCCEED", Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, __VA_ARGS__ )
  11336. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE()
  11337. #if !defined(CATCH_CONFIG_RUNTIME_STATIC_REQUIRE)
  11338. #define STATIC_REQUIRE( ... ) static_assert( __VA_ARGS__, #__VA_ARGS__ ); SUCCEED( #__VA_ARGS__ )
  11339. #define STATIC_REQUIRE_FALSE( ... ) static_assert( !(__VA_ARGS__), "!(" #__VA_ARGS__ ")" ); SUCCEED( "!(" #__VA_ARGS__ ")" )
  11340. #else
  11341. #define STATIC_REQUIRE( ... ) REQUIRE( __VA_ARGS__ )
  11342. #define STATIC_REQUIRE_FALSE( ... ) REQUIRE_FALSE( __VA_ARGS__ )
  11343. #endif
  11344. #endif
  11345. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature )
  11346. // "BDD-style" convenience wrappers
  11347. #define SCENARIO( ... ) TEST_CASE( "Scenario: " __VA_ARGS__ )
  11348. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, "Scenario: " __VA_ARGS__ )
  11349. #define GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Given: " << desc )
  11350. #define AND_GIVEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( "And given: " << desc )
  11351. #define WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " When: " << desc )
  11352. #define AND_WHEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And when: " << desc )
  11353. #define THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " Then: " << desc )
  11354. #define AND_THEN( desc ) INTERNAL_CATCH_DYNAMIC_SECTION( " And: " << desc )
  11355. using Catch::Detail::Approx;
  11356. #else // CATCH_CONFIG_DISABLE
  11357. //////
  11358. // If this config identifier is defined then all CATCH macros are prefixed with CATCH_
  11359. #ifdef CATCH_CONFIG_PREFIX_ALL
  11360. #define CATCH_REQUIRE( ... ) (void)(0)
  11361. #define CATCH_REQUIRE_FALSE( ... ) (void)(0)
  11362. #define CATCH_REQUIRE_THROWS( ... ) (void)(0)
  11363. #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  11364. #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  11365. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11366. #define CATCH_REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11367. #endif// CATCH_CONFIG_DISABLE_MATCHERS
  11368. #define CATCH_REQUIRE_NOTHROW( ... ) (void)(0)
  11369. #define CATCH_CHECK( ... ) (void)(0)
  11370. #define CATCH_CHECK_FALSE( ... ) (void)(0)
  11371. #define CATCH_CHECKED_IF( ... ) if (__VA_ARGS__)
  11372. #define CATCH_CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  11373. #define CATCH_CHECK_NOFAIL( ... ) (void)(0)
  11374. #define CATCH_CHECK_THROWS( ... ) (void)(0)
  11375. #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  11376. #define CATCH_CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  11377. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11378. #define CATCH_CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11379. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11380. #define CATCH_CHECK_NOTHROW( ... ) (void)(0)
  11381. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11382. #define CATCH_CHECK_THAT( arg, matcher ) (void)(0)
  11383. #define CATCH_REQUIRE_THAT( arg, matcher ) (void)(0)
  11384. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11385. #define CATCH_INFO( msg ) (void)(0)
  11386. #define CATCH_WARN( msg ) (void)(0)
  11387. #define CATCH_CAPTURE( msg ) (void)(0)
  11388. #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11389. #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11390. #define CATCH_METHOD_AS_TEST_CASE( method, ... )
  11391. #define CATCH_REGISTER_TEST_CASE( Function, ... ) (void)(0)
  11392. #define CATCH_SECTION( ... )
  11393. #define CATCH_DYNAMIC_SECTION( ... )
  11394. #define CATCH_FAIL( ... ) (void)(0)
  11395. #define CATCH_FAIL_CHECK( ... ) (void)(0)
  11396. #define CATCH_SUCCEED( ... ) (void)(0)
  11397. #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11398. // "BDD-style" convenience wrappers
  11399. #define CATCH_SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11400. #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 )
  11401. #define CATCH_GIVEN( desc )
  11402. #define CATCH_AND_GIVEN( desc )
  11403. #define CATCH_WHEN( desc )
  11404. #define CATCH_AND_WHEN( desc )
  11405. #define CATCH_THEN( desc )
  11406. #define CATCH_AND_THEN( desc )
  11407. #define CATCH_STATIC_REQUIRE( ... ) (void)(0)
  11408. #define CATCH_STATIC_REQUIRE_FALSE( ... ) (void)(0)
  11409. // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required
  11410. #else
  11411. #define REQUIRE( ... ) (void)(0)
  11412. #define REQUIRE_FALSE( ... ) (void)(0)
  11413. #define REQUIRE_THROWS( ... ) (void)(0)
  11414. #define REQUIRE_THROWS_AS( expr, exceptionType ) (void)(0)
  11415. #define REQUIRE_THROWS_WITH( expr, matcher ) (void)(0)
  11416. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11417. #define REQUIRE_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11418. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11419. #define REQUIRE_NOTHROW( ... ) (void)(0)
  11420. #define CHECK( ... ) (void)(0)
  11421. #define CHECK_FALSE( ... ) (void)(0)
  11422. #define CHECKED_IF( ... ) if (__VA_ARGS__)
  11423. #define CHECKED_ELSE( ... ) if (!(__VA_ARGS__))
  11424. #define CHECK_NOFAIL( ... ) (void)(0)
  11425. #define CHECK_THROWS( ... ) (void)(0)
  11426. #define CHECK_THROWS_AS( expr, exceptionType ) (void)(0)
  11427. #define CHECK_THROWS_WITH( expr, matcher ) (void)(0)
  11428. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11429. #define CHECK_THROWS_MATCHES( expr, exceptionType, matcher ) (void)(0)
  11430. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11431. #define CHECK_NOTHROW( ... ) (void)(0)
  11432. #if !defined(CATCH_CONFIG_DISABLE_MATCHERS)
  11433. #define CHECK_THAT( arg, matcher ) (void)(0)
  11434. #define REQUIRE_THAT( arg, matcher ) (void)(0)
  11435. #endif // CATCH_CONFIG_DISABLE_MATCHERS
  11436. #define INFO( msg ) (void)(0)
  11437. #define WARN( msg ) (void)(0)
  11438. #define CAPTURE( msg ) (void)(0)
  11439. #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11440. #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11441. #define METHOD_AS_TEST_CASE( method, ... )
  11442. #define REGISTER_TEST_CASE( Function, ... ) (void)(0)
  11443. #define SECTION( ... )
  11444. #define DYNAMIC_SECTION( ... )
  11445. #define FAIL( ... ) (void)(0)
  11446. #define FAIL_CHECK( ... ) (void)(0)
  11447. #define SUCCEED( ... ) (void)(0)
  11448. #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ))
  11449. #define STATIC_REQUIRE( ... ) (void)(0)
  11450. #define STATIC_REQUIRE_FALSE( ... ) (void)(0)
  11451. #endif
  11452. #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION_NO_REG( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature )
  11453. // "BDD-style" convenience wrappers
  11454. #define SCENARIO( ... ) INTERNAL_CATCH_TESTCASE_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ) )
  11455. #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TESTCASE_METHOD_NO_REGISTRATION(INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), className )
  11456. #define GIVEN( desc )
  11457. #define AND_GIVEN( desc )
  11458. #define WHEN( desc )
  11459. #define AND_WHEN( desc )
  11460. #define THEN( desc )
  11461. #define AND_THEN( desc )
  11462. using Catch::Detail::Approx;
  11463. #endif
  11464. #endif // ! CATCH_CONFIG_IMPL_ONLY
  11465. // start catch_reenable_warnings.h
  11466. #ifdef __clang__
  11467. # ifdef __ICC // icpc defines the __clang__ macro
  11468. # pragma warning(pop)
  11469. # else
  11470. # pragma clang diagnostic pop
  11471. # endif
  11472. #elif defined __GNUC__
  11473. # pragma GCC diagnostic pop
  11474. #endif
  11475. // end catch_reenable_warnings.h
  11476. // end catch.hpp
  11477. #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED